diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 64f05a07863..99e84273c32 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -21,6 +21,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu .link_libc = true, }); hip_test_module.addOptions("hip_fixtures", hip_fixtures); + hip_test_module.addImport("hip_kernels", b.createModule(.{ .root_source_file = b.addWriteFiles().add("kernels.zig", stub) })); const hip_tests = b.addTest(.{ .root_module = hip_test_module }); const run_hip_tests = b.addRunArtifact(hip_tests); test_step.dependOn(&run_hip_tests.step); @@ -63,4 +64,54 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const affine_test = b.addTest(.{ .root_module = affine_module }); b.step("hip-affine-build", "Compile affine golden GPU test without executing").dependOn(&affine_test.step); b.step("hip-affine-test", "Run exact affine golden GPU regression").dependOn(&b.addRunArtifact(affine_test).step); + const device_lib = b.option([]const u8, "hip-device-lib", "ROCm device bitcode directory (default /lib/llvm/amdgcn/bitcode; Arch: /amdgcn/bitcode)"); + const objects = kernelObjects(b, hipcc, hipcc_resolved, device_lib, hip_arch); + const kernel_module = b.createModule(.{ .root_source_file = b.path("zig/src/hip/kernel_tests.zig"), .target = target, .link_libc = true }); + kernel_module.addIncludePath(.{ .cwd_relative = hip_include }); + kernel_module.addCSourceFile(.{ .file = b.path("zig/src/hip/device_arch.c"), .flags = &.{"-D__HIP_PLATFORM_AMD__"} }); + kernel_module.addImport("hip_kernels", objects); + const kernel_test = b.addTest(.{ .root_module = kernel_module }); + b.step("hip-kernel-build", "Compile the model-free kernels and their GPU tests without running them").dependOn(&kernel_test.step); + b.step("hip-kernel-test", "Every model-free kernel against its host reference on the GPU").dependOn(&b.addRunArtifact(kernel_test).step); +} + +/// The model-free kernels' source groups, in zig/src/hip/kernels.zig's Group order. +const groups = [_][]const u8{ "ops/ops.hip", "ops/act.hip", "attention/attention.hip", "recurrence/gated_delta.hip", "attention/prefill.hip", "decode/decode.hip", "decode/plan.hip" }; + +/// What the group sources include, so an edit to one rebuilds them. +const headers = [_][]const u8{ "attention/attention_fa.hip", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", "ops/draw.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", "ops/norms.hpp", "ops/rope.hpp" }; + +/// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20. +const flags = [_][]const u8{ "-D__HIP_PLATFORM_AMD__=1", "-DUSE_ROCM=1", "-DHIPBLAS_V2", "-fPIC", "-DCUDA_HAS_FP16=1", "-DHIP_ENABLE_WARP_SYNC_BUILTINS=1", "-std=c++20", "-fno-gpu-rdc", "-mno-wavefrontsize64", "-ffp-contract=off" }; + +const stub = "pub const arch = \"\";\npub const images: [7][]align(8) const u8 = @splat(&.{});\n"; + +/// One code object a group for `arch`, built with the caps table's instruction switches, as the `hip_kernels` module. +fn kernelObjects(b: *std.Build, hipcc: []const u8, hipcc_resolved: []const u8, device_lib: ?[]const u8, arch: []const u8) *std.Build.Module { + const c = caps.Caps.of(arch).?; + const root = std.fs.path.dirname(std.fs.path.dirname(hipcc_resolved) orelse ".") orelse "."; + const files = b.addWriteFiles(); + var decls: []const u8 = ""; + var refs: []const u8 = ""; + for (groups, 0..) |source, i| { + const run = b.addSystemCommand(&.{ hipcc, "--genco" }); + run.addArgs(&flags); + run.addArg(b.fmt("-DTF_WAVE={d}", .{c.wave})); + run.addArg(b.fmt("-DTF_DOT2_F16={d}", .{@intFromBool(c.dot2_f16)})); + run.addArg(b.fmt("-DTF_DOT2_BF16={d}", .{@intFromBool(c.dot2_bf16)})); + run.addArg(b.fmt("-DTF_SDOT4={d}", .{@intFromBool(c.sdot4)})); + run.addArg(b.fmt("-DTF_SDOT8={d}", .{@intFromBool(c.sdot8)})); + run.addArg(b.fmt("--rocm-path={s}", .{root})); + run.addArg(b.fmt("--rocm-device-lib-path={s}", .{device_lib orelse b.fmt("{s}/lib/llvm/amdgcn/bitcode", .{root})})); + run.addArg(b.fmt("--offload-arch={s}", .{arch})); + run.addPrefixedDirectoryArg("-I", b.path("zig/kernels/hip")); + for (headers) |h| run.addFileInput(b.path(b.fmt("zig/kernels/hip/{s}", .{h}))); + run.addArg("-o"); + const object = run.addOutputFileArg(b.fmt("group{d}.hsaco", .{i})); + run.addFileArg(b.path(b.fmt("zig/kernels/hip/{s}", .{source}))); + _ = files.addCopyFile(object, b.fmt("group{d}.hsaco", .{i})); + decls = b.fmt("{s}const g{d} align(8) = @embedFile(\"group{d}.hsaco\").*;\n", .{ decls, i, i }); + refs = b.fmt("{s}&g{d}, ", .{ refs, i }); + } + return b.createModule(.{ .root_source_file = files.add("kernels.zig", b.fmt("pub const arch = \"{s}\";\n{s}pub const images = [_][]align(8) const u8{{ {s}}};\n", .{ arch, decls, refs })) }); } diff --git a/zig/kernels/hip/attention/attention.hip b/zig/kernels/hip/attention/attention.hip new file mode 100644 index 00000000000..e4c8afa2c8f --- /dev/null +++ b/zig/kernels/hip/attention/attention.hip @@ -0,0 +1,236 @@ +// Causal attention, fp32 scores and softmax; KV heads are read as head / (heads / kv_heads), never repeated. + +#include +#include +#include + +#include "attention_fa.hip" + +namespace tf { +namespace rocm { + +__device__ float lane0_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +template +__device__ float row_dot(const float* qreg, const Cache* row, int d, int lane) { + float partial = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) partial += qreg[i] * static_cast(row[idx]); + } + return lane0_sum(partial); +} + +template +__global__ void __launch_bounds__(32) +causal_kernel(const float* __restrict__ q, const Cache* __restrict__ k, const Cache* __restrict__ v, + float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, float scale, int q_pos0, + long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, long long v_ss) { + int qi = blockIdx.x; + int head = blockIdx.y; + int batch = blockIdx.z; + if (qi >= qlen) return; + int lane = threadIdx.x; + int kv = head / (heads / kv_heads); + int visible = q_pos0 + qi + 1; + if (visible > span) visible = span; + + const float* qrow = q + ((static_cast(batch) * heads + head) * qlen + qi) * d; + float qreg[8] = {}; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) qreg[i] = qrow[idx]; + } + + const Cache* kbase = k + batch * k_sb + kv * k_sh; + const Cache* vbase = v + batch * v_sb + kv * v_sh; + float max_score = -INFINITY; + for (int key = 0; key < visible; ++key) { + float score = row_dot(qreg, kbase + key * k_ss, d, lane) * scale; + max_score = fmaxf(max_score, score); + } + float denom = 0.f; + for (int key = 0; key < visible; ++key) { + float score = row_dot(qreg, kbase + key * k_ss, d, lane) * scale; + denom += expf(score - max_score); + } + float acc[8] = {}; + for (int key = 0; key < visible; ++key) { + float score = row_dot(qreg, kbase + key * k_ss, d, lane) * scale; + float weight = expf(score - max_score) / denom; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) acc[i] += weight * static_cast((vbase + key * v_ss)[idx]); + } + } + float* orow = out + ((static_cast(batch) * heads + head) * qlen + qi) * d; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) orow[idx] = acc[i]; + } +} + +} // namespace rocm +} // namespace tf + +// Decode: a warp scores a key, a block per head reduces the softmax, then V streams in 128-key tiles. +template +__global__ void score_keys(const float* __restrict__ q, const Cache* __restrict__ k, float* __restrict__ scores, + int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos) { + if (pos != nullptr) visible = min(pos[blockIdx.z] + 1, span); + int lane = threadIdx.x & 31; + int key = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + int head = blockIdx.y; + int batch = blockIdx.z; + const float* qrow = q + (static_cast(batch) * heads + head) * d; + float qreg[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + qreg[i] = idx < d ? qrow[idx] : 0.f; + } + float partial = 0.f; + if (key < visible) { + int kv = head / (heads / kv_heads); + const Cache* krow = k + batch * k_sb + static_cast(kv) * k_sh + static_cast(key) * k_ss; +#pragma unroll + for (int i = 0; i < 8; ++i) { + int idx = lane + i * 32; + if (idx < d) partial += qreg[i] * static_cast(krow[idx]); + } + } + float dot = tf::rocm::lane0_sum(partial); + if (lane == 0 && key < span) { + float score = key < visible ? dot * scale : -INFINITY; + scores[(static_cast(batch) * heads + head) * span + key] = score; + } +} + +extern "C" __global__ void tf_softmax_stats(const float* __restrict__ scores, float* __restrict__ stats, int span, + int visible, const int* pos) { + if (pos != nullptr) visible = min(pos[blockIdx.y] + 1, span); + int head = blockIdx.x; + int batch = blockIdx.y; + const float* row = scores + (static_cast(batch) * gridDim.x + head) * span; + float local = -INFINITY; + for (int i = threadIdx.x; i < visible; i += blockDim.x) local = fmaxf(local, row[i]); + __shared__ float buf[256]; + buf[threadIdx.x] = local; + __syncthreads(); + for (int step = blockDim.x >> 1; step > 0; step >>= 1) { + if (threadIdx.x < step) buf[threadIdx.x] = fmaxf(buf[threadIdx.x], buf[threadIdx.x + step]); + __syncthreads(); + } + float max_score = buf[0]; + __syncthreads(); + local = 0.f; + for (int i = threadIdx.x; i < visible; i += blockDim.x) local += expf(row[i] - max_score); + buf[threadIdx.x] = local; + __syncthreads(); + for (int step = blockDim.x >> 1; step > 0; step >>= 1) { + if (threadIdx.x < step) buf[threadIdx.x] += buf[threadIdx.x + step]; + __syncthreads(); + } + if (threadIdx.x == 0) { + float* dest = stats + (static_cast(batch) * gridDim.x + head) * 2; + dest[0] = max_score; + dest[1] = buf[0]; + } +} + +template +__global__ void apply_values(const float* __restrict__ scores, const float* __restrict__ stats, + const Cache* __restrict__ v, float* __restrict__ partials, int span, int heads, + int kv_heads, int d, int visible, long long v_sb, long long v_sh, long long v_ss, + const int* pos) { + if (pos != nullptr) visible = min(pos[blockIdx.z] + 1, span); + int tile = blockIdx.x; + int head = blockIdx.y; + int batch = blockIdx.z; + int lane = threadIdx.x; + int key0 = tile * 128; + if (lane >= d) return; + if (key0 >= visible) { // a tile past the keys in use (the graph's grid covers the whole cache) adds zero + partials[(((static_cast(batch) * heads + head) * gridDim.x) + tile) * d + lane] = 0.f; + return; + } + int kv = head / (heads / kv_heads); + const float* row = scores + (static_cast(batch) * heads + head) * span; + float max_score = stats[(static_cast(batch) * heads + head) * 2]; + float denom = stats[(static_cast(batch) * heads + head) * 2 + 1]; + const Cache* base = v + batch * v_sb + static_cast(kv) * v_sh + lane; + float acc = 0.f; + int stop = key0 + 128; + if (stop > visible) stop = visible; + for (int key = key0; key < stop; ++key) { + float weight = expf(row[key] - max_score) / denom; + acc += weight * static_cast(base[static_cast(key) * v_ss]); + } + int tiles = gridDim.x; + partials[(((static_cast(batch) * heads + head) * tiles) + tile) * d + lane] = acc; +} + +extern "C" __global__ void tf_sum_partials(const float* __restrict__ partials, float* __restrict__ out, int tiles, + int d) { + int head = blockIdx.x; + int batch = blockIdx.y; + int lane = threadIdx.x; + if (lane >= d) return; + const float* col = partials + ((static_cast(batch) * gridDim.x + head) * tiles) * d + lane; + float acc = 0.f; + for (int tile = 0; tile < tiles; ++tile) acc += col[static_cast(tile) * d]; + out[(static_cast(batch) * gridDim.x + head) * d + lane] = acc; +} + +// The template kernels launches.zig resolves. +template __global__ void tf::rocm::causal_kernel<__half>(const float* __restrict__ q, const __half* __restrict__ k, + const __half* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); +template __global__ void tf::rocm::causal_kernel(const float* __restrict__ q, + const hip_bfloat16* __restrict__ k, const hip_bfloat16* __restrict__ v, float* __restrict__ out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, + long long v_sb, long long v_sh, long long v_ss); +template __global__ void tf::rocm::causal_kernel(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); +template __global__ void score_keys<__half>(const float* __restrict__ q, const __half* __restrict__ k, + float* __restrict__ scores, int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos); +template __global__ void score_keys(const float* __restrict__ q, const hip_bfloat16* __restrict__ k, + float* __restrict__ scores, int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos); +template __global__ void score_keys(const float* __restrict__ q, const float* __restrict__ k, + float* __restrict__ scores, int span, int heads, int kv_heads, int d, float scale, int visible, long long k_sb, + long long k_sh, long long k_ss, const int* pos); +template __global__ void apply_values<__half>(const float* __restrict__ scores, const float* __restrict__ stats, + const __half* __restrict__ v, float* __restrict__ partials, int span, int heads, int kv_heads, int d, int visible, + long long v_sb, long long v_sh, long long v_ss, const int* pos); +template __global__ void apply_values(const float* __restrict__ scores, const float* __restrict__ stats, + const hip_bfloat16* __restrict__ v, float* __restrict__ partials, int span, int heads, int kv_heads, int d, + int visible, long long v_sb, long long v_sh, long long v_ss, const int* pos); +template __global__ void apply_values(const float* __restrict__ scores, const float* __restrict__ stats, + const float* __restrict__ v, float* __restrict__ partials, int span, int heads, int kv_heads, int d, int visible, + long long v_sb, long long v_sh, long long v_ss, const int* pos); +template __global__ void tf::rocm::fa_prefill<__half, 64>(const float* __restrict__ q, const __half* __restrict__ k, + const __half* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); +template __global__ void tf::rocm::fa_prefill(const float* __restrict__ q, + const hip_bfloat16* __restrict__ k, const hip_bfloat16* __restrict__ v, float* __restrict__ out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, + long long v_sb, long long v_sh, long long v_ss); +template __global__ void tf::rocm::fa_prefill(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, + float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss); diff --git a/zig/kernels/hip/attention/attention_fa.hip b/zig/kernels/hip/attention/attention_fa.hip new file mode 100644 index 00000000000..f5bb6baca22 --- /dev/null +++ b/zig/kernels/hip/attention/attention_fa.hip @@ -0,0 +1,462 @@ +// Flash Attention 2 prefill: a block owns 16 query rows and walks the keys in order with an online softmax. + +#include +#include +#include + +#include + +namespace tf { +namespace rocm { + +constexpr int kFaThreads = 256; +constexpr int kFaBc = 32; +constexpr int kFaMaxD = 256; + +// The query stays fp32 and the keys widen in the product: dot2 would round the query. +template +using fa_q_t = float; + +__device__ __forceinline__ __half fa_store(__half, float x) { return __float2half(x); } +__device__ __forceinline__ hip_bfloat16 fa_store(hip_bfloat16, float x) { return hip_bfloat16(x); } +__device__ __forceinline__ float fa_store(float, float x) { return x; } + +template +__host__ __device__ constexpr int fa_ld() { + // Pad so 32 keys at one column sit in 32 different banks. The row itself stays contiguous. + return sizeof(T) == 4 ? 257 : 258; +} + +template +__device__ __forceinline__ float fa_dot_half(const __half* q, const __half* k) { + const __half2* qq = reinterpret_cast(q); + const __half2* kk = reinterpret_cast(k); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; +#pragma unroll 8 + for (int p = 0; p < D / 2; p += 4) { + a0 = __builtin_amdgcn_fdot2(qq[p], kk[p], a0, false); + a1 = __builtin_amdgcn_fdot2(qq[p + 1], kk[p + 1], a1, false); + a2 = __builtin_amdgcn_fdot2(qq[p + 2], kk[p + 2], a2, false); + a3 = __builtin_amdgcn_fdot2(qq[p + 3], kk[p + 3], a3, false); + } + return (a0 + a1) + (a2 + a3); +} + +__device__ __forceinline__ float fa_dot_half(const __half* q, const __half* k, int d) { + const __half2* qq = reinterpret_cast(q); + const __half2* kk = reinterpret_cast(k); + int pairs = d >> 1; + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + int p = 0; + for (; p + 4 <= pairs; p += 4) { + a0 = __builtin_amdgcn_fdot2(qq[p], kk[p], a0, false); + a1 = __builtin_amdgcn_fdot2(qq[p + 1], kk[p + 1], a1, false); + a2 = __builtin_amdgcn_fdot2(qq[p + 2], kk[p + 2], a2, false); + a3 = __builtin_amdgcn_fdot2(qq[p + 3], kk[p + 3], a3, false); + } + float acc = (a0 + a1) + (a2 + a3); + for (; p < pairs; ++p) acc = __builtin_amdgcn_fdot2(qq[p], kk[p], acc, false); + return acc; +} + +template +__device__ __forceinline__ void fa_dot_bf2(const float* q0, const float* q1, const hip_bfloat16* k, float& acc0, + float& acc1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; +#pragma unroll 8 + for (int dim = 0; dim < D; dim += 4) { + float k0 = static_cast(k[dim]); + float k1 = static_cast(k[dim + 1]); + float k2 = static_cast(k[dim + 2]); + float k3 = static_cast(k[dim + 3]); + a0 = fmaf(q0[dim], k0, a0); + b0 = fmaf(q1[dim], k0, b0); + a1 = fmaf(q0[dim + 1], k1, a1); + b1 = fmaf(q1[dim + 1], k1, b1); + a2 = fmaf(q0[dim + 2], k2, a2); + b2 = fmaf(q1[dim + 2], k2, b2); + a3 = fmaf(q0[dim + 3], k3, a3); + b3 = fmaf(q1[dim + 3], k3, b3); + } + acc0 = (a0 + a1) + (a2 + a3); + acc1 = (b0 + b1) + (b2 + b3); +} + +template +__device__ __forceinline__ float fa_dot_bf(const float* q, const hip_bfloat16* k) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; +#pragma unroll 8 + for (int dim = 0; dim < D; dim += 4) { + a0 = fmaf(q[dim], static_cast(k[dim]), a0); + a1 = fmaf(q[dim + 1], static_cast(k[dim + 1]), a1); + a2 = fmaf(q[dim + 2], static_cast(k[dim + 2]), a2); + a3 = fmaf(q[dim + 3], static_cast(k[dim + 3]), a3); + } + return (a0 + a1) + (a2 + a3); +} + +__device__ __forceinline__ float fa_dot_bf(const float* q, const hip_bfloat16* k, int d) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + int dim = 0; + for (; dim + 4 <= d; dim += 4) { + a0 = fmaf(q[dim], static_cast(k[dim]), a0); + a1 = fmaf(q[dim + 1], static_cast(k[dim + 1]), a1); + a2 = fmaf(q[dim + 2], static_cast(k[dim + 2]), a2); + a3 = fmaf(q[dim + 3], static_cast(k[dim + 3]), a3); + } + float acc = (a0 + a1) + (a2 + a3); + for (; dim < d; ++dim) acc = fmaf(q[dim], static_cast(k[dim]), acc); + return acc; +} + +template +__device__ __forceinline__ float fa_dot_f(const float* q, const float* k) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; +#pragma unroll 8 + for (int dim = 0; dim < D; dim += 4) { + a0 = fmaf(q[dim], k[dim], a0); + a1 = fmaf(q[dim + 1], k[dim + 1], a1); + a2 = fmaf(q[dim + 2], k[dim + 2], a2); + a3 = fmaf(q[dim + 3], k[dim + 3], a3); + } + return (a0 + a1) + (a2 + a3); +} + +__device__ __forceinline__ float fa_dot_f(const float* q, const float* k, int d) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + int dim = 0; + for (; dim + 4 <= d; dim += 4) { + a0 = fmaf(q[dim], k[dim], a0); + a1 = fmaf(q[dim + 1], k[dim + 1], a1); + a2 = fmaf(q[dim + 2], k[dim + 2], a2); + a3 = fmaf(q[dim + 3], k[dim + 3], a3); + } + float acc = (a0 + a1) + (a2 + a3); + for (; dim < d; ++dim) acc = fmaf(q[dim], k[dim], acc); + return acc; +} + +template +__device__ __forceinline__ float fa_qk(const __half* q, const __half* k, int d) { + if constexpr (DSpec == 256) return fa_dot_half<256>(q, k); + return fa_dot_half(q, k, d); +} + +template +__device__ __forceinline__ float fa_qk(const float* q, const hip_bfloat16* k, int d) { + if constexpr (DSpec == 256) return fa_dot_bf<256>(q, k); + return fa_dot_bf(q, k, d); +} + +template +__device__ __forceinline__ float fa_qk(const float* q, const float* k, int d) { + if constexpr (DSpec == 256) return fa_dot_f<256>(q, k); + return fa_dot_f(q, k, d); +} + +template +__device__ __forceinline__ void fa_pair_half(const __half* q, const __half* k0, const __half* k1, int d, float& s0, + float& s1) { + const __half2* qq = reinterpret_cast(q); + const __half2* a = reinterpret_cast(k0); + const __half2* b = reinterpret_cast(k1); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int pairs = d >> 1; + int p = 0; +#pragma unroll 8 + for (; p + 4 <= pairs; p += 4) { + __half2 q0 = qq[p]; + __half2 q1 = qq[p + 1]; + __half2 q2 = qq[p + 2]; + __half2 q3 = qq[p + 3]; + a0 = __builtin_amdgcn_fdot2(q0, a[p], a0, false); + a1 = __builtin_amdgcn_fdot2(q1, a[p + 1], a1, false); + a2 = __builtin_amdgcn_fdot2(q2, a[p + 2], a2, false); + a3 = __builtin_amdgcn_fdot2(q3, a[p + 3], a3, false); + if constexpr (Bc == 64) { + b0 = __builtin_amdgcn_fdot2(q0, b[p], b0, false); + b1 = __builtin_amdgcn_fdot2(q1, b[p + 1], b1, false); + b2 = __builtin_amdgcn_fdot2(q2, b[p + 2], b2, false); + b3 = __builtin_amdgcn_fdot2(q3, b[p + 3], b3, false); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; p < pairs; ++p) { + __half2 qv = qq[p]; + s0 = __builtin_amdgcn_fdot2(qv, a[p], s0, false); + if constexpr (Bc == 64) s1 = __builtin_amdgcn_fdot2(qv, b[p], s1, false); + } +} + +template +__device__ __forceinline__ void fa_pair_hf(const float* q, const __half* k0, const __half* k1, int d, float& s0, + float& s1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int dim = 0; +#pragma unroll 8 + for (; dim + 4 <= d; dim += 4) { + float q0 = q[dim]; + float q1 = q[dim + 1]; + float q2 = q[dim + 2]; + float q3 = q[dim + 3]; + a0 = fmaf(q0, __half2float(k0[dim]), a0); + a1 = fmaf(q1, __half2float(k0[dim + 1]), a1); + a2 = fmaf(q2, __half2float(k0[dim + 2]), a2); + a3 = fmaf(q3, __half2float(k0[dim + 3]), a3); + if constexpr (Bc == 64) { + b0 = fmaf(q0, __half2float(k1[dim]), b0); + b1 = fmaf(q1, __half2float(k1[dim + 1]), b1); + b2 = fmaf(q2, __half2float(k1[dim + 2]), b2); + b3 = fmaf(q3, __half2float(k1[dim + 3]), b3); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; dim < d; ++dim) { + s0 = fmaf(q[dim], __half2float(k0[dim]), s0); + if constexpr (Bc == 64) s1 = fmaf(q[dim], __half2float(k1[dim]), s1); + } +} + +template +__device__ __forceinline__ void fa_pair_bf(const float* q, const hip_bfloat16* k0, const hip_bfloat16* k1, int d, + float& s0, float& s1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int dim = 0; +#pragma unroll 8 + for (; dim + 4 <= d; dim += 4) { + float q0 = q[dim]; + float q1 = q[dim + 1]; + float q2 = q[dim + 2]; + float q3 = q[dim + 3]; + a0 = fmaf(q0, static_cast(k0[dim]), a0); + a1 = fmaf(q1, static_cast(k0[dim + 1]), a1); + a2 = fmaf(q2, static_cast(k0[dim + 2]), a2); + a3 = fmaf(q3, static_cast(k0[dim + 3]), a3); + if constexpr (Bc == 64) { + b0 = fmaf(q0, static_cast(k1[dim]), b0); + b1 = fmaf(q1, static_cast(k1[dim + 1]), b1); + b2 = fmaf(q2, static_cast(k1[dim + 2]), b2); + b3 = fmaf(q3, static_cast(k1[dim + 3]), b3); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; dim < d; ++dim) { + s0 = fmaf(q[dim], static_cast(k0[dim]), s0); + if constexpr (Bc == 64) s1 = fmaf(q[dim], static_cast(k1[dim]), s1); + } +} + +template +__device__ __forceinline__ void fa_pair_f(const float* q, const float* k0, const float* k1, int d, float& s0, + float& s1) { + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + float b0 = 0.f, b1 = 0.f, b2 = 0.f, b3 = 0.f; + int dim = 0; +#pragma unroll 8 + for (; dim + 4 <= d; dim += 4) { + float q0 = q[dim]; + float q1 = q[dim + 1]; + float q2 = q[dim + 2]; + float q3 = q[dim + 3]; + a0 = fmaf(q0, k0[dim], a0); + a1 = fmaf(q1, k0[dim + 1], a1); + a2 = fmaf(q2, k0[dim + 2], a2); + a3 = fmaf(q3, k0[dim + 3], a3); + if constexpr (Bc == 64) { + b0 = fmaf(q0, k1[dim], b0); + b1 = fmaf(q1, k1[dim + 1], b1); + b2 = fmaf(q2, k1[dim + 2], b2); + b3 = fmaf(q3, k1[dim + 3], b3); + } + } + s0 = (a0 + a1) + (a2 + a3); + s1 = (b0 + b1) + (b2 + b3); + for (; dim < d; ++dim) { + s0 = fmaf(q[dim], k0[dim], s0); + if constexpr (Bc == 64) s1 = fmaf(q[dim], k1[dim], s1); + } +} + +template +__device__ void fa_load_tile(Cache* dst, const Cache* src, int k0, int span, int d, long long stride, int tid) { + constexpr int ld = fa_ld(); + const bool vec8 = sizeof(Cache) == 2 && (d % 8) == 0 && (stride % 8) == 0 && + (reinterpret_cast(src) & 15u) == 0; + if (vec8) { + int chunks = d >> 3; + for (int e = tid; e < Bc * chunks; e += kFaThreads) { + int key = e / chunks; + int chunk = e - key * chunks; + unsigned bits0 = 0, bits1 = 0, bits2 = 0, bits3 = 0; + if (k0 + key < span) { + const unsigned* g = reinterpret_cast( + src + (static_cast(k0 + key) * stride) + chunk * 8); + bits0 = g[0]; + bits1 = g[1]; + bits2 = g[2]; + bits3 = g[3]; + } + unsigned* slot = reinterpret_cast(dst + key * ld + chunk * 8); + slot[0] = bits0; + slot[1] = bits1; + slot[2] = bits2; + slot[3] = bits3; + } + return; + } + for (int e = tid; e < Bc * d; e += kFaThreads) { + int key = e / d; + int dim = e - key * d; + float raw = 0.f; + if (k0 + key < span) raw = static_cast(src[(static_cast(k0 + key) * stride) + dim]); + dst[key * ld + dim] = fa_store(Cache{}, raw); + } +} + +template +__global__ void __launch_bounds__(kFaThreads, 1) +fa_prefill(const float* __restrict__ q, const Cache* __restrict__ k, const Cache* __restrict__ v, + float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, float scale, int q_pos0, + long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, long long v_ss) { + constexpr int kBr = 16; + constexpr int kWarps = kFaThreads / 32; + constexpr int kQLd = fa_ld>(); + constexpr int kKLd = fa_ld(); + __shared__ alignas(16) fa_q_t sQ[kBr * kQLd]; + __shared__ alignas(16) Cache sK[Bc * kKLd]; + __shared__ float sP[kBr * Bc]; + __shared__ float sM[kBr]; + __shared__ float sL[kBr]; + __shared__ float sA[kBr]; + + int q0 = blockIdx.x * kBr; + int head = blockIdx.y; + int batch = blockIdx.z; + if (q0 >= qlen) return; + int tid = threadIdx.x; + int warp = tid >> 5; + int lane = tid & 31; + int q_hi = qlen - q0; + if (q_hi > kBr) q_hi = kBr; + int max_vis = q_pos0 + q0 + q_hi; + if (max_vis > span) max_vis = span; + int kv = head / (heads / kv_heads); + + const float* qrows = q + ((static_cast(batch) * heads + head) * qlen + q0) * d; + float* orows = out + ((static_cast(batch) * heads + head) * qlen + q0) * d; + const Cache* kbase = k + static_cast(batch) * k_sb + static_cast(kv) * k_sh; + const Cache* vbase = v + static_cast(batch) * v_sb + static_cast(kv) * v_sh; + + for (int e = tid; e < kBr * d; e += kFaThreads) { + int row = e / d; + int dim = e - row * d; + sQ[row * kQLd + dim] = row < q_hi ? qrows[row * d + dim] : 0.f; + } + float oreg[kBr]; +#pragma unroll + for (int row = 0; row < kBr; ++row) oreg[row] = 0.f; + if (tid < kBr) { + sM[tid] = -INFINITY; + sL[tid] = 0.f; + sA[tid] = 1.f; + } + __syncthreads(); + + for (int k0 = 0; k0 < max_vis; k0 += Bc) { + fa_load_tile(sK, kbase, k0, span, d, k_ss, tid); + __syncthreads(); +#pragma unroll 1 + for (int iter = 0; iter < kBr / kWarps; ++iter) { + int row = warp + iter * kWarps; + float s0 = 0.f, s1 = 0.f; + if (row < q_hi) { + const Cache* key0 = sK + lane * kKLd; + const Cache* key1 = Bc == 64 ? sK + (lane + 32) * kKLd : key0; + if constexpr (std::is_same_v) + fa_pair_hf(sQ + row * kQLd, key0, key1, d, s0, s1); + else if constexpr (std::is_same_v) + fa_pair_bf(sQ + row * kQLd, key0, key1, d, s0, s1); + else + fa_pair_f(sQ + row * kQLd, key0, key1, d, s0, s1); + s0 *= scale; + s1 *= scale; + int vis = q_pos0 + q0 + row + 1; + if (vis > span) vis = span; + if (k0 + lane >= vis) s0 = -INFINITY; + if (k0 + lane + 32 >= vis) s1 = -INFINITY; + } + if (row < kBr) { + sP[row * Bc + lane] = s0; + if constexpr (Bc == 64) sP[row * Bc + lane + 32] = s1; + } + } + __syncthreads(); + if (tid < kBr) { + int row = tid; + if (row >= q_hi) { + sA[row] = 1.f; + for (int key = 0; key < Bc; ++key) sP[row * Bc + key] = 0.f; + } else { + float tile_max = -INFINITY; + bool any = false; + for (int key = 0; key < Bc; ++key) { + float score = sP[row * Bc + key]; + if (score != -INFINITY) { + tile_max = fmaxf(tile_max, score); + any = true; + } + } + if (!any) { + sA[row] = 1.f; + for (int key = 0; key < Bc; ++key) sP[row * Bc + key] = 0.f; + } else { + float next_m = fmaxf(sM[row], tile_max); + float alpha = sM[row] == -INFINITY ? 0.f : expf(sM[row] - next_m); + float sum = 0.f; + for (int key = 0; key < Bc; ++key) { + float score = sP[row * Bc + key]; + float prob = score == -INFINITY ? 0.f : expf(score - next_m); + sP[row * Bc + key] = prob; + sum += prob; + } + sL[row] = fmaf(alpha, sL[row], sum); + sM[row] = next_m; + sA[row] = alpha; + } + } + } + __syncthreads(); + fa_load_tile(sK, vbase, k0, span, d, v_ss, tid); + __syncthreads(); + if (tid < d) { + float pv[kBr]; +#pragma unroll + for (int row = 0; row < kBr; ++row) pv[row] = 0.f; + for (int key = 0; key < Bc; ++key) { + float vv = static_cast(sK[key * kKLd + tid]); +#pragma unroll + for (int row = 0; row < kBr; ++row) pv[row] = fmaf(sP[row * Bc + key], vv, pv[row]); + } +#pragma unroll + for (int row = 0; row < kBr; ++row) oreg[row] = fmaf(sA[row], oreg[row], pv[row]); + } + __syncthreads(); + } + + if (tid < d) { + for (int row = 0; row < q_hi; ++row) { + float inv = sL[row] == 0.f ? 0.f : 1.f / sL[row]; + orows[row * d + tid] = oreg[row] * inv; + } + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/attention/prefill.hip b/zig/kernels/hip/attention/prefill.hip new file mode 100644 index 00000000000..87e39f57d46 --- /dev/null +++ b/zig/kernels/hip/attention/prefill.hip @@ -0,0 +1,278 @@ +// Prefill attention for long prompts: 64 query rows share a 64-key tile; dot2 products and online softmax in fp32. + +#include +#include +#include + +#include "decode/pages.hpp" + +namespace { + +constexpr int kRows = 64; // query rows a block +constexpr int kKeys = 64; // keys a tile +constexpr int kChunk = 64; // head dimensions a staged key or value chunk +constexpr int kThreads = 256; +static_assert(kKeys == kPageTokens, "a key tile is one page"); + +// A cache element type's pair for dot2, the rounding into it and the product. +template +struct Dot; + +template <> +struct Dot<__half> { + using elem = _Float16; + using pair = _Float16 __attribute__((ext_vector_type(2))); + static __device__ __forceinline__ float dot(pair a, pair b, float acc) { + return __builtin_amdgcn_fdot2(a, b, acc, false); + } +}; + +template <> +struct Dot { + using elem = __bf16; + using pair = __bf16 __attribute__((ext_vector_type(2))); + static __device__ __forceinline__ float dot(pair a, pair b, float acc) { +#if TF_DOT2_BF16 + return __builtin_amdgcn_fdot2_f32_bf16(a, b, acc, false); +#else + // RDNA2 has no bf16 dot2: its caches are fp16, this only keeps the kernel building + return fmaf(static_cast(a.y), static_cast(b.y), fmaf(static_cast(a.x), static_cast(b.x), acc)); +#endif + } +}; + +// A 16-byte LDS read as four pairs. +template +__device__ __forceinline__ void pairs4(const void* at, Pair out[4]) { + const uint4 w = *reinterpret_cast(at); + out[0] = __builtin_bit_cast(Pair, w.x); + out[1] = __builtin_bit_cast(Pair, w.y); + out[2] = __builtin_bit_cast(Pair, w.z); + out[3] = __builtin_bit_cast(Pair, w.w); +} + +// q rounds to the cache type once and stays in LDS; with PAGED, k and v are a layer's pools and a 64-key tile a page. +template +__device__ void fa_dot2(const float* __restrict__ q, const Cache* __restrict__ k, const Cache* __restrict__ v, + float* __restrict__ out, int qlen, int span, int heads, int kv_heads, int d, float scale, + int q_pos0, long long k_sb, long long k_sh, long long k_ss, long long v_sb, long long v_sh, + long long v_ss, const unsigned* table, int count) { + constexpr int kQChunks = 256 / 8; // 16-byte chunks a q row + constexpr int kKChunks = kChunk / 8; // a staged key row's + constexpr int kPLd = kRows + 4; // a key pair's probabilities, row-indexed + __shared__ uint4 sQ[kRows * kQChunks]; + __shared__ uint4 sKV[kKeys * kKChunks]; // a key chunk (key, 8 dims) or a value chunk (key pair, 4 dims) + using T = Dot; + using elem = typename T::elem; + using pair_t = typename T::pair; + __shared__ alignas(16) pair_t sH[kKeys / 2 * kPLd]; + __shared__ float sA[kRows], sL[kRows]; + + const int q0 = blockIdx.x * kRows; + const int head = blockIdx.y; + const int batch = blockIdx.z; + if (q0 >= qlen) return; + const int tid = threadIdx.x; + int q_hi = qlen - q0; + if (q_hi > kRows) q_hi = kRows; + int max_vis = q_pos0 + q0 + q_hi; + if (max_vis > span) max_vis = span; + const int kv = head / (heads / kv_heads); + const float* qrows = q + ((static_cast(batch) * heads + head) * qlen + q0) * d; + float* orows = out + ((static_cast(batch) * heads + head) * qlen + q0) * d; + const Cache* kbase = PAGED ? k : k + static_cast(batch) * k_sb + static_cast(kv) * k_sh; + const Cache* vbase = PAGED ? v : v + static_cast(batch) * v_sb + static_cast(kv) * v_sh; + const long long kstride = PAGED ? d : k_ss; + const long long vstride = PAGED ? d : v_ss; + const int chunks = d / 8; + + for (int e = tid; e < kRows * chunks; e += kThreads) { + const int row = e / chunks, c = e % chunks; + elem h[8]; +#pragma unroll + for (int m = 0; m < 8; ++m) + h[m] = static_cast(row < q_hi ? qrows[static_cast(row) * d + 8 * c + m] : 0.f); + sQ[row * kQChunks + (c ^ (row & 7))] = __builtin_bit_cast(uint4, h); + } + + // scores: rows sr + 16i against keys 4sk .. 4sk + 3; PV: rows pr .. pr + 3 at dims 4pc .. 4pc + 3 of each chunk + const int sr = tid / 16, sk = tid % 16; + const int pr = (tid / 16) * 4, pc = tid % 16; + float m_run[4], l_run[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) m_run[i] = -INFINITY, l_run[i] = 0.f; + float o[4][16]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 16; ++m) o[i][m] = 0.f; + + for (int k0 = 0; k0 < max_vis; k0 += kKeys) { + // the tile's first key row in the keys' and the values' storage + const Cache* ktile = PAGED ? kbase + page_row(table[k0 / kPageTokens], count, kv, 0, d) : kbase + static_cast(k0) * k_ss; + const Cache* vtile = PAGED ? vbase + page_row(table[k0 / kPageTokens], count, kv, 0, d) : vbase + static_cast(k0) * v_ss; + float acc[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] = 0.f; + for (int c0 = 0; c0 < chunks; c0 += kKChunks) { + uint4 staged[2]; +#pragma unroll + for (int t = 0; t < 2; ++t) { + const int e = tid + t * kThreads, key = e / kKChunks, c = e % kKChunks; + staged[t] = k0 + key < span + ? *reinterpret_cast(ktile + static_cast(key) * kstride + 8 * (c0 + c)) + : uint4{0, 0, 0, 0}; + } + __syncthreads(); +#pragma unroll + for (int t = 0; t < 2; ++t) { + const int e = tid + t * kThreads, key = e / kKChunks, c = e % kKChunks; + sKV[key * kKChunks + (c ^ ((key >> 2) & 7))] = staged[t]; + } + __syncthreads(); +#pragma unroll 2 + for (int c = 0; c < kKChunks; ++c) { + pair_t qv[4][4], kf[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = sr + 16 * i; + pairs4(&sQ[row * kQChunks + ((c0 + c) ^ (row & 7))], qv[i]); + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int key = 4 * sk + j; + pairs4(&sKV[key * kKChunks + (c ^ ((key >> 2) & 7))], kf[j]); + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int m = 0; m < 4; ++m) acc[i][j] = T::dot(qv[i][m], kf[j][m], acc[i][j]); + } + } + // the online softmax in registers: a row's 64 keys sit on its 16 lanes +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = sr + 16 * i; + int vis = q_pos0 + q0 + row + 1; + if (vis > span) vis = span; + float tile_max = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + acc[i][j] = (row < q_hi && k0 + 4 * sk + j < vis) ? acc[i][j] * scale : -INFINITY; + tile_max = fmaxf(tile_max, acc[i][j]); + } +#pragma unroll + for (int lane = 8; lane > 0; lane >>= 1) tile_max = fmaxf(tile_max, __shfl_xor(tile_max, lane, 16)); + const float next_m = fmaxf(m_run[i], tile_max); + const float alpha = next_m == -INFINITY ? 1.f : expf(m_run[i] - next_m); + float p[4], sum = 0.f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + p[j] = next_m == -INFINITY ? 0.f : expf(acc[i][j] - next_m); + sum += p[j]; + } +#pragma unroll + for (int lane = 8; lane > 0; lane >>= 1) sum += __shfl_xor(sum, lane, 16); + l_run[i] = alpha * l_run[i] + sum; + m_run[i] = next_m; + sH[(2 * sk) * kPLd + row] = pair_t{static_cast(p[0]), static_cast(p[1])}; + sH[(2 * sk + 1) * kPLd + row] = pair_t{static_cast(p[2]), static_cast(p[3])}; + if (sk == 0) sA[row] = alpha; + } +#pragma unroll + for (int at = 0; at < 256 / kChunk; ++at) { + if (at * kKChunks >= chunks) break; + const int c0 = at * kKChunks; + // a value chunk: key pair `pair`, dims 8g .. 8g + 7 interleaved as (key, key + 1) fp16 pairs + const int pair = tid / kKChunks, g = tid % kKChunks; + const int key = k0 + 2 * pair; + const uint4 a = key < span ? *reinterpret_cast(vtile + static_cast(2 * pair) * vstride + 8 * (c0 + g)) + : uint4{0, 0, 0, 0}; + const uint4 b = key + 1 < span + ? *reinterpret_cast(vtile + static_cast(2 * pair + 1) * vstride + 8 * (c0 + g)) + : uint4{0, 0, 0, 0}; + __syncthreads(); + const elem* ha = reinterpret_cast(&a); + const elem* hb = reinterpret_cast(&b); + pair_t lo[4], hi[4]; +#pragma unroll + for (int m = 0; m < 4; ++m) lo[m] = pair_t{ha[m], hb[m]}, hi[m] = pair_t{ha[4 + m], hb[4 + m]}; + sKV[pair * 16 + 2 * g] = __builtin_bit_cast(uint4, lo); + sKV[pair * 16 + 2 * g + 1] = __builtin_bit_cast(uint4, hi); + __syncthreads(); + float pv[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 4; ++m) pv[i][m] = 0.f; +#pragma unroll 4 + for (int pp = 0; pp < kKeys / 2; ++pp) { + pair_t pr4[4], vv[4]; + pairs4(sH + pp * kPLd + pr, pr4); + pairs4(&sKV[pp * 16 + pc], vv); +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 4; ++m) pv[i][m] = T::dot(pr4[i], vv[m], pv[i][m]); + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int m = 0; m < 4; ++m) { + float& acc_o = o[i][4 * at + m]; + acc_o = fmaf(sA[pr + i], acc_o, pv[i][m]); + } + } + } + if (sk == 0) +#pragma unroll + for (int i = 0; i < 4; ++i) sL[sr + 16 * i] = l_run[i]; + __syncthreads(); +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int row = pr + i; + if (row >= q_hi) continue; + const float inv = sL[row] == 0.f ? 0.f : 1.f / sL[row]; +#pragma unroll + for (int at = 0; at < 256 / kChunk; ++at) { + if (at * kKChunks >= chunks) break; +#pragma unroll + for (int m = 0; m < 4; ++m) + orows[static_cast(row) * d + 64 * at + 4 * pc + m] = o[i][4 * at + m] * inv; + } + } +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_wide_f16(const float* q, const __half* k, const __half* v, float* out, int qlen, int span, int heads, + int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, long long k_ss, + long long v_sb, long long v_sh, long long v_ss) { + fa_dot2<__half, false>(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, k_sb, k_sh, k_ss, v_sb, v_sh, v_ss, nullptr, 0); +} + +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_wide_bf16(const float* q, const hip_bfloat16* k, const hip_bfloat16* v, float* out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, long long k_sb, long long k_sh, + long long k_ss, long long v_sb, long long v_sh, long long v_ss) { + fa_dot2(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, k_sb, k_sh, k_ss, v_sb, + v_sh, v_ss, nullptr, 0); +} + +// The same tile over a stream's pages: `k` and `v` are a layer's pools, `table` the stream's page ids. +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_paged_f16(const float* q, const __half* k, const __half* v, float* out, int qlen, int span, int heads, + int kv_heads, int d, float scale, int q_pos0, const unsigned* table, int count) { + fa_dot2<__half, true>(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, 0, 0, 0, 0, 0, 0, table, count); +} + +extern "C" __global__ void __launch_bounds__(kThreads, 1) +tf_fa_paged_bf16(const float* q, const hip_bfloat16* k, const hip_bfloat16* v, float* out, int qlen, int span, + int heads, int kv_heads, int d, float scale, int q_pos0, const unsigned* table, int count) { + fa_dot2(q, k, v, out, qlen, span, heads, kv_heads, d, scale, q_pos0, 0, 0, 0, 0, 0, 0, table, count); +} diff --git a/zig/kernels/hip/decode/decode.hip b/zig/kernels/hip/decode/decode.hip new file mode 100644 index 00000000000..4f8328fd445 --- /dev/null +++ b/zig/kernels/hip/decode/decode.hip @@ -0,0 +1,423 @@ +// Decode-step kernels for a few rows: the MoE router, a wave an expert, and residual tails; sums in the fastest order. + +// kind: 1 fp16, 2 bf16 (ops/act.hip's numbering). + +#include +#include + +#include + +#include "decode/plan.hpp" + +namespace { + +__device__ __forceinline__ float bf16_up(uint32_t bits) { return __uint_as_float(bits << 16); } + +// Four consecutive activations (8 bytes) widened. +template +__device__ __forceinline__ float4 widen4(uint2 v) { + if constexpr (KIND == 1) { + const __half2 a = __builtin_bit_cast(__half2, v.x); + const __half2 b = __builtin_bit_cast(__half2, v.y); + return make_float4(__low2float(a), __high2float(a), __low2float(b), __high2float(b)); + } else { + return make_float4(bf16_up(v.x & 0xffffu), bf16_up(v.x >> 16), bf16_up(v.y & 0xffffu), bf16_up(v.y >> 16)); + } +} + +constexpr int kRouterWaves = 4; +constexpr int kRouterSteps = 16; // float4 loads a lane keeps in flight +constexpr int kRouterRows = 16; + +// logits[r, e] = x[r] . rows[e], 16 rows a block, a wave an expert; d is a multiple of 4, weight rows 16-byte aligned. +template +__device__ void router_decode(const void* x, const float* rows, float* logits, int r, int d, int e) { + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * kRouterWaves + (threadIdx.x >> 5); + if (expert >= e) return; + // blockIdx.y picks a block of 16 rows: a row's sums are the same whichever block it is in + const int first = blockIdx.y * kRouterRows; + x = static_cast(x) + static_cast(first) * d; + logits += static_cast(first) * e; + r = r - first < kRouterRows ? r - first : kRouterRows; + const float* w = rows + static_cast(expert) * d; + float acc[kRouterRows]; +#pragma unroll + for (int k = 0; k < kRouterRows; ++k) acc[k] = 0.f; + for (int base = 0; base < d; base += kRouterSteps * 128) { + float4 wv[kRouterSteps]; +#pragma unroll + for (int s = 0; s < kRouterSteps; ++s) { + const int at = base + (lane + 32 * s) * 4; + wv[s] = at < d ? *reinterpret_cast(w + at) : make_float4(0.f, 0.f, 0.f, 0.f); + } +#pragma unroll + for (int k = 0; k < kRouterRows; ++k) { + if (k >= r) continue; + const uint16_t* xr = static_cast(x) + static_cast(k) * d; +#pragma unroll + for (int s = 0; s < kRouterSteps; ++s) { + const int at = base + (lane + 32 * s) * 4; + if (at >= d) continue; + const float4 xv = widen4(*reinterpret_cast(xr + at)); + acc[k] = fmaf(xv.x, wv[s].x, acc[k]); + acc[k] = fmaf(xv.y, wv[s].y, acc[k]); + acc[k] = fmaf(xv.z, wv[s].z, acc[k]); + acc[k] = fmaf(xv.w, wv[s].w, acc[k]); + } + } + } +#pragma unroll + for (int k = 0; k < kRouterRows; ++k) { + float v = acc[k]; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) v += __shfl_xor(v, mask, 32); + if (lane == 0 && k < r) logits[static_cast(k) * e + expert] = v; + } +} + + +__device__ __forceinline__ float load_kind(const void* p, int kind, long long i) { + return kind == 1 ? __half2float(static_cast(p)[i]) : bf16_up(static_cast(p)[i]); +} + +// A float rounded to the activation kind (fp16 or bf16, to nearest even) and widened again. +__device__ __forceinline__ float round_kind(float v, int kind) { + if (kind == 1) return __half2float(__float2half_rn(v)); + if (v != v) return v; + const uint32_t u = __float_as_uint(v); + return __uint_as_float(((u + (((u >> 16) & 1u) + 0x7fffu)) >> 16) << 16); +} + +__device__ __forceinline__ void store_kind(void* p, int kind, long long i, float v) { + if (kind == 1) { + static_cast<__half*>(p)[i] = __float2half_rn(v); + } else { + const uint32_t u = __float_as_uint(v); + static_cast(p)[i] = v != v ? 0x7fc0 : static_cast((u + (((u >> 16) & 1u) + 0x7fffu)) >> 16); + } +} + +constexpr int kTailThreads = 512; +constexpr int kTailWidth = 8192; + +// One row a block, one launch: x = round(x + t), t = y or the slot-ordered weighted sum; normed = rms(x) * weight. +__device__ void tail_body(void* x, const void* y, const float* wts, const float* weight, void* normed, int kind, + int slots, int width, float eps) { + __shared__ float row_v[kTailWidth]; + __shared__ float part[kTailThreads / 32]; + const int row = blockIdx.x; + const long long at = static_cast(row) * width; + float sum = 0.f; + for (int i = threadIdx.x; i < width; i += kTailThreads) { + float t; + if (slots > 0) { + float acc = 0.f; + for (int s = 0; s < slots; ++s) { + acc += static_cast(y)[(static_cast(row) * slots + s) * width + i] * + wts[row * slots + s]; + } + t = round_kind(acc, kind); + } else { + t = load_kind(y, kind, at + i); + } + const float v = round_kind(load_kind(x, kind, at + i) + t, kind); + store_kind(x, kind, at + i, v); + row_v[i] = v; + sum += v * v; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sum; + __syncthreads(); + float total = 0.f; +#pragma unroll + for (int w = 0; w < kTailThreads / 32; ++w) total += part[w]; + const float inv = rsqrtf(total / static_cast(width) + eps); + for (int i = threadIdx.x; i < width; i += kTailThreads) { + float value = row_v[i] * inv; + if (weight != nullptr) value *= weight[i]; + store_kind(normed, kind, at + i, value); + } +} + +// Conv launch arguments: x (rows, channels), taps, state, snapshots; q, k (rows, kw), v (rows, vw) out; norm, gate. +struct ConvArgs { + const void* x; + int kind; + const float* weight; + float* state; + float* states; + float* qn; + float* kn; + float* v; + int channels, kernel, rows, kw, vw; + const float* qw; + const float* kw_w; + float eps; + int norm; + const void* ga; + const void* gb; + const float* a_log; + const float* dt_bias; + float* gate; + float* beta; + int gcount, heads; + // A round's plan (plan.count null: the launch's own rows and state): a grid row a slot, rows and state from it. + PlanArgs plan; + int layer; +}; + +// The conv for a window's rows split into q, k, v: taps in order, then silu; q, k heads rms-normed; gate and beta last. +__device__ void conv_split_body(const ConvArgs& launch) { + __shared__ float sq[128]; + __shared__ float inv_s; + ConvArgs c = launch; + float* samples = nullptr; + const int conv_blocks = (c.channels + 127) / 128; + if (launch.plan.count != nullptr) { + const int slot = blockIdx.y; + // the gates are one pass over every row of the round, from the first slot's blocks + if (blockIdx.x >= conv_blocks && slot != 0) return; + if (blockIdx.x < conv_blocks) { + const int rows = launch.plan.count[slot]; + if (rows == 0) return; + const long long row0 = launch.plan.first[slot]; + c.rows = rows; + c.state = reinterpret_cast(plan_desc(launch.plan, slot)[plan_first(launch.layer)]); + c.x = static_cast(launch.x) + row0 * c.channels * 2; + c.qn += row0 * c.kw; + c.kn += row0 * c.kw; + c.v += row0 * c.vw; + // a window of rows keeps its input rows and leaves the window as the round found it, for its keep + const bool replayed = rows > 1 && slot + 1 < static_cast(gridDim.y); + c.states = nullptr; + samples = replayed ? reinterpret_cast(launch.plan.snaps[2 * launch.layer]) + row0 * c.channels : nullptr; + } + } + if (blockIdx.x >= conv_blocks) { + const int i = (blockIdx.x - conv_blocks) * 128 + threadIdx.x; + if (c.ga == nullptr || i >= c.gcount) return; + const int h = i % c.heads; + c.beta[i] = 1.f / (1.f + expf(-load_kind(c.gb, c.kind, i))); + const float xg = load_kind(c.ga, c.kind, i) + c.dt_bias[h]; + const float soft = xg > 20.f ? xg : log1pf(expf(xg)); + c.gate[i] = expf(-expf(c.a_log[h]) * soft); + return; + } + const int channel = blockIdx.x * 128 + threadIdx.x; + const bool live = channel < c.channels; + const bool head = c.norm == 128 && static_cast(blockIdx.x) * 128 < 2 * c.kw; + const float* taps = c.weight + static_cast(live ? channel : 0) * c.kernel; + const int kept = c.kernel - 1; + float history[7]; + if (live) { + for (int tap = 0; tap < kept; ++tap) history[tap] = c.state[static_cast(tap) * c.channels + channel]; + } + for (int r = 0; r < c.rows; ++r) { + float y = 0.f; + float sample = 0.f; + if (live) { + float acc = 0.f; + for (int tap = 0; tap < kept; ++tap) acc += history[tap] * taps[tap]; + sample = load_kind(c.x, c.kind, static_cast(r) * c.channels + channel); + acc += sample * taps[kept]; + y = acc * (1.f / (1.f + expf(-acc))); + } + if (head) { + // the norm of the head's 128 values, then the scale by its weight + __syncthreads(); + sq[threadIdx.x] = y * y; + __syncthreads(); + if (threadIdx.x < 32) { + float sum = 0.f; + for (int j = 0; j < 4; ++j) sum += sq[threadIdx.x + 32 * j]; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if (threadIdx.x == 0) inv_s = rsqrtf(sum / 128.f + c.eps); + } + __syncthreads(); + const bool is_q = channel < c.kw; + y = y * inv_s * (is_q ? c.qw : c.kw_w)[threadIdx.x]; + } + if (live) { + if (channel < c.kw) { + c.qn[static_cast(r) * c.kw + channel] = y; + } else if (channel < 2 * c.kw) { + c.kn[static_cast(r) * c.kw + channel - c.kw] = y; + } else { + c.v[static_cast(r) * c.vw + channel - 2 * c.kw] = y; + } + for (int tap = 0; tap < kept - 1; ++tap) history[tap] = history[tap + 1]; + if (kept > 0) history[kept - 1] = sample; + if (samples != nullptr) samples[static_cast(r) * c.channels + channel] = sample; + if (c.states != nullptr) { + for (int tap = 0; tap < kept; ++tap) { + c.states[(static_cast(r) * kept + tap) * c.channels + channel] = history[tap]; + } + } + } + } + if (live && samples == nullptr) { + for (int tap = 0; tap < kept; ++tap) c.state[static_cast(tap) * c.channels + channel] = history[tap]; + } +} + +// rms over rows of `width` fp32 values a wave a row as rms_rows; blockIdx.y picks the first or second set of rows. +__device__ void + rms2_body(const float* x0, const float* w0, float* y0, const float* x1, const float* w1, float* y1, int rows, + int width, float eps) { + constexpr int kMost = 1024 / 32; + const float* x = blockIdx.y == 0 ? x0 : x1; + const float* weight = blockIdx.y == 0 ? w0 : w1; + float* y = blockIdx.y == 0 ? y0 : y1; + const int lane = threadIdx.x & 31; + const int row = blockIdx.x * 8 + (threadIdx.x >> 5); + if (row >= rows) return; + const long long at = static_cast(row) * width; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = i < width ? x[at + i] : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i >= width) break; + float value = v[j] * inv; + if (weight != nullptr) value *= weight[i]; + y[at + i] = value; + } +} + +// The gated norm out = rms(y) * weight * round(silu(z)) in the kind, a wave a (row, head), no fp32 round trip between. +__device__ void + gnorm_out_body(const float* y, const float* weight, const void* z, void* out, int kind, int rows, int width, + float eps) { + constexpr int kMost = 1024 / 32; + const int lane = threadIdx.x & 31; + const int row = blockIdx.x * 8 + (threadIdx.x >> 5); + if (row >= rows) return; + const long long at = static_cast(row) * width; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = i < width ? y[at + i] : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i >= width) break; + float value = v[j] * inv; + if (weight != nullptr) value *= weight[i]; + const float zv = load_kind(z, kind, at + i); + store_kind(out, kind, at + i, value * round_kind(zv / (1.f + expf(-zv)), kind)); + } +} + +constexpr int kSelectThreads = 256; +constexpr int kSelectMax = 1024; + +__device__ __forceinline__ float round_bf16_f(float v) { return round_kind(v, 2); } + +// act.hip's moe_select with picks by rank: expert i is in the top k when fewer than k beat it; `items` writes the plan. +__device__ void select_body(const float* logits, int* pick, float* wts, int* items, int* members, int capacity, + int experts, int top_k) { + __shared__ float v[kSelectMax]; + __shared__ float top_v[32]; + __shared__ int top_i[32]; + const int row = blockIdx.x; + const int slots = top_k + 1; + const float* l = logits + static_cast(row) * (experts + 1); + for (int i = threadIdx.x; i < experts; i += kSelectThreads) v[i] = l[i]; + __syncthreads(); + for (int i = threadIdx.x; i < experts; i += kSelectThreads) { + const float vi = v[i]; + int rank = 0; +#pragma unroll 16 + for (int j = 0; j < experts; ++j) { + const float vj = v[j]; + rank += (vj > vi) || (vj == vi && j < i); + } + if (rank < top_k) { + top_v[rank] = vi; + top_i[rank] = i; + } + } + __syncthreads(); + if (threadIdx.x == 0) { + const float top = top_v[0]; + float ex[32]; + float total = 0.f; + for (int k = 0; k < top_k; ++k) { + ex[k] = expf(top_v[k] - top); + total += ex[k]; + } + for (int k = 0; k < top_k; ++k) { + pick[row * slots + k] = top_i[k]; + wts[row * slots + k] = round_bf16_f(ex[k] / total); + } + const float gate = round_bf16_f(l[experts]); + pick[row * slots + top_k] = experts; + wts[row * slots + top_k] = round_bf16_f(1.f / (1.f + expf(-gate))); + } + if (items != nullptr) { + __syncthreads(); + for (int k = threadIdx.x; k < capacity; k += kSelectThreads) { + const bool real = k < slots; + items[3 * k] = real ? pick[k] : 0; + items[3 * k + 1] = real ? k : 0; + items[3 * k + 2] = real ? 1 : 0; + if (real) members[k] = k; + } + } +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(32 * kRouterWaves) + tf_router_decode_f16(const void* x, const float* rows, float* logits, int r, int d, int e) { + router_decode<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(32 * kRouterWaves) + tf_router_decode_bf16(const void* x, const float* rows, float* logits, int r, int d, int e) { + router_decode<2>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(kTailThreads) + tf_tail(void* x, const void* y, const float* wts, const float* weight, void* normed, int kind, int slots, int width, + float eps) { + tail_body(x, y, wts, weight, normed, kind, slots, width, eps); +} + +extern "C" __global__ void __launch_bounds__(128) tf_conv_split(ConvArgs c) { conv_split_body(c); } + +extern "C" __global__ void __launch_bounds__(256) + tf_rms2(const float* x0, const float* w0, float* y0, const float* x1, const float* w1, float* y1, int rows, int width, + float eps) { + rms2_body(x0, w0, y0, x1, w1, y1, rows, width, eps); +} + +extern "C" __global__ void __launch_bounds__(256) + tf_gnorm_out(const float* y, const float* weight, const void* z, void* out, int kind, int rows, int width, float eps) { + gnorm_out_body(y, weight, z, out, kind, rows, width, eps); +} + +extern "C" __global__ void __launch_bounds__(kSelectThreads) + tf_select_decode(const float* logits, int* pick, float* wts, int* items, int* members, int capacity, int experts, + int top_k) { + select_body(logits, pick, wts, items, members, capacity, experts, top_k); +} diff --git a/zig/kernels/hip/decode/pages.hpp b/zig/kernels/hip/decode/pages.hpp new file mode 100644 index 00000000000..89070fa945a --- /dev/null +++ b/zig/kernels/hip/decode/pages.hpp @@ -0,0 +1,14 @@ +#pragma once + +// Paged KV: a pool of `count` 64-position pages a head, named by a stream's table; a head's pages sit side by side. +constexpr int kPageTokens = 64; + +// The element offset in a pool of `count` pages a head of head `h`, slot `slot` of page `page`. +__device__ __forceinline__ long long page_row(unsigned page, unsigned count, int h, int slot, int d) { + return ((static_cast(h) * count + page) * kPageTokens + slot) * d; +} + +// The element offset in a pool of head `h` at stream position `pos`. +__device__ __forceinline__ long long page_at(const unsigned* table, unsigned count, int h, int pos, int d) { + return page_row(table[pos / kPageTokens], count, h, pos % kPageTokens, d); +} diff --git a/zig/kernels/hip/decode/plan.hip b/zig/kernels/hip/decode/plan.hip new file mode 100644 index 00000000000..e2261447770 --- /dev/null +++ b/zig/kernels/hip/decode/plan.hip @@ -0,0 +1,219 @@ +// A lane round's attention walk, cache writes and keep, read from the round's plan on the device (plan.hpp). + +#include "ops/common.hpp" +#include "decode/plan.hpp" + +namespace { + +__device__ __forceinline__ float wave_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +// Row r's keys (already rotated, fp32) and values (the activation kind) into its slot's pages at its position. +__device__ void plan_kv_write_body(const float* keys, const void* values, int kind, int rows, int kv_heads, int d, + PlanArgs plan, int layer) { + const long long i = gid(); + if (i >= static_cast(rows) * kv_heads * d) return; + const int j = static_cast(i % d); + const int h = static_cast((i / d) % kv_heads); + const int r = static_cast(i / (static_cast(d) * kv_heads)); + const unsigned long long* desc = plan_desc(plan, plan.slot[r]); + const long long to = page_at(plan_pages(plan, desc), plan.pool, h, plan.pos[r], d) + j; + store(reinterpret_cast(desc[plan_first(layer)]), kind, to, keys[i]); + static_cast(reinterpret_cast(desc[plan_second(layer)]))[to] = static_cast(values)[i]; +} + +// Query heads a block takes together: they share a KV head, so its keys and values are read once for all of them. +constexpr int kMaxGroup = 16; + +// score_keys over a plan's rows: a warp scores a key for each of the block's heads (one KV head's), in its order. +template +__device__ void plan_score_body(const float* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + extern __shared__ float qs[]; // the block's query heads, group * d + const int batch = blockIdx.z; + const int group = heads / gridDim.y; + const int head0 = blockIdx.y * group; + const float* qrows = q + (static_cast(batch) * heads + head0) * d; + for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = qrows[i]; + __syncthreads(); + const int visible = min(plan.pos[batch] + 1, span); + const int lane = threadIdx.x & 31; + const int key = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + float kreg[8] = {}; + if (key < visible) { + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + const void* keys = reinterpret_cast(desc[plan_first(layer)]); + const long long base = page_at(plan_pages(plan, desc), plan.pool, head0 / (heads / kv_heads), key, d); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int idx = lane + i * 32; + if (idx < d) kreg[i] = load(keys, KIND, base + idx); + } + } +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) { // the same for the whole block, so every lane reaches wave_sum + float partial = 0.f; + if (key < visible) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int idx = lane + i * 32; + if (idx < d) partial += qs[g * d + idx] * kreg[i]; + } + } + const float dot = wave_sum(partial); + if (lane == 0 && key < span) { + const float score = key < visible ? dot * scale : -INFINITY; + scores[(static_cast(batch) * heads + head0 + g) * span + key] = score; + } + } + } +} + +// apply_values over a plan's rows: a 128-key tile of the block's heads, weights worked once a block, in its order. +template +__device__ void plan_apply_body(const float* __restrict__ scores, const float* __restrict__ stats, + float* __restrict__ partials, int span, int heads, int kv_heads, int d, + PlanArgs plan, int layer) { + __shared__ float weights[kMaxGroup * 128]; + const int batch = blockIdx.z; + const int visible = min(plan.pos[batch] + 1, span); + const int tile = blockIdx.x; + const int group = heads / gridDim.y; + const int head0 = blockIdx.y * group; + const long long first = static_cast(batch) * heads + head0; + const int lane = threadIdx.x; + const int key0 = tile * 128; + if (key0 >= visible) { // a tile past the keys in use adds zero + if (lane < d) { + for (int g = 0; g < group; ++g) partials[((first + g) * gridDim.x + tile) * d + lane] = 0.f; + } + return; + } + const int stop = min(key0 + 128, visible); + for (int i = threadIdx.x; i < group * 128; i += blockDim.x) { + const long long h = first + i / 128; + const int key = key0 + i % 128; + if (key < stop) weights[i] = expf(scores[h * span + key] - stats[h * 2]) / stats[h * 2 + 1]; + } + __syncthreads(); + if (lane >= d) return; + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + const void* values = reinterpret_cast(desc[plan_second(layer)]); + const unsigned* table = plan_pages(plan, desc); + const int kv = head0 / (heads / kv_heads); + float acc[kMaxGroup] = {}; + // a page at a time: its table entry is read once, and the keys are summed in order + for (int key = key0; key < stop;) { + const int edge = min((key / kPageTokens + 1) * kPageTokens, stop); + const long long slot0 = page_row(table[key / kPageTokens], plan.pool, kv, 0, d) + lane; + for (; key < edge; ++key) { + const float value = load(values, KIND, slot0 + static_cast(key % kPageTokens) * d); +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) acc[g] += weights[g * 128 + key - key0] * value; + } + } + } +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) partials[((first + g) * gridDim.x + tile) * d + lane] = acc[g]; + } +} + +// The words of a row copied by a block row of threads, four at a time. +__device__ __forceinline__ void copy_words(unsigned int* to, const unsigned int* from, int words) { + const int stride = gridDim.x * blockDim.x; + for (int i = (blockIdx.x * blockDim.x + threadIdx.x) * 4; i < words; i += stride * 4) { + *reinterpret_cast(to + i) = *reinterpret_cast(from + i); + } +} + +} // namespace + +extern "C" { + +__global__ void __launch_bounds__(256) +tf_plan_kv_write(const float* keys, const void* values, int kind, int rows, int kv_heads, int d, PlanArgs plan, int layer) { + plan_kv_write_body(keys, values, kind, rows, kv_heads, d, plan, layer); +} + +__global__ void __launch_bounds__(128) +tf_plan_score_f16(const float* q, float* scores, int span, int heads, int kv_heads, int d, float scale, PlanArgs plan, int layer) { + plan_score_body<1>(q, scores, span, heads, kv_heads, d, scale, plan, layer); +} + +__global__ void __launch_bounds__(128) +tf_plan_score_bf16(const float* q, float* scores, int span, int heads, int kv_heads, int d, float scale, PlanArgs plan, int layer) { + plan_score_body<2>(q, scores, span, heads, kv_heads, d, scale, plan, layer); +} + +__global__ void __launch_bounds__(256) +tf_plan_apply_f16(const float* scores, const float* stats, float* partials, int span, int heads, int kv_heads, int d, PlanArgs plan, int layer) { + plan_apply_body<1>(scores, stats, partials, span, heads, kv_heads, d, plan, layer); +} + +__global__ void __launch_bounds__(256) +tf_plan_apply_bf16(const float* scores, const float* stats, float* partials, int span, int heads, int kv_heads, int d, PlanArgs plan, int layer) { + plan_apply_body<2>(scores, stats, partials, span, heads, kv_heads, d, plan, layer); +} + +// A prompt pass's rotated, rounded keys and values (16-bit) into positions pos0 .. pos0 + len of a stream's pages. +__global__ void __launch_bounds__(256) +tf_page_write(const uint16_t* src, uint16_t* pool, const unsigned* table, int len, int kv_heads, int d, long long s_head, + long long s_row, int pos0, int count) { + const long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + const int j = static_cast(i % d); + const int h = static_cast((i / d) % kv_heads); + const int r = static_cast(i / (static_cast(d) * kv_heads)); + pool[page_at(table, count, h, pos0 + r, d) + j] = src[h * s_head + r * s_row + j]; +} + +// The first `len` positions of a stream's pages as (kv_heads, len, d), the flat layout other attention kernels read. +__global__ void __launch_bounds__(256) +tf_page_gather(const uint16_t* pool, const unsigned* table, uint16_t* dst, int len, int kv_heads, int d, int count) { + const long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + const int j = static_cast(i % d); + const int r = static_cast((i / d) % len); + const int h = static_cast(i / (static_cast(d) * len)); + dst[i] = pool[page_at(table, count, h, r, d) + j]; +} + +// Row r of `dst` is `words` words from the address srcs[r]: a launch whose rows come from anywhere keeps its arguments. +__global__ void __launch_bounds__(256) tf_plan_gather(const unsigned long long* srcs, unsigned int* dst, int words) { + const unsigned int* from = reinterpret_cast(srcs[blockIdx.y]); + unsigned int* to = dst + static_cast(blockIdx.y) * words; + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < words; i += gridDim.x * blockDim.x) to[i] = from[i]; +} + +// Each slot's conv window and last final row after its first keep[slot] rows (negative: none); states: tf_gdn_replay. +__global__ void __launch_bounds__(256) +tf_plan_keep(PlanArgs plan, const int* keep, const unsigned int* hidden, int hidden_words, int channels, int taps, int layers) { + const int slot = blockIdx.z; + const int n = keep[slot]; + if (n < 0) return; + const unsigned long long* desc = plan_desc(plan, slot); + if (blockIdx.y == layers) { + const int row = plan.first[slot] + n - 1; + if (desc[1] != 0) copy_words(reinterpret_cast(desc[1]), hidden + static_cast(row) * hidden_words, hidden_words); + return; + } + const int layer = blockIdx.y; + if (plan.count[slot] <= 1 || plan.snaps[2 * layer] == 0) return; + float* window = reinterpret_cast(desc[plan_first(layer)]); + const float* samples = reinterpret_cast(plan.snaps[2 * layer]) + static_cast(plan.first[slot]) * channels; + // tap t takes position n - taps + t of the round's first window followed by its rows: ascending taps read ahead + for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < channels; c += gridDim.x * blockDim.x) { + for (int t = 0; t < taps; ++t) { + const int at = n - taps + t; + window[static_cast(t) * channels + c] = at < 0 ? window[static_cast(taps + at) * channels + c] : samples[static_cast(at) * channels + c]; + } + } +} + +} // extern "C" diff --git a/zig/kernels/hip/decode/plan.hpp b/zig/kernels/hip/decode/plan.hpp new file mode 100644 index 00000000000..7e3af96b47b --- /dev/null +++ b/zig/kernels/hip/decode/plan.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include + +#include "decode/pages.hpp" + +// A lane round's plan in device memory: no stream state is a launch argument, so one launch or graph serves any. +struct PlanArgs { + const int* pos; // per row: its position + const int* slot; // per row: its slot + const int* first; // per slot: its first row + const int* count; // per slot: its rows + const unsigned long long* desc; // per slot: the address of its descriptor + const unsigned long long* snaps; // per layer: the round's conv and DeltaNet snapshots, a row each + unsigned pages; // words of a descriptor before its page table + unsigned pool; // pages a head of a layer's pool holds +}; + +// Slot descriptor: [0] cached positions, [1] last kept final row, two cache addresses a layer, then the page table. +__device__ __forceinline__ const unsigned long long* plan_desc(const PlanArgs& p, int slot) { + return reinterpret_cast(p.desc[slot]); +} + +__device__ __forceinline__ int plan_first(int layer) { return 2 + 2 * layer; } + +__device__ __forceinline__ int plan_second(int layer) { return 3 + 2 * layer; } + +__device__ __forceinline__ const unsigned* plan_pages(const PlanArgs& p, const unsigned long long* desc) { + return reinterpret_cast(desc + p.pages); +} diff --git a/zig/kernels/hip/ops/act.hip b/zig/kernels/hip/ops/act.hip new file mode 100644 index 00000000000..0e21b6cef9b --- /dev/null +++ b/zig/kernels/hip/ops/act.hip @@ -0,0 +1,279 @@ + +#include +#include + +#include + +namespace tf { +namespace rocm { + +__device__ float warp_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +__device__ inline float widen(float v) { return v; } +__device__ inline float widen(__half v) { return __half2float(v); } +__device__ inline float widen(hip_bfloat16 v) { return static_cast(v); } +__device__ inline void narrow(float v, float* out) { *out = v; } +__device__ inline void narrow(float v, __half* out) { *out = __float2half_rn(v); } +__device__ inline void narrow(float v, hip_bfloat16* out) { *out = hip_bfloat16(v); } + +// fp32 sum of squares by one wave (lane l adds l, l + 32, ... then the xor tree), so bits do not depend on blockDim. +constexpr int kRmsThreads = 256; +constexpr int kRmsWidth = 8192; + +template +__global__ void __launch_bounds__(kRmsThreads) rms_kernel(const T* __restrict__ x, const float* __restrict__ weight, + T* __restrict__ y, int width, float eps) { + __shared__ float row_v[kRmsWidth]; + __shared__ float inv_s; + const int row = blockIdx.x; + const T* in = x + static_cast(row) * width; + for (int i = threadIdx.x; i < width; i += kRmsThreads) row_v[i] = widen(in[i]); + __syncthreads(); + if (threadIdx.x < 32) { + float sum = 0.f; + for (int i = threadIdx.x; i < width; i += 32) sum += row_v[i] * row_v[i]; + const float inv = rsqrtf(warp_sum(sum) / static_cast(width) + eps); + if (threadIdx.x == 0) inv_s = inv; + } + __syncthreads(); + const float inv = inv_s; + T* out = y + static_cast(row) * width; + for (int i = threadIdx.x; i < width; i += kRmsThreads) { + float value = row_v[i] * inv; + if (weight != nullptr) value *= weight[i]; + narrow(value, out + i); + } +} + +// Length 1. Taps run in order, then the state shifts toward the new sample. +extern "C" __global__ void tf_conv_decode(const float* __restrict__ x, const float* __restrict__ weight, + float* __restrict__ state, float* __restrict__ y, int channels, int kernel) { + int channel = blockIdx.x * blockDim.x + threadIdx.x; + int batch = blockIdx.y; + if (channel >= channels) return; + const float* row = weight + static_cast(channel) * kernel; + float history[7]; + int kept = kernel - 1; + float acc = 0.f; + for (int tap = 0; tap < kept; ++tap) { + history[tap] = state[(static_cast(batch) * kept + tap) * channels + channel]; + acc += history[tap] * row[tap]; + } + float sample = x[static_cast(batch) * channels + channel]; + acc += sample * row[kept]; + float gate = 1.f / (1.f + expf(-acc)); + y[(static_cast(batch) * channels) + channel] = acc * gate; + for (int tap = 0; tap < kept - 1; ++tap) { + state[(static_cast(batch) * kept + tap) * channels + channel] = history[tap + 1]; + } + if (kept > 0) state[(static_cast(batch) * kept + kept - 1) * channels + channel] = sample; +} + +// A window's rows in one launch: conv_decode's step for each row in turn, the state after each kept in ``states``. +extern "C" __global__ void tf_conv_rows(const float* __restrict__ x, const float* __restrict__ weight, + float* __restrict__ state, float* __restrict__ y, float* __restrict__ states, + int channels, int kernel, int rows) { + int channel = blockIdx.x * blockDim.x + threadIdx.x; + if (channel >= channels) return; + const float* row = weight + static_cast(channel) * kernel; + float history[7]; + int kept = kernel - 1; + for (int tap = 0; tap < kept; ++tap) history[tap] = state[static_cast(tap) * channels + channel]; + for (int r = 0; r < rows; ++r) { + float acc = 0.f; + for (int tap = 0; tap < kept; ++tap) acc += history[tap] * row[tap]; + float sample = x[static_cast(r) * channels + channel]; + acc += sample * row[kept]; + float gate = 1.f / (1.f + expf(-acc)); + y[static_cast(r) * channels + channel] = acc * gate; + for (int tap = 0; tap < kept - 1; ++tap) history[tap] = history[tap + 1]; + if (kept > 0) history[kept - 1] = sample; + if (states != nullptr) { + for (int tap = 0; tap < kept; ++tap) { + states[(static_cast(r) * kept + tap) * channels + channel] = history[tap]; + } + } + } + for (int tap = 0; tap < kept; ++tap) state[static_cast(tap) * channels + channel] = history[tap]; +} + +// ``per`` > 0: rows of a window, ``per`` rows to a position, row r at ``pos_dev[r / per]``. +extern "C" __global__ void tf_rope_decode(const float* __restrict__ x, float* __restrict__ y, int width, int rotary, + int pos, float theta, const int* __restrict__ pos_dev, int per) { + int row = blockIdx.x; + if (pos_dev != nullptr) pos = per > 0 ? pos_dev[row / per] : *pos_dev; + int lane = threadIdx.x; + const float* in = x + static_cast(row) * width; + float* out = y + static_cast(row) * width; + int half = rotary >> 1; + for (int i = lane; i < half; i += 32) { + float freq = 1.f / powf(theta, static_cast(i) / static_cast(half)); + float ang = static_cast(pos) * freq; + float c = cosf(ang); + float s = sinf(ang); + float x1 = in[i]; + float x2 = in[half + i]; + out[i] = x1 * c - x2 * s; + out[half + i] = x1 * s + x2 * c; + } + for (int i = rotary + lane; i < width; i += 32) out[i] = in[i]; +} + +template +__global__ void __launch_bounds__(256) moe_router_kernel(const T* __restrict__ x, const float* __restrict__ rows, + float* __restrict__ logits, int d, int e) { + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * 8 + (threadIdx.x >> 5); + const int row = blockIdx.y; + if (expert >= e) return; + const T* xr = x + static_cast(row) * d; + const float* w = rows + static_cast(expert) * d; + float acc = 0.f; + for (int i = lane; i < d; i += 32) acc = fmaf(widen(xr[i]), w[i], acc); + acc = warp_sum(acc); + if (lane == 0) logits[static_cast(row) * e + expert] = acc; +} + +constexpr int kSelectMax = 1024; + +__device__ inline float round_bf16(float v) { return static_cast(hip_bfloat16(v)); } + +extern "C" __global__ void __launch_bounds__(32) tf_moe_select(const float* __restrict__ logits, int* __restrict__ pick, + float* __restrict__ wts, int* __restrict__ items, + int* __restrict__ members, int capacity, int experts, + int top_k) { + __shared__ float v[kSelectMax]; + __shared__ float ex[32]; + const int lane = threadIdx.x; + const int row = blockIdx.x; + const int slots = top_k + 1; + const float* l = logits + static_cast(row) * (experts + 1); + for (int i = lane; i < experts; i += 32) v[i] = l[i]; + __syncthreads(); + float top = 0.f, total = 0.f; + for (int k = 0; k < top_k; ++k) { + float best = -INFINITY; + int idx = 0x7fffffff; + for (int i = lane; i < experts; i += 32) { + const float value = v[i]; + if (value > best || (value == best && i < idx)) { + best = value; + idx = i; + } + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) { + const float other = __shfl_xor(best, mask, 32); + const int at = __shfl_xor(idx, mask, 32); + if (other > best || (other == best && at < idx)) { + best = other; + idx = at; + } + } + if (k == 0) top = best; + const float e = expf(best - top); + total += e; + if (lane == 0) { + pick[row * slots + k] = idx; + ex[k] = e; + v[idx] = -INFINITY; + } + __syncthreads(); + } + if (lane == 0) { + for (int k = 0; k < top_k; ++k) wts[row * slots + k] = round_bf16(ex[k] / total); + const float gate = round_bf16(l[experts]); + pick[row * slots + top_k] = experts; + wts[row * slots + top_k] = round_bf16(1.f / (1.f + expf(-gate))); + } + if (items != nullptr) { + __syncthreads(); + for (int k = lane; k < capacity; k += 32) { + const bool real = k < slots; + items[3 * k] = real ? pick[k] : 0; + items[3 * k + 1] = real ? k : 0; + items[3 * k + 2] = real ? 1 : 0; + if (real) members[k] = k; + } + } +} + +template +__global__ void moe_act_kernel(const float* __restrict__ both, T* __restrict__ out, int width, float limit, + long long total) { + const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= total) return; + const long long p = i / width; + const int c = static_cast(i - p * width); + float g = both[p * 2 * width + c]; + float u = both[p * 2 * width + width + c]; + if (limit > 0.f) { + g = fminf(g, limit); + u = fminf(fmaxf(u, -limit), limit); + } + narrow(g / (1.f + expf(-g)) * u, out + i); +} + +template +__global__ void moe_combine_kernel(const float* __restrict__ y, const float* __restrict__ wts, T* __restrict__ out, + int slots, int d) { + const int row = blockIdx.y; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= d) return; + float acc = 0.f; + for (int s = 0; s < slots; ++s) { + acc += y[(static_cast(row) * slots + s) * d + c] * wts[row * slots + s]; + } + narrow(acc, out + static_cast(row) * d + c); +} + +template +__global__ void gdn_gate_kernel(const T* __restrict__ a, const T* __restrict__ b, const float* __restrict__ a_log, + const float* __restrict__ dt_bias, float* __restrict__ gate, float* __restrict__ beta, + int count, int heads) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + const int h = i % heads; + beta[i] = 1.f / (1.f + expf(-widen(b[i]))); + const float x = widen(a[i]) + dt_bias[h]; + const float soft = x > 20.f ? x : log1pf(expf(x)); + gate[i] = expf(-expf(a_log[h]) * soft); +} + +// The template kernels launches.zig resolves. +template __global__ void rms_kernel(const float* __restrict__ x, const float* __restrict__ weight, + float* __restrict__ y, int width, float eps); +template __global__ void rms_kernel<__half>(const __half* __restrict__ x, const float* __restrict__ weight, + __half* __restrict__ y, int width, float eps); +template __global__ void rms_kernel(const hip_bfloat16* __restrict__ x, const float* __restrict__ weight, + hip_bfloat16* __restrict__ y, int width, float eps); +template __global__ void moe_router_kernel<__half>(const __half* __restrict__ x, const float* __restrict__ rows, + float* __restrict__ logits, int d, int e); +template __global__ void moe_router_kernel(const hip_bfloat16* __restrict__ x, + const float* __restrict__ rows, float* __restrict__ logits, int d, int e); +template __global__ void moe_act_kernel<__half>(const float* __restrict__ both, __half* __restrict__ out, int width, + float limit, long long total); +template __global__ void moe_act_kernel(const float* __restrict__ both, hip_bfloat16* __restrict__ out, + int width, float limit, long long total); +template __global__ void moe_combine_kernel(const float* __restrict__ y, const float* __restrict__ wts, + float* __restrict__ out, int slots, int d); +template __global__ void moe_combine_kernel<__half>(const float* __restrict__ y, const float* __restrict__ wts, + __half* __restrict__ out, int slots, int d); +template __global__ void moe_combine_kernel(const float* __restrict__ y, const float* __restrict__ wts, + hip_bfloat16* __restrict__ out, int slots, int d); +template __global__ void gdn_gate_kernel(const float* __restrict__ a, const float* __restrict__ b, + const float* __restrict__ a_log, const float* __restrict__ dt_bias, float* __restrict__ gate, + float* __restrict__ beta, int count, int heads); +template __global__ void gdn_gate_kernel<__half>(const __half* __restrict__ a, const __half* __restrict__ b, + const float* __restrict__ a_log, const float* __restrict__ dt_bias, float* __restrict__ gate, + float* __restrict__ beta, int count, int heads); +template __global__ void gdn_gate_kernel(const hip_bfloat16* __restrict__ a, + const hip_bfloat16* __restrict__ b, const float* __restrict__ a_log, const float* __restrict__ dt_bias, + float* __restrict__ gate, float* __restrict__ beta, int count, int heads); + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/ops/attention.hpp b/zig/kernels/hip/ops/attention.hpp new file mode 100644 index 00000000000..c97bcf67f5a --- /dev/null +++ b/zig/kernels/hip/ops/attention.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include "common.hpp" + +// The gated attention's o input and the cache writes. + +namespace { + +// out[r, h * d + j] = att * sigmoid(gate) rounded to kind; att is (heads, len, d), or (len, heads, d) with rows_major. +extern "C" __global__ void tf_attn_gate(const float* att, const void* qg, void* out, int kind, int len, int heads, int d, + int rows_major) { + long long i = gid(); + if (i >= static_cast(len) * heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % heads); + int r = static_cast(i / (static_cast(d) * heads)); + float a = rows_major ? att[i] : att[(static_cast(h) * len + r) * d + j]; + float g = load(qg, kind, (static_cast(r) * heads + h) * 2 * d + d + j); + store(out, kind, i, a * sigmoid(g)); +} + +// keys or values (len, kv_heads, d) of kind into the cache (kv_heads, total, d) at slot pos0. +extern "C" __global__ void tf_kv_write(const void* src, void* cache, int kind, int len, int kv_heads, int d, int total, + int pos0) { + long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % kv_heads); + int r = static_cast(i / (static_cast(d) * kv_heads)); + long long to = (static_cast(h) * total + pos0 + r) * d + j; + if (kind == 0) static_cast(cache)[to] = static_cast(src)[i]; + else static_cast(cache)[to] = static_cast(src)[i]; +} + +// kv_write with the first slot read from the device (`pos`, one int32), so a captured graph replays at any position. +extern "C" __global__ void tf_kv_write_at(const void* src, void* cache, int kind, int len, int kv_heads, int d, int total, + const int* pos) { + long long i = gid(); + if (i >= static_cast(len) * kv_heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % kv_heads); + int r = static_cast(i / (static_cast(d) * kv_heads)); + long long to = (static_cast(h) * total + *pos + r) * d + j; + if (kind == 0) static_cast(cache)[to] = static_cast(src)[i]; + else static_cast(cache)[to] = static_cast(src)[i]; +} + +} // namespace diff --git a/zig/kernels/hip/ops/common.hpp b/zig/kernels/hip/ops/common.hpp new file mode 100644 index 00000000000..980e5b5645c --- /dev/null +++ b/zig/kernels/hip/ops/common.hpp @@ -0,0 +1,46 @@ +#pragma once + +// The torch ops between kernels, bit for bit: round where torch rounds, no contraction; kind 0 fp32, 1 fp16, 2 bf16. + +#include +#include +#include + +namespace { + +__device__ __forceinline__ float bf16_to_float(uint16_t h) { return __uint_as_float(static_cast(h) << 16); } + +// c10::BFloat16's round to nearest even, NaN to 0x7fc0. +__device__ __forceinline__ uint16_t float_to_bf16(float f) { + if (f != f) return 0x7fc0; + uint32_t u = __float_as_uint(f); + uint32_t bias = ((u >> 16) & 1u) + 0x7fffu; + return static_cast((u + bias) >> 16); +} + +__device__ __forceinline__ float load(const void* p, int kind, long long i) { + if (kind == 0) return static_cast(p)[i]; + if (kind == 1) return __half2float(static_cast(p)[i]); + return bf16_to_float(static_cast(p)[i]); +} + +__device__ __forceinline__ void store(void* p, int kind, long long i, float v) { + if (kind == 0) static_cast(p)[i] = v; + else if (kind == 1) static_cast<__half*>(p)[i] = __float2half_rn(v); + else static_cast(p)[i] = float_to_bf16(v); +} + +// A value rounded to `kind` and widened again: what torch holds after an op that returns that dtype. +__device__ __forceinline__ float rounded(float v, int kind) { + if (kind == 1) return __half2float(__float2half_rn(v)); + if (kind == 2) return bf16_to_float(float_to_bf16(v)); + return v; +} + +// torch's silu and sigmoid on an fp32 operand: x / (1 + exp(-x)) and 1 / (1 + exp(-x)). +__device__ __forceinline__ float silu(float x) { return x / (1.0f + expf(-x)); } +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } + +__device__ __forceinline__ long long gid() { return static_cast(blockIdx.x) * blockDim.x + threadIdx.x; } + +} // namespace diff --git a/zig/kernels/hip/ops/draw.hpp b/zig/kernels/hip/ops/draw.hpp new file mode 100644 index 00000000000..def5b8fba4e --- /dev/null +++ b/zig/kernels/hip/ops/draw.hpp @@ -0,0 +1,136 @@ +#pragma once + +#include "common.hpp" + +// Argmax and top-k of logits rows. + +namespace { + +constexpr int kThreads = 1024; +constexpr int kWaves = kThreads / 32; + +__device__ __forceinline__ float widen(uint16_t bits, int kind) { + if (kind == 1) return __half2float(__ushort_as_half(bits)); + return __uint_as_float(static_cast(bits) << 16); +} + +// torch's argmax order: a NaN beats every value, then the larger value, then the lower index. +__device__ __forceinline__ bool better(float a, int ia, float b, int ib) { + bool na = a != a, nb = b != b; + if (na || nb) return na && (!nb || ia < ib); + return a > b || (a == b && ia < ib); +} + +extern "C" __global__ void tf_argmax(const uint16_t* logits, int kind, int n, int* out) { + const uint16_t* row = logits + static_cast(blockIdx.x) * n; + float top = 0.0f; + int at = -1; + for (int i = threadIdx.x; i < n; i += kThreads) { + float v = widen(row[i], kind); + if (at < 0 || better(v, i, top, at)) { + top = v; + at = i; + } + } + __shared__ float sv[kThreads]; + __shared__ int si[kThreads]; + sv[threadIdx.x] = top; + si[threadIdx.x] = at; + __syncthreads(); + for (int stride = kThreads / 2; stride > 0; stride >>= 1) { + if (threadIdx.x < stride) { + int j = threadIdx.x + stride; + if (si[j] >= 0 && (si[threadIdx.x] < 0 || better(sv[j], si[j], sv[threadIdx.x], si[threadIdx.x]))) { + sv[threadIdx.x] = sv[j]; + si[threadIdx.x] = si[j]; + } + } + __syncthreads(); + } + if (threadIdx.x == 0) out[blockIdx.x] = si[0]; +} + +// A monotone 16-bit key of a value's bits (-0 and +0 share one), so equal keys are equal values. +__device__ __forceinline__ uint32_t order_key(uint16_t bits) { + if (bits == 0x8000) bits = 0; + return (bits & 0x8000) ? (~bits & 0xffffu) : (bits | 0x8000u); +} + +// Row r's ks[r] largest by (value desc, id asc): two histograms of the k-th key, then one ordered compaction. +extern "C" __global__ void tf_topk(const uint16_t* logits, int n, const int* ks, int stride, int* ids, uint16_t* values) { + const int r = blockIdx.x, k = ks[r]; + if (k <= 0) return; + const uint16_t* row = logits + static_cast(r) * n; + __shared__ int hist[256]; + __shared__ int pick[4]; // high byte, low byte, count above, count of the k-th key to take + __shared__ int wave_gt[kWaves], wave_eq[kWaves]; + for (int i = threadIdx.x; i < 256; i += kThreads) hist[i] = 0; + __syncthreads(); + for (int i = threadIdx.x; i < n; i += kThreads) atomicAdd(&hist[order_key(row[i]) >> 8], 1); + __syncthreads(); + if (threadIdx.x == 0) { + int above = 0, b = 255; + for (; b > 0 && above + hist[b] < k; --b) above += hist[b]; + pick[0] = b; + pick[2] = above; + } + __syncthreads(); + for (int i = threadIdx.x; i < 256; i += kThreads) hist[i] = 0; + __syncthreads(); + const uint32_t high = pick[0]; + for (int i = threadIdx.x; i < n; i += kThreads) { + uint32_t key = order_key(row[i]); + if ((key >> 8) == high) atomicAdd(&hist[key & 255u], 1); + } + __syncthreads(); + if (threadIdx.x == 0) { + int above = pick[2], b = 255; + for (; b > 0 && above + hist[b] < k; --b) above += hist[b]; + pick[1] = b; + pick[2] = above; // the keys above the k-th + pick[3] = k - above; // how many of the k-th's to take, lowest ids first + } + __syncthreads(); + const uint32_t kth = (high << 8) | static_cast(pick[1]); + const int above = pick[2], take = pick[3]; + int seen_gt = 0, seen_eq = 0; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (int base = 0; base < n; base += kThreads) { + int i = base + threadIdx.x; + uint16_t bits = i < n ? row[i] : 0; + uint32_t key = order_key(bits); + bool gt = i < n && key > kth, eq = i < n && key == kth; + unsigned long long mg = __ballot(gt), me = __ballot(eq); + unsigned long long below = (1ull << lane) - 1; + if (lane == 0) { + wave_gt[wave] = __popcll(mg); + wave_eq[wave] = __popcll(me); + } + __syncthreads(); + int gt_before = seen_gt, eq_before = seen_eq; + for (int w = 0; w < wave; ++w) { + gt_before += wave_gt[w]; + eq_before += wave_eq[w]; + } + if (gt) { + int slot = gt_before + __popcll(mg & below); + ids[r * stride + slot] = i; + values[r * stride + slot] = bits; + } + if (eq) { + int rank = eq_before + __popcll(me & below); + if (rank < take) { + ids[r * stride + above + rank] = i; + values[r * stride + above + rank] = bits; + } + } + for (int w = 0; w < kWaves; ++w) { + seen_gt += wave_gt[w]; + seen_eq += wave_eq[w]; + } + __syncthreads(); + if (seen_eq >= take && seen_gt >= above) break; + } +} + +} // namespace diff --git a/zig/kernels/hip/ops/elementwise.hpp b/zig/kernels/hip/ops/elementwise.hpp new file mode 100644 index 00000000000..0b1d5bb7aed --- /dev/null +++ b/zig/kernels/hip/ops/elementwise.hpp @@ -0,0 +1,81 @@ +#pragma once + +#include "common.hpp" + +// Embedding rows, casts, sums, column copies and the draft projection. + +namespace { + +// An MLX code at index i of a packed row, including one that crosses two words (qwen_math._codes). +__device__ __forceinline__ uint32_t code_at(const uint32_t* row, int words, int bits, long long i) { + long long bit = i * bits; + int word = static_cast(bit / 32), shift = static_cast(bit % 32); + uint64_t low = row[word]; + uint64_t high = (shift + bits > 32 && word + 1 < words) ? row[word + 1] : 0; + uint64_t value = (low >> shift) | (high << ((32 - shift) & 31)); + return static_cast(value & ((1u << bits) - 1u)); +} + +extern "C" __global__ void tf_embed_rows(const uint32_t* words, const void* scale, const void* bias, int scale_kind, + const int* ids, int n, int bits, int group, int k, void* out, int out_kind) { + long long i = gid(); + if (i >= static_cast(n) * k) return; + int r = static_cast(i / k), c = static_cast(i % k); + long long id = ids[r]; + int words_row = k * bits / 32, groups = k / group; + float code = static_cast(code_at(words + id * words_row, words_row, bits, c)); + float s = load(scale, scale_kind, id * groups + c / group); + float b = load(bias, scale_kind, id * groups + c / group); + float y = code * s; + y = y + b; + store(out, out_kind, i, y); +} + +// The float gather: rows of an fp32 table (an embedding kept unquantized), written in the activation type. +extern "C" __global__ void tf_embed_dense(const float* table, const int* ids, int n, int k, void* out, int out_kind) { + long long i = gid(); + if (i >= static_cast(n) * k) return; + int r = static_cast(i / k), c = static_cast(i % k); + store(out, out_kind, i, table[static_cast(ids[r]) * k + c]); +} + +extern "C" __global__ void tf_cast(const void* src, int skind, void* dst, int dkind, long long n) { + long long i = gid(); + if (i < n) store(dst, dkind, i, load(src, skind, i)); +} + +extern "C" __global__ void tf_silu_mul(const void* gate, const void* up, void* out, int kind, long long n) { + long long i = gid(); + if (i >= n) return; + float s = rounded(silu(load(gate, kind, i)), kind); + store(out, kind, i, s * load(up, kind, i)); +} + +extern "C" __global__ void tf_add(const void* x, const void* y, void* out, int kind, long long n) { + long long i = gid(); + if (i < n) store(out, kind, i, load(x, kind, i) + load(y, kind, i)); +} + +// rows of `cols` values from a source with row stride `stride` at column `offset`, kept in kind. +extern "C" __global__ void tf_copy_cols(const void* src, long long stride, int offset, void* dst, int kind, int rows, + int cols) { + long long i = gid(); + if (i >= static_cast(rows) * cols) return; + long long r = i / cols; + int c = static_cast(i % cols); + long long from = r * stride + offset + c; + if (kind == 0) static_cast(dst)[i] = static_cast(src)[from]; + else static_cast(dst)[i] = static_cast(src)[from]; +} + +// y[r, n] = x[r, :] . w[n, :] over fp32 weights (MTP fc), a wave a value; drafts only, so the sum order is free. +extern "C" __global__ void tf_dense_rows(const void* x, int kind, const float* w, void* out, int rows, int n, int k) { + int col = blockIdx.x, r = blockIdx.y; + if (col >= n || r >= rows) return; + float acc = 0.0f; + for (int i = threadIdx.x; i < k; i += 32) acc += load(x, kind, static_cast(r) * k + i) * w[static_cast(col) * k + i]; + for (int off = 16; off > 0; off >>= 1) acc += __shfl_xor(acc, off, 32); + if (threadIdx.x == 0) store(out, kind, static_cast(r) * n + col, acc); +} + +} // namespace diff --git a/zig/kernels/hip/ops/linear.hpp b/zig/kernels/hip/ops/linear.hpp new file mode 100644 index 00000000000..e77529f1677 --- /dev/null +++ b/zig/kernels/hip/ops/linear.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "common.hpp" + +// The linear attention's prefill: conv, gate and gated norm. + +namespace { + +// Conv prefill: window [state | x], taps summed in order, then silu; row block 0 writes new_state, never `state`. +constexpr int kConvRows = 16; // rows a conv_prefill thread slides over +constexpr int kConvTaps = 8; // most taps it holds + +extern "C" __global__ void tf_conv_prefill(const void* x, int kind, const float* weight, const float* state, float* out, + float* new_state, int len, int channels, int kernel) { + // a thread one channel over kConvRows rows, the window sliding in registers (each input read once) + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + const int r0 = blockIdx.y * kConvRows; + const int kept = kernel - 1; + auto window = [&](int t) -> float { + if (t < kept) return state ? state[static_cast(t) * channels + c] : 0.0f; + return load(x, kind, static_cast(t - kept) * channels + c); + }; + if (blockIdx.y == 0) + for (int t = 0; t < kept; ++t) new_state[static_cast(t) * channels + c] = window(len + t); + float w[kConvTaps], win[kConvTaps]; + for (int tap = 0; tap < kernel; ++tap) w[tap] = weight[static_cast(c) * kernel + tap]; + for (int tap = 0; tap + 1 < kernel; ++tap) win[tap] = window(r0 + tap); + const int r1 = r0 + kConvRows < len ? r0 + kConvRows : len; + for (int r = r0; r < r1; ++r) { + win[kernel - 1] = window(r + kernel - 1); + float acc = 0.0f; + for (int tap = 0; tap < kernel; ++tap) { + float p = win[tap] * w[tap]; + acc = acc + p; + } + out[static_cast(r) * channels + c] = silu(acc); + for (int tap = 0; tap + 1 < kernel; ++tap) win[tap] = win[tap + 1]; + } +} + +// _gate_beta: beta = sigmoid(b), gate = exp(-exp(a_log) * softplus(a + dt_bias)) with torch's softplus. +extern "C" __global__ void tf_gdn_gate_prefill(const void* a, const void* b, int kind, const float* a_log, + const float* dt_bias, float* gate, float* beta, int count, int heads) { + long long i = gid(); + if (i >= static_cast(count) * heads) return; + int h = static_cast(i % heads); + beta[i] = sigmoid(load(b, kind, i)); + float x = load(a, kind, i) + dt_bias[h]; + float xb = x * 1.0f; + float sp = xb > 20.0f ? x : log1pf(expf(xb)) / 1.0f; + float e = -expf(a_log[h]); + gate[i] = expf(e * sp); +} + +// out = y * silu(z) widened, rounded to kind: the linear-attention output before its projection. +extern "C" __global__ void tf_gnorm_silu(const float* y, const void* z, void* out, int kind, long long n) { + long long i = gid(); + if (i >= n) return; + float s = rounded(silu(load(z, kind, i)), kind); + store(out, kind, i, y[i] * s); +} + +} // namespace diff --git a/zig/kernels/hip/ops/moe.hpp b/zig/kernels/hip/ops/moe.hpp new file mode 100644 index 00000000000..f12329e903a --- /dev/null +++ b/zig/kernels/hip/ops/moe.hpp @@ -0,0 +1,217 @@ +#pragma once + +#include "common.hpp" + +// The MoE plan and the router's logits. + +namespace { + +// Stable-sorts the pairs by expert into members and cuts items of at most `tile` pairs; one block, counted per segment. +extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts, int tile, int* members, int* items, + int capacity) { + extern __shared__ int shared[]; + int* counts = shared; + int* starts = shared + experts; + int* ends = shared + 2 * experts; + unsigned short* seg = reinterpret_cast(shared + 3 * experts); + const int segs = experts <= 256 ? 64 : 16; + const int span = (pairs + segs - 1) / segs; + const int t = threadIdx.x; + for (int i = t; i < segs * experts; i += blockDim.x) seg[i] = 0; + __syncthreads(); + if (t < segs) { + for (int p = t * span; p < pairs && p < (t + 1) * span; ++p) seg[t * experts + picks[p]] += 1; + } + __syncthreads(); + // an expert's total and each segment's first place for it (still relative to the expert's start) + for (int e = t; e < experts; e += blockDim.x) { + int run = 0; + for (int g = 0; g < segs; ++g) { + int c = seg[g * experts + e]; + seg[g * experts + e] = static_cast(run); + run += c; + } + counts[e] = run; + } + __syncthreads(); + if (t == 0) { + int start = 0, end = 0; + for (int e = 0; e < experts; ++e) { + starts[e] = start; + start += counts[e]; + end += (counts[e] + tile - 1) / tile; + ends[e] = end; + } + } + __syncthreads(); + if (t < segs) { + for (int p = t * span; p < pairs && p < (t + 1) * span; ++p) { + int e = picks[p]; + members[starts[e] + seg[t * experts + e]] = p; + seg[t * experts + e] += 1; + } + } + for (int slot = t; slot < capacity; slot += blockDim.x) { + int lo = 0, hi = experts; + while (lo < hi) { // searchsorted(ends, slot, right=True) + int mid = (lo + hi) / 2; + if (ends[mid] <= slot) lo = mid + 1; + else hi = mid; + } + int e = lo < experts - 1 ? lo : experts - 1; + int reps = (counts[e] + tile - 1) / tile; + int within = slot - (ends[e] - reps); + int count = counts[e] - within * tile; + items[slot * 3] = e; + items[slot * 3 + 1] = starts[e] + within * tile; + items[slot * 3 + 2] = count < 0 ? 0 : (count > tile ? tile : count); + } +} + +// moe_router_kernel's logits with a wave's expert row read once for 8 token rows; each logit keeps its bits. +__device__ __forceinline__ float router_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +template +__device__ void router_rows(const void* x, const float* rows, float* logits, int r, int d, int e) { + constexpr int kChunk = 1024; + __shared__ float xs[8][kChunk]; + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * 8 + (threadIdx.x >> 5); + const int row0 = blockIdx.y * 8; + const float* w = rows + static_cast(expert < e ? expert : 0) * d; + float acc[8]; +#pragma unroll + for (int k = 0; k < 8; ++k) acc[k] = 0.f; + for (int base = 0; base < d; base += kChunk) { + const int n = d - base < kChunk ? d - base : kChunk; + __syncthreads(); + for (int q = threadIdx.x; q < 8 * kChunk; q += blockDim.x) { + const int k = q / kChunk, i = q % kChunk; + xs[k][i] = (row0 + k < r && i < n) ? load(x, KIND, static_cast(row0 + k) * d + base + i) : 0.f; + } + __syncthreads(); + // lane l keeps adding i = l, l + 32, ... in order across the chunks + for (int i = lane; i < n; i += 32) { + const float wv = w[base + i]; +#pragma unroll + for (int k = 0; k < 8; ++k) acc[k] = fmaf(xs[k][i], wv, acc[k]); + } + } + if (expert >= e) return; +#pragma unroll + for (int k = 0; k < 8; ++k) { + const float sum = router_sum(acc[k]); + if (lane == 0 && row0 + k < r) logits[static_cast(row0 + k) * e + expert] = sum; + } +} + +// The router's logits for many rows: a 64 x 64 tile of (row, expert) a block, 4 x 4 a thread, in fp32. +template +__device__ void router_tile(const void* x, const float* rows, float* logits, int r, int d, int e) { + constexpr int kTile = 64, kStep = 32, kLd = kTile + 4; + __shared__ alignas(16) float xs[kStep][kLd]; + __shared__ alignas(16) float ws[kStep][kLd]; + const int row0 = blockIdx.y * kTile, expert0 = blockIdx.x * kTile; + const int ty = threadIdx.x / 16, tx = threadIdx.x % 16; + // the staging: activation row ar at steps ak .. ak + 7, router rows wr and wr + 32 at steps wk .. wk + 3 + const int ar = threadIdx.x / 4, ak = (threadIdx.x % 4) * 8; + const int wr = threadIdx.x / 8, wk = (threadIdx.x % 8) * 4; + const uint16_t* xh = static_cast(x); + float acc[4][4] = {}; + for (int base = 0; base < d; base += kStep) { + uint4 xv = {0, 0, 0, 0}; + if (row0 + ar < r) xv = *reinterpret_cast(xh + static_cast(row0 + ar) * d + base + ak); + float4 w0 = {0, 0, 0, 0}, w1 = {0, 0, 0, 0}; + if (expert0 + wr < e) w0 = *reinterpret_cast(rows + static_cast(expert0 + wr) * d + base + wk); + if (expert0 + wr + 32 < e) + w1 = *reinterpret_cast(rows + static_cast(expert0 + wr + 32) * d + base + wk); + __syncthreads(); + const uint16_t* h = reinterpret_cast(&xv); +#pragma unroll + for (int j = 0; j < 8; ++j) xs[ak + j][ar] = KIND == 1 ? __half2float(__ushort_as_half(h[j])) : bf16_to_float(h[j]); + const float a0[4] = {w0.x, w0.y, w0.z, w0.w}, a1[4] = {w1.x, w1.y, w1.z, w1.w}; +#pragma unroll + for (int j = 0; j < 4; ++j) ws[wk + j][wr] = a0[j], ws[wk + j][wr + 32] = a1[j]; + __syncthreads(); +#pragma unroll + for (int i = 0; i < kStep; ++i) { + const float4 a = *reinterpret_cast(&xs[i][4 * ty]); + const float4 b = *reinterpret_cast(&ws[i][4 * tx]); + const float av[4] = {a.x, a.y, a.z, a.w}, bv[4] = {b.x, b.y, b.z, b.w}; +#pragma unroll + for (int u = 0; u < 4; ++u) +#pragma unroll + for (int w = 0; w < 4; ++w) acc[u][w] = fmaf(av[u], bv[w], acc[u][w]); + } + } +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int row = row0 + 4 * ty + u; + if (row >= r) continue; +#pragma unroll + for (int w = 0; w < 4; ++w) { + const int expert = expert0 + 4 * tx + w; + if (expert < e) logits[static_cast(row) * e + expert] = acc[u][w]; + } + } +} + +// router_tile's logits for up to 32 rows: a wave an expert, a lane a row, each logit one in-order fmaf chain. +template +__device__ void router_small(const void* x, const float* rows, float* logits, int r, int d, int e) { + const int lane = threadIdx.x & 31; + const int expert = blockIdx.x * 8 + (threadIdx.x >> 5); + const int row = blockIdx.y * 32 + lane; + if (expert >= e) return; + const uint16_t* xh = static_cast(x) + static_cast(row < r ? row : 0) * d; + const float* w = rows + static_cast(expert) * d; + float acc = 0.f; + for (int base = 0; base < d; base += 8) { + const uint4 xv = *reinterpret_cast(xh + base); + const uint16_t* h = reinterpret_cast(&xv); + const float4 w0 = *reinterpret_cast(w + base); + const float4 w1 = *reinterpret_cast(w + base + 4); + const float wv[8] = {w0.x, w0.y, w0.z, w0.w, w1.x, w1.y, w1.z, w1.w}; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc = fmaf(KIND == 1 ? __half2float(__ushort_as_half(h[j])) : bf16_to_float(h[j]), wv[j], acc); + } + } + if (row < r) logits[static_cast(row) * e + expert] = acc; +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(256) tf_router_small_f16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_small<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_small_bf16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_small<2>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_tile_f16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_tile<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_tile_bf16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_tile<2>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_rows_f16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_rows<1>(x, rows, logits, r, d, e); +} + +extern "C" __global__ void __launch_bounds__(256) tf_router_rows_bf16(const void* x, const float* rows, float* logits, + int r, int d, int e) { + router_rows<2>(x, rows, logits, r, d, e); +} diff --git a/zig/kernels/hip/ops/norms.hpp b/zig/kernels/hip/ops/norms.hpp new file mode 100644 index 00000000000..f6af92bedc4 --- /dev/null +++ b/zig/kernels/hip/ops/norms.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include "common.hpp" + +// RMS norm rows, a wave a row. + +namespace { + +// rms_kernel's arithmetic a wave a row, 8 rows a block, so short rows do not hold a 256-thread block each. +__device__ void rms_rows(const void* x, int kind, const float* weight, void* y, int rows, int width, float eps) { + constexpr int kMost = 1024 / 32; + const int lane = threadIdx.x & 31; + const int row = blockIdx.x * 8 + (threadIdx.x >> 5); + if (row >= rows) return; + const long long at = static_cast(row) * width; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = i < width ? load(x, kind, at + i) : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i >= width) break; + float value = v[j] * inv; + if (weight != nullptr) value *= weight[i]; + store(y, kind, at + i, value); + } +} + +} // namespace + +extern "C" __global__ void __launch_bounds__(256) tf_rms_rows(const void* x, int kind, const float* weight, void* y, + int rows, int width, float eps) { + rms_rows(x, kind, weight, y, rows, width, eps); +} diff --git a/zig/kernels/hip/ops/ops.hip b/zig/kernels/hip/ops/ops.hip new file mode 100644 index 00000000000..a5e20960b11 --- /dev/null +++ b/zig/kernels/hip/ops/ops.hip @@ -0,0 +1,10 @@ +// The torch-op kernels as one code object: each job's header is part of this translation unit. + +#include "common.hpp" +#include "elementwise.hpp" +#include "attention.hpp" +#include "linear.hpp" +#include "rope.hpp" +#include "norms.hpp" +#include "moe.hpp" +#include "draw.hpp" diff --git a/zig/kernels/hip/ops/rope.hpp b/zig/kernels/hip/ops/rope.hpp new file mode 100644 index 00000000000..12b481e481d --- /dev/null +++ b/zig/kernels/hip/ops/rope.hpp @@ -0,0 +1,86 @@ +#pragma once + +#include "common.hpp" + +// RoPE for a prefill and the window's fused q / k norm and rotation. + +namespace { + +// apply_rope's prefill formula as torch has it, rounded to kind, stored as out_kind at h * s_head + r * s_row + j. +extern "C" __global__ void tf_rope_prefill(const void* x, int kind, void* out, int out_kind, long long s_head, long long s_row, + int len, int heads, int d, int rotary, int pos0, float theta) { + long long i = gid(); + if (i >= static_cast(len) * heads * d) return; + int j = static_cast(i % d); + int h = static_cast((i / d) % heads); + int r = static_cast(i / (static_cast(d) * heads)); + long long base = (static_cast(r) * heads + h) * d; + int half = rotary / 2; + float y; + if (j >= rotary) { + y = load(x, kind, base + j); + } else { + int f = j < half ? j : j - half; + float expo = static_cast(f) / static_cast(half); + float freq = 1.0f / powf(theta, expo); + float ang = static_cast(pos0 + r) * freq; + float c = cosf(ang), s = sinf(ang); + float x1 = load(x, kind, base + f), x2 = load(x, kind, base + f + half); + y = j < half ? x1 * c - x2 * s : x1 * s + x2 * c; + } + store(out, out_kind, h * s_head + r * s_row + j, rounded(y, kind)); +} + +// A window's q or k heads in one pass, a wave a (row, head): RMS norm, then rotation at its position, both rounded. +extern "C" __global__ void __launch_bounds__(256) tf_qk_rope(const void* src, int kind, long long s_row, int s_head, + const float* weight, float eps, int rows, int heads, int width, + int rotary, float theta, const int* pos, float* wide, + void* cache, int total) { + constexpr int kMost = 512 / 32; + __shared__ float row_v[8][512]; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + const int g = blockIdx.x * 8 + wave; + const bool live = g < rows * heads; + const int r = live ? g / heads : 0, h = live ? g % heads : 0; + const long long at = r * s_row + static_cast(h) * s_head; + float v[kMost]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + v[j] = live && i < width ? load(src, kind, at + i) : 0.f; + if (i < width) sum += v[j] * v[j]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + const float inv = rsqrtf(__shfl(sum, 0, 32) / static_cast(width) + eps); +#pragma unroll + for (int j = 0; j < kMost; ++j) { + const int i = lane + 32 * j; + if (i < width) row_v[wave][i] = rounded(v[j] * inv * weight[i], kind); + } + __syncthreads(); + if (!live) return; + const int p = pos[r]; + const int half = rotary >> 1; + float* out = wide ? wide + static_cast(g) * width : nullptr; + const long long slot = (static_cast(h) * total + p) * width; + auto put = [&](int i, float value) { + value = rounded(value, kind); + if (out) out[i] = value; + if (cache) store(cache, kind, slot + i, value); + }; + for (int i = lane; i < half; i += 32) { + float freq = 1.f / powf(theta, static_cast(i) / static_cast(half)); + float ang = static_cast(p) * freq; + float c = cosf(ang); + float sn = sinf(ang); + float x1 = row_v[wave][i]; + float x2 = row_v[wave][half + i]; + put(i, x1 * c - x2 * sn); + put(half + i, x1 * sn + x2 * c); + } + for (int i = rotary + lane; i < width; i += 32) put(i, row_v[wave][i]); +} + +} // namespace diff --git a/zig/kernels/hip/recurrence/gated_delta.hip b/zig/kernels/hip/recurrence/gated_delta.hip new file mode 100644 index 00000000000..79ab274e2ee --- /dev/null +++ b/zig/kernels/hip/recurrence/gated_delta.hip @@ -0,0 +1,302 @@ +// Gated DeltaNet: a wave per (batch, value head, value row) walks the sequence, lane sums as the Python reference. + +#include "decode/plan.hpp" + +#include + +namespace tf { +namespace rocm { + +__device__ float lane0_sum(float x) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) x += __shfl_xor(x, mask, 32); + return __shfl(x, 0, 32); +} + +template +__global__ void __launch_bounds__(32) +gated_delta_kernel(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ state, + float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states) { + constexpr int SPAN = (DK + 31) / 32; + const int lane = threadIdx.x; + const int row = blockIdx.x; + const int head = blockIdx.y; + const int batch = blockIdx.z; + if (row >= dv) return; + const int key_head = head / (value_heads / key_heads); + + float s[4] = {0.f, 0.f, 0.f, 0.f}; + const size_t state_row = + ((static_cast(batch) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = state[state_row + idx]; + } + + for (int t = 0; t < length; ++t) { + const size_t step = (static_cast(batch) * length + t) * value_heads + head; + const float decay = gate[step]; + const float step_beta = beta[step]; + const float value = v[(static_cast(batch) * length + t) * value_heads * dv + + static_cast(head) * dv + row]; + const size_t key = + ((static_cast(batch) * length + t) * key_heads + key_head) * DK; + + float remembered = 0.f; + float ks[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) { + ks[i] = k[key + idx]; + s[i] = s[i] * decay; + remembered = remembered + s[i] * ks[i]; + } + } + const float delta = (value - lane0_sum(remembered)) * step_beta; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = s[i] + ks[i] * delta; + } + if (states != nullptr) { + const size_t snap = (((static_cast(batch) * length + t) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) states[snap + idx] = s[i]; + } + } + + float readout = 0.f; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) readout = readout + s[i] * q[key + idx]; + } + // Every lane has to enter the shuffle. Lane 0 owns the stored sum. + readout = lane0_sum(readout); + if (lane == 0) { + y[(static_cast(batch) * length + t) * value_heads * dv + + static_cast(head) * dv + row] = readout; + } + } + +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) state[state_row + idx] = s[i]; + } +} + +// Value rows share a staged tile of k and q, in the wave kernel's order (-ffp-contract=off keeps it). +template +__device__ __forceinline__ void +gated_delta_tile_body(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ state, + float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states, int batch, bool write_back = true) { + constexpr int SPAN = (DK + 31) / 32; + constexpr int WIDTH = 32 * ROWS; + const int lane = threadIdx.x; + const int local = threadIdx.y; + const int row = blockIdx.x * ROWS + local; + const int head = blockIdx.y; + const int key_head = head / (value_heads / key_heads); + const int tid = local * 32 + lane; + + __shared__ float ks[STEPS][DK]; + __shared__ float qs[STEPS][DK]; + __shared__ float gs[STEPS]; + __shared__ float bs[STEPS]; + __shared__ float vs[STEPS][ROWS]; + + float s[4] = {0.f, 0.f, 0.f, 0.f}; + const size_t state_row = ((static_cast(batch) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = state[state_row + idx]; + } + + for (int t0 = 0; t0 < length; t0 += STEPS) { + const int n = min(STEPS, length - t0); + const int nvec = n * (DK / 4); + for (int i = tid; i < nvec; i += WIDTH) { + const int elem = i * 4; + const int step = elem / DK; + const int col = elem - step * DK; + const size_t at = + ((static_cast(batch) * length + (t0 + step)) * key_heads + key_head) * DK + col; + const float4 key = *reinterpret_cast(k + at); + ks[step][col] = key.x; + ks[step][col + 1] = key.y; + ks[step][col + 2] = key.z; + ks[step][col + 3] = key.w; + // a replay (no q) advances the state alone + if (q == nullptr) continue; + const float4 query = *reinterpret_cast(q + at); + qs[step][col] = query.x; + qs[step][col + 1] = query.y; + qs[step][col + 2] = query.z; + qs[step][col + 3] = query.w; + } + for (int i = tid; i < n; i += WIDTH) { + const size_t step = (static_cast(batch) * length + (t0 + i)) * value_heads + head; + gs[i] = gate[step]; + bs[i] = beta[step]; + } + for (int i = tid; i < n * ROWS; i += WIDTH) { + const int step = i / ROWS; + const int which = i - step * ROWS; + vs[step][which] = v[((static_cast(batch) * length + (t0 + step)) * value_heads + head) * dv + + blockIdx.x * ROWS + which]; + } + __syncthreads(); + + for (int tt = 0; tt < n; ++tt) { + const float decay = gs[tt]; + const float step_beta = bs[tt]; + const float value = vs[tt][local]; + float remembered = 0.f; + float held[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) { + held[i] = ks[tt][idx]; + s[i] = s[i] * decay; + remembered = remembered + s[i] * held[i]; + } + } + const float delta = (value - lane0_sum(remembered)) * step_beta; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) s[i] = s[i] + held[i] * delta; + } + if (states != nullptr) { + const size_t snap = + (((static_cast(batch) * length + (t0 + tt)) * value_heads + head) * dv + row) * DK; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) states[snap + idx] = s[i]; + } + } + if (q == nullptr) continue; + float readout = 0.f; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) readout = readout + s[i] * qs[tt][idx]; + } + readout = lane0_sum(readout); + if (lane == 0) { + y[((static_cast(batch) * length + (t0 + tt)) * value_heads + head) * dv + row] = readout; + } + } + __syncthreads(); + } + + if (!write_back) return; +#pragma unroll + for (int i = 0; i < SPAN; ++i) { + const int idx = lane + i * 32; + if (idx < DK) state[state_row + idx] = s[i]; + } +} + +template +__global__ void __launch_bounds__(32 * ROWS) +gated_delta_tile(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ state, + float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states) { + gated_delta_tile_body(q, k, v, gate, beta, state, y, length, key_heads, value_heads, dv, states, + blockIdx.z); +} + +// A round's windows in one launch, a grid plane a slot; rows, state and snapshots come from the plan, same scan. +template +__device__ __forceinline__ void +gated_delta_plan_body(const float* q, const float* k, const float* v, const float* gate, const float* beta, float* y, + int key_heads, int value_heads, int dv, PlanArgs plan, int layer) { + const int slot = blockIdx.z; + const int length = plan.count[slot]; + if (length == 0) return; + const long long row0 = plan.first[slot]; + const unsigned long long* desc = plan_desc(plan, slot); + float* state = reinterpret_cast(desc[plan_second(layer)]); + // a window of rows leaves the state as the round found it, for its keep to replay (padding rows keep nothing) + const bool replayed = length > 1 && slot + 1 < static_cast(gridDim.z); + gated_delta_tile_body(q + row0 * key_heads * DK, k + row0 * key_heads * DK, v + row0 * value_heads * dv, + gate + row0 * value_heads, beta + row0 * value_heads, state, + y + row0 * value_heads * dv, length, key_heads, value_heads, dv, nullptr, 0, + !replayed); +} + +// A keep: each slot's state run from the round's start through its kept rows, by the same scan on the inputs kept. +template +__device__ __forceinline__ void gated_delta_replay_body(const int* keep, int rows, int key_heads, int value_heads, int dv, + PlanArgs plan, int slots) { + const int slot = blockIdx.z % slots; + const int layer = blockIdx.z / slots; + const int n = keep[slot]; + if (n <= 0 || plan.count[slot] <= 1 || plan.snaps[2 * layer + 1] == 0) return; + const long long row0 = plan.first[slot]; + const float* k = reinterpret_cast(plan.snaps[2 * layer + 1]); + const float* v = k + static_cast(rows) * key_heads * DK; + const float* gate = v + static_cast(rows) * value_heads * dv; + const float* beta = gate + static_cast(rows) * value_heads; + float* state = reinterpret_cast(plan_desc(plan, slot)[plan_second(layer)]); + gated_delta_tile_body(nullptr, k + row0 * key_heads * DK, v + row0 * value_heads * dv, + gate + row0 * value_heads, beta + row0 * value_heads, state, nullptr, n, key_heads, + value_heads, dv, nullptr, 0); +} + +} // namespace rocm +} // namespace tf + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_plan_128(const float* q, const float* k, const float* v, const float* gate, const float* beta, float* y, + int key_heads, int value_heads, int dv, PlanArgs plan, int layer) { + tf::rocm::gated_delta_plan_body<128>(q, k, v, gate, beta, y, key_heads, value_heads, dv, plan, layer); +} + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_replay_128(const int* keep, int rows, int key_heads, int value_heads, int dv, PlanArgs plan, int slots) { + tf::rocm::gated_delta_replay_body<128>(keep, rows, key_heads, value_heads, dv, plan, slots); +} + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_replay_16(const int* keep, int rows, int key_heads, int value_heads, int dv, PlanArgs plan, int slots) { + tf::rocm::gated_delta_replay_body<16>(keep, rows, key_heads, value_heads, dv, plan, slots); +} + +extern "C" __global__ void __launch_bounds__(256) +tf_gdn_plan_16(const float* q, const float* k, const float* v, const float* gate, const float* beta, float* y, + int key_heads, int value_heads, int dv, PlanArgs plan, int layer) { + tf::rocm::gated_delta_plan_body<16>(q, k, v, gate, beta, y, key_heads, value_heads, dv, plan, layer); +} + +// The template kernels launches.zig resolves. +template __global__ void tf::rocm::gated_delta_tile<128, 8, 16>(const float* __restrict__ q, + const float* __restrict__ k, const float* __restrict__ v, const float* __restrict__ gate, + const float* __restrict__ beta, float* __restrict__ state, float* __restrict__ y, int length, int key_heads, + int value_heads, int dv, float* __restrict__ states); +template __global__ void tf::rocm::gated_delta_tile<16, 8, 16>(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ state, float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states); +template __global__ void tf::rocm::gated_delta_kernel<128>(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ state, float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states); +template __global__ void tf::rocm::gated_delta_kernel<16>(const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ state, float* __restrict__ y, int length, int key_heads, int value_heads, int dv, + float* __restrict__ states); diff --git a/zig/src/hip/admission_tests.zig b/zig/src/hip/admission_tests.zig index 9d55184ec7e..3853a524a49 100644 --- a/zig/src/hip/admission_tests.zig +++ b/zig/src/hip/admission_tests.zig @@ -11,6 +11,9 @@ test { _ = @import("runtime.zig"); _ = @import("launch.zig"); _ = @import("graph.zig"); + _ = @import("arena.zig"); + _ = @import("launches.zig"); + _ = @import("ops/ops.zig"); _ = @import("context.zig").Context.init; _ = @import("stream.zig").Stream.init; _ = @import("memory.zig").DeviceBuffer.alloc; diff --git a/zig/src/hip/arena.zig b/zig/src/hip/arena.zig new file mode 100644 index 00000000000..ecd192fc66a --- /dev/null +++ b/zig/src/hip/arena.zig @@ -0,0 +1,74 @@ +//! A forward's scratch handed out front to back and reset per forward, so a captured graph replays the same addresses. + +const std = @import("std"); +const runtime = @import("runtime.zig"); +const DeviceBuffer = @import("memory.zig").DeviceBuffer; + +pub const Arena = struct { + /// Null for a counting arena. + buf: ?DeviceBuffer, + base: u64, + len: usize, + used: usize = 0, + peak: usize = 0, + + pub fn init(r: *const runtime.Runtime, bytes: usize) runtime.Error!Arena { + const buf = try DeviceBuffer.alloc(r, bytes); + return .{ .buf = buf, .base = @intFromPtr(buf.ptr), .len = bytes }; + } + + /// An arena with no memory behind it, for a forward on the counting stream: its peak is what the forward takes. + pub fn counting() Arena { + return .{ .buf = null, .base = 1 << 40, .len = 1 << 60 }; + } + + pub fn deinit(self: *Arena) void { + if (self.buf) |*b| b.free(); + self.* = undefined; + } + + /// `bytes` 256-byte aligned; refused past the end (the caller sized the arena for its largest forward). + pub fn take(self: *Arena, bytes: usize) error{OutOfDeviceMemory}!u64 { + const at = std.mem.alignForward(usize, self.used, 256); + if (at + bytes > self.len) { + std.log.err("scratch arena of {d} bytes cannot take {d} more at {d}", .{ self.len, bytes, at }); + return error.OutOfDeviceMemory; + } + self.used = at + bytes; + self.peak = @max(self.peak, self.used); + return self.base + at; + } + + /// `n` values of `T`. + pub fn of(self: *Arena, comptime T: type, n: usize) error{OutOfDeviceMemory}!u64 { + return self.take(n * @sizeOf(T)); + } + + pub fn reset(self: *Arena) void { + self.used = 0; + } + + /// The current mark, to hand scratch back after a step that needs it only briefly. + pub fn mark(self: *const Arena) usize { + return self.used; + } + + pub fn release(self: *Arena, at: usize) void { + std.debug.assert(at <= self.used); + self.used = at; + } +}; + +test "scratch comes front to back, 256-byte aligned, and is refused past the end" { + var a = Arena.counting(); + a.len = 1000; + try std.testing.expectEqual(@as(u64, 1 << 40), try a.take(10)); + try std.testing.expectEqual(@as(u64, (1 << 40) + 256), try a.of(f32, 4)); + const m = a.mark(); + _ = try a.take(300); + a.release(m); + try std.testing.expectEqual(@as(usize, 272), a.used); + try std.testing.expectEqual(@as(usize, 512 + 300), a.peak); + a.reset(); + try std.testing.expectEqual(@as(usize, 0), a.used); +} diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig new file mode 100644 index 00000000000..e2009e27f7e --- /dev/null +++ b/zig/src/hip/kernel_tests.zig @@ -0,0 +1,26 @@ +//! The model-free kernels on a real GPU: every kernel resolves, and each launch matches its host reference. +const std = @import("std"); +const Runtime = @import("runtime.zig").Runtime; +const Context = @import("context.zig").Context; +const kernels = @import("kernels.zig"); +const Launcher = @import("launches.zig").Launcher; + +test "the code objects load on this device and every kernel the launchers use resolves" { + var r = try Runtime.open(); + defer r.close(); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + var arch_buffer: [256]u8 = undefined; + const arch = try @import("device_arch.zig").query(&r, 0, &arch_buffer); + try std.testing.expectEqualStrings(kernels.arch, arch); + var l = try Launcher.load(&r, .{}, kernels.images); + defer l.unload(); +} + +test { + _ = @import("kernel_tests/gdn.zig"); + _ = @import("kernel_tests/decode.zig"); + _ = @import("kernel_tests/chain.zig"); + _ = @import("kernel_tests/attention.zig"); + _ = @import("kernel_tests/ops.zig"); +} diff --git a/zig/src/hip/kernel_tests/attention.zig b/zig/src/hip/kernel_tests/attention.zig new file mode 100644 index 00000000000..b46fda64c2c --- /dev/null +++ b/zig/src/hip/kernel_tests/attention.zig @@ -0,0 +1,225 @@ +//! Attention: planned decode over pages and the paged prompt tile against their flat forms (same bits) and float64. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const plan = @import("../launches/plan.zig"); +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; + +const page = 64; + +/// A cache of `kv_heads` heads and `span` positions in the activation type, flat (kv_heads, span, d) and paged. +const Cache = struct { + k: []u16, + v: []u16, + /// Position block i lives in page table[i]. + table: []u32, + + fn make(t: *Rig, rng: *rig.Rng, kv_heads: usize, span: usize, d: usize) !Cache { + const c: Cache = .{ .k = try gpa.alloc(u16, kv_heads * span * d), .v = try gpa.alloc(u16, kv_heads * span * d), .table = try gpa.alloc(u32, span / page) }; + for (c.k) |*x| x.* = t.bits(rng.unit()); + for (c.v) |*x| x.* = t.bits(rng.unit()); + // a permutation, so a walk that ignored the table would read the wrong keys + for (c.table, 0..) |*p, i| p.* = @intCast((i * 5 + 3) % c.table.len); + return c; + } + + fn free(c: Cache) void { + gpa.free(c.k); + gpa.free(c.v); + gpa.free(c.table); + } + + /// The pool layout of decode/pages.hpp: ((h * count + page) * 64 + slot) * d. + fn pool(c: Cache, src: []const u16, kv_heads: usize, span: usize, d: usize) ![]u16 { + const out = try gpa.alloc(u16, src.len); + const count = span / page; + for (0..kv_heads) |h| for (0..span) |pos| { + const to = ((h * count + c.table[pos / page]) * page + pos % page) * d; + @memcpy(out[to..][0..d], src[(h * span + pos) * d ..][0..d]); + }; + return out; + } +}; + +/// softmax(q . k * scale) v in float64 for one query of `head` seeing positions [0, visible). +fn reference(t: *const Rig, c: Cache, q: []const f32, head: usize, group: usize, span: usize, d: usize, visible: usize, scale: f64, out: []f64) void { + const kv = head / group; + var top: f64 = -std.math.inf(f64); + var scores: [4096]f64 = undefined; + for (0..visible) |key| { + var dot: f64 = 0; + for (0..d) |j| dot += @as(f64, q[j]) * t.value(c.k[(kv * span + key) * d + j]); + scores[key] = dot * scale; + top = @max(top, scores[key]); + } + var sum: f64 = 0; + for (scores[0..visible]) |*s| { + s.* = @exp(s.* - top); + sum += s.*; + } + @memset(out[0..d], 0); + for (0..visible) |key| for (0..d) |j| { + out[j] += scores[key] / sum * t.value(c.v[(kv * span + key) * d + j]); + }; +} + +fn worst(got: []const f32, want: []const f64) f64 { + var scale: f64 = 0; + var max: f64 = 0; + for (got, want) |g, w| { + max = @max(max, @abs(@as(f64, g) - w)); + scale = @max(scale, @abs(w)); + } + return max / scale; +} + +/// Rows at positions `pos` over one slot's cache: the planned walk (grouped heads, pages) and the flat walk agree. +fn decode(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, d: usize, pos: []const i32) !void { + const span: usize = 1024; + const rows = pos.len; + const group = heads / kv_heads; + const scale: f32 = 1 / @sqrt(@as(f32, @floatFromInt(d))); + const c = try Cache.make(t, rng, kv_heads, span, d); + defer c.free(); + const hq = try gpa.alloc(f32, rows * heads * d); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + var q = try t.upload(hq); + defer q.free(); + var k = try t.upload(c.k); + defer k.free(); + var v = try t.upload(c.v); + defer v.free(); + const pk = try c.pool(c.k, kv_heads, span, d); + defer gpa.free(pk); + const pv = try c.pool(c.v, kv_heads, span, d); + defer gpa.free(pv); + var pool_k = try t.upload(pk); + defer pool_k.free(); + var pool_v = try t.upload(pv); + defer pool_v.free(); + // one slot: descriptor [cached, kept, k pool, v pool], then its page table + const words = 4; + const desc = try gpa.alloc(u64, words + (c.table.len + 1) / 2); + defer gpa.free(desc); + @memset(desc, 0); + desc[2] = at(pool_k); + desc[3] = at(pool_v); + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. c.table.len * 4], std.mem.sliceAsBytes(c.table)); + var dev_desc = try t.upload(desc); + defer dev_desc.free(); + const desc_ptr = [_]u64{at(dev_desc)}; + var descs = try t.upload(&desc_ptr); + defer descs.free(); + var dev_pos = try t.upload(pos); + defer dev_pos.free(); + const zeros = try gpa.alloc(i32, rows); + defer gpa.free(zeros); + @memset(zeros, 0); + var slot = try t.upload(zeros); + defer slot.free(); + const first = [_]i32{0}; + const count = [_]i32{@intCast(rows)}; + var dev_first = try t.upload(&first); + defer dev_first.free(); + var dev_count = try t.upload(&count); + defer dev_count.free(); + const tiles = span / 128; + var scores = try t.alloc(rows * heads * span * 4); + defer scores.free(); + var stats = try t.alloc(rows * heads * 2 * 4); + defer stats.free(); + var partials = try t.alloc(rows * heads * tiles * d * 4); + defer partials.free(); + var outs: [2]DeviceBuffer = .{ try t.alloc(rows * heads * d * 4), try t.alloc(rows * heads * d * 4) }; + defer for (&outs) |*o| o.free(); + const s = t.stream.handle; + try t.on.tf_causal(@ptrFromInt(at(q)), @ptrFromInt(at(k)), @ptrFromInt(at(v)), @ptrFromInt(at(outs[0])), @intCast(rows), 1, @intCast(span), @intCast(heads), @intCast(kv_heads), @intCast(d), scale, 0, 0, @intCast(span * d), @intCast(d), 0, @intCast(span * d), @intCast(d), if (t.bf16) 1 else 0, @ptrFromInt(at(scores)), @ptrFromInt(at(stats)), @ptrFromInt(at(partials)), s, @ptrFromInt(at(dev_pos))); + const p: plan.PlanRef = .{ .rows = rows, .slots = 1, .args = .{ .pos = at(dev_pos), .slot = at(slot), .first = at(dev_first), .count = at(dev_count), .desc = at(descs), .pages = words, .pool = @intCast(c.table.len) } }; + try t.on.planCausal(at(q), at(outs[1]), at(scores), at(stats), at(partials), p, 0, heads, kv_heads, d, span, scale, t.kind(), s); + try t.stream.synchronize(); + const flat = try rig.download(f32, outs[0]); + defer gpa.free(flat); + const planned = try rig.download(f32, outs[1]); + defer gpa.free(planned); + try std.testing.expectEqualSlices(u32, @ptrCast(flat), @ptrCast(planned)); + const want = try gpa.alloc(f64, rows * heads * d); + defer gpa.free(want); + for (0..rows) |r| for (0..heads) |h| { + const at_q = (r * heads + h) * d; + reference(t, c, hq[at_q..][0..d], h, group, span, d, @intCast(pos[r] + 1), scale, want[at_q..][0..d]); + }; + try std.testing.expect(worst(planned, want) < 1e-5); +} + +test "the planned decode walk over pages writes the flat walk's bits for grouped heads, within 1e-5 of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0xA77E57 }; + const pos = [_]i32{ 0, 37, 300, 1023 }; + try decode(t, &rng, 16, 2, 256, &pos); // 8 query heads a KV head, Qwen3.6-35B-A3B's attention + try decode(t, &rng, 24, 4, 256, &pos); // 6, Qwen3.8-27B + try decode(t, &rng, 16, 4, 128, &pos); // 4 + try decode(t, &rng, 4, 4, 128, &pos); // no sharing +} + +/// A prompt of `qlen` queries from `q_pos0` over `span` positions: the paged 64-row tile writes the flat tile's bits. +fn prompt(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, d: usize, qlen: usize, q_pos0: usize) !void { + const span = q_pos0 + qlen; + const group = heads / kv_heads; + const scale: f32 = 1 / @sqrt(@as(f32, @floatFromInt(d))); + const c = try Cache.make(t, rng, kv_heads, span, d); + defer c.free(); + const hq = try gpa.alloc(f32, heads * qlen * d); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + var q = try t.upload(hq); + defer q.free(); + var k = try t.upload(c.k); + defer k.free(); + var v = try t.upload(c.v); + defer v.free(); + const pk = try c.pool(c.k, kv_heads, span, d); + defer gpa.free(pk); + const pv = try c.pool(c.v, kv_heads, span, d); + defer gpa.free(pv); + var pool_k = try t.upload(pk); + defer pool_k.free(); + var pool_v = try t.upload(pv); + defer pool_v.free(); + var table = try t.upload(c.table); + defer table.free(); + var outs: [2]DeviceBuffer = .{ try t.alloc(heads * qlen * d * 4), try t.alloc(heads * qlen * d * 4) }; + defer for (&outs) |*o| o.free(); + const s = t.stream.handle; + const kind: c_int = if (t.bf16) 1 else 0; + try t.on.tf_causal(@ptrFromInt(at(q)), @ptrFromInt(at(k)), @ptrFromInt(at(v)), @ptrFromInt(at(outs[0])), 1, @intCast(qlen), @intCast(span), @intCast(heads), @intCast(kv_heads), @intCast(d), scale, @intCast(q_pos0), 0, @intCast(span * d), @intCast(d), 0, @intCast(span * d), @intCast(d), kind, null, null, null, s, null); + try t.on.pagedCausal(at(q), at(pool_k), at(pool_v), at(table), at(outs[1]), qlen, span, heads, kv_heads, d, scale, q_pos0, c.table.len, kind, s); + try t.stream.synchronize(); + const flat = try rig.download(f32, outs[0]); + defer gpa.free(flat); + const paged = try rig.download(f32, outs[1]); + defer gpa.free(paged); + try std.testing.expectEqualSlices(u32, @ptrCast(flat), @ptrCast(paged)); + // the tile rounds q to the cache's type once, so it sits within that type's rounding of float64 + const want = try gpa.alloc(f64, heads * qlen * d); + defer gpa.free(want); + for (0..heads) |h| for (0..qlen) |i| { + const at_q = (h * qlen + i) * d; + reference(t, c, hq[at_q..][0..d], h, group, span, d, q_pos0 + i + 1, scale, want[at_q..][0..d]); + }; + const bound: f64 = if (t.bf16) 2e-2 else 4e-3; + try std.testing.expect(worst(paged, want) < bound); +} + +test "the paged prompt tile writes the flat tile's bits, within the cache type's rounding of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9A6ED }; + try prompt(t, &rng, 16, 2, 256, 128, 0); + try prompt(t, &rng, 16, 2, 256, 64, 192); + try prompt(t, &rng, 24, 4, 256, 192, 64); + try prompt(t, &rng, 16, 4, 128, 128, 128); +} diff --git a/zig/src/hip/kernel_tests/chain.zig b/zig/src/hip/kernel_tests/chain.zig new file mode 100644 index 00000000000..c2edd65a083 --- /dev/null +++ b/zig/src/hip/kernel_tests/chain.zig @@ -0,0 +1,222 @@ +//! The merged linear-attention and MoE-pick launches against the chains they replace: the same bytes. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; + +fn same(a: DeviceBuffer, b: DeviceBuffer) !void { + const ha = try rig.download(u8, a); + defer gpa.free(ha); + const hb = try rig.download(u8, b); + defer gpa.free(hb); + try std.testing.expectEqualSlices(u8, ha, hb); +} + +fn ptr(v: u64) ?*anyopaque { + return @ptrFromInt(v); +} + +/// The pick rule over `rows` rows of (experts + 1) logits: picks, weights, items and members alike. +fn select(t: *Rig, rng: *rig.Rng, rows: usize, experts: usize, top_k: usize) !void { + const slots = top_k + 1; + const capacity = slots + 7; + const logits = try gpa.alloc(f32, rows * (experts + 1)); + defer gpa.free(logits); + for (logits) |*v| v.* = rng.unit() * 4.0; + // equal logits: the lower index wins + for (0..rows) |r| logits[r * (experts + 1) + 5] = logits[r * (experts + 1) + 9]; + var dev_logits = try t.upload(logits); + defer dev_logits.free(); + var picks: [2]DeviceBuffer = undefined; + var wts: [2]DeviceBuffer = undefined; + var items: [2]DeviceBuffer = undefined; + var members: [2]DeviceBuffer = undefined; + for (0..2) |v| { + picks[v] = try t.alloc(rows * slots * 4); + wts[v] = try t.alloc(rows * slots * 4); + items[v] = try t.alloc(capacity * 12); + members[v] = try t.alloc(capacity * 4); + try members[v].fill8(0); + } + defer for (0..2) |v| { + picks[v].free(); + wts[v].free(); + items[v].free(); + members[v].free(); + }; + const plan = rows == 1; + for ([2]*const @import("../launches.zig").Launcher{ &t.off, &t.on }, 0..) |l, v| { + try l.tf_moe_select(@ptrFromInt(at(dev_logits)), @ptrFromInt(at(picks[v])), @ptrFromInt(at(wts[v])), if (plan) @ptrFromInt(at(items[v])) else null, if (plan) @ptrFromInt(at(members[v])) else null, @intCast(capacity), @intCast(rows), @intCast(experts), @intCast(top_k), t.stream.handle); + } + try t.stream.synchronize(); + try same(picks[0], picks[1]); + try same(wts[0], wts[1]); + if (plan) { + try same(items[0], items[1]); + try same(members[0], members[1]); + } +} + +/// A window's conv chain (cast, conv, three column copies, q and k norms, gate) against one launch. +fn conv(t: *Rig, rng: *rig.Rng, rows: usize) !void { + const kw: usize = 2048; + const vw: usize = 4096; + const ch = 2 * kw + vw; + const kernel: usize = 4; + const eps: f32 = 1e-6; + const vheads: usize = 32; + const hx = try gpa.alloc(u16, rows * ch); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit() * 2.0); + const hw = try gpa.alloc(f32, ch * kernel); + defer gpa.free(hw); + for (hw) |*v| v.* = rng.unit() / 2.0; + const hs = try gpa.alloc(f32, (kernel - 1) * ch); + defer gpa.free(hs); + for (hs) |*v| v.* = rng.unit(); + const hn = try gpa.alloc(f32, 128 * 2); + defer gpa.free(hn); + for (hn) |*v| v.* = 1.0 + rng.unit() / 4.0; + const ha = try gpa.alloc(u16, rows * vheads); + defer gpa.free(ha); + for (ha) |*v| v.* = t.bits(rng.unit() * 3.0); + const hb = try gpa.alloc(u16, rows * vheads); + defer gpa.free(hb); + for (hb) |*v| v.* = t.bits(rng.unit() * 3.0); + const hlog = try gpa.alloc(f32, vheads * 2); + defer gpa.free(hlog); + for (hlog) |*v| v.* = rng.unit(); + var x = try t.upload(hx); + defer x.free(); + var weight = try t.upload(hw); + defer weight.free(); + var norm = try t.upload(hn); + defer norm.free(); + var dev_a = try t.upload(ha); + defer dev_a.free(); + var dev_b = try t.upload(hb); + defer dev_b.free(); + var dev_log = try t.upload(hlog); + defer dev_log.free(); + var xr = try t.alloc(rows * ch * 4); + defer xr.free(); + var mixed = try t.alloc(rows * ch * 4); + defer mixed.free(); + var bufs: [2][9]DeviceBuffer = undefined; // gate, beta, state, snaps, qc, kc, v, qn, kn + for (0..2) |v| { + bufs[v] = .{ + try t.alloc(rows * vheads * 4), try t.alloc(rows * vheads * 4), try t.upload(hs), + try t.alloc(rows * (kernel - 1) * ch * 4), try t.alloc(rows * kw * 4), try t.alloc(rows * kw * 4), + try t.alloc(rows * vw * 4), try t.alloc(rows * kw * 4), try t.alloc(rows * kw * 4), + }; + } + defer for (&bufs) |*set| for (set) |*b| b.free(); + const s = t.stream.handle; + const l = &t.on; + const heads = rows * (kw / 128); + const kind = t.kind(); + { + const b = bufs[0]; + try l.tf_cast(ptr(at(x)), kind, ptr(at(xr)), 0, @intCast(rows * ch), s); + if (rows == 1) { + try l.tf_conv_decode(@ptrFromInt(at(xr)), @ptrFromInt(at(weight)), @ptrFromInt(at(b[2])), @ptrFromInt(at(mixed)), 1, @intCast(ch), @intCast(kernel), s); + } else { + try l.tf_conv_rows(@ptrFromInt(at(xr)), @ptrFromInt(at(weight)), @ptrFromInt(at(b[2])), @ptrFromInt(at(mixed)), @ptrFromInt(at(b[3])), @intCast(rows), @intCast(ch), @intCast(kernel), s); + } + try l.tf_copy_cols(ptr(at(mixed)), @intCast(ch), 0, ptr(at(b[4])), 0, @intCast(rows), @intCast(kw), s); + try l.tf_copy_cols(ptr(at(mixed)), @intCast(ch), @intCast(kw), ptr(at(b[5])), 0, @intCast(rows), @intCast(kw), s); + try l.tf_copy_cols(ptr(at(mixed)), @intCast(ch), @intCast(2 * kw), ptr(at(b[6])), 0, @intCast(rows), @intCast(vw), s); + try l.tf_rms(ptr(at(b[4])), @ptrFromInt(at(norm)), ptr(at(b[7])), 0, @intCast(heads), 128, eps, s); + try l.tf_rms(ptr(at(b[5])), @ptrFromInt(at(norm) + 512), ptr(at(b[8])), 0, @intCast(heads), 128, eps, s); + try l.tf_gdn_gate(ptr(at(dev_a)), ptr(at(dev_b)), kind, @ptrFromInt(at(dev_log)), @ptrFromInt(at(dev_log) + 128), @ptrFromInt(at(b[0])), @ptrFromInt(at(b[1])), @intCast(rows * 32), 32, s); + } + { + const b = bufs[1]; + try l.tf_conv_split(.{ + .x = at(x), + .kind = kind, + .weight = at(weight), + .state = at(b[2]), + .states = if (rows > 1) at(b[3]) else 0, + .qn = at(b[7]), + .kn = at(b[8]), + .v = at(b[6]), + .channels = @intCast(ch), + .kernel = @intCast(kernel), + .rows = @intCast(rows), + .kw = @intCast(kw), + .vw = @intCast(vw), + .qw = at(norm), + .kw_w = at(norm) + 512, + .eps = eps, + .norm = 128, + .ga = at(dev_a), + .gb = at(dev_b), + .a_log = at(dev_log), + .dt_bias = at(dev_log) + 128, + .gate = at(b[0]), + .beta = at(b[1]), + .gcount = @intCast(rows * 32), + .heads = 32, + }, s); + } + try t.stream.synchronize(); + // gate, beta, state, snapshots (several rows only), v, q norm, k norm + for ([_]usize{ 0, 1, 2, 6, 7, 8 }) |i| try same(bufs[0][i], bufs[1][i]); + if (rows > 1) try same(bufs[0][3], bufs[1][3]); +} + +/// The linear attention's gated norm: rms then gnorm_silu against one launch. +fn gnorm(t: *Rig, rng: *rig.Rng, rows: usize) !void { + const n = rows * 32 * 128; + const eps: f32 = 1e-6; + const hy = try gpa.alloc(f32, n); + defer gpa.free(hy); + for (hy) |*v| v.* = rng.unit() * 3.0; + const hz = try gpa.alloc(u16, n); + defer gpa.free(hz); + for (hz) |*v| v.* = t.bits(rng.unit() * 4.0); + const hn = try gpa.alloc(f32, 128); + defer gpa.free(hn); + for (hn) |*v| v.* = 1.0 + rng.unit() / 4.0; + var y = try t.upload(hy); + defer y.free(); + var z = try t.upload(hz); + defer z.free(); + var weight = try t.upload(hn); + defer weight.free(); + var yn = try t.alloc(n * 4); + defer yn.free(); + var outs: [2]DeviceBuffer = .{ try t.alloc(n * 2), try t.alloc(n * 2) }; + defer for (&outs) |*o| o.free(); + const s = t.stream.handle; + try t.on.tf_rms(ptr(at(y)), @ptrFromInt(at(weight)), ptr(at(yn)), 0, @intCast(rows * 32), 128, eps, s); + try t.on.tf_gnorm_silu(@ptrFromInt(at(yn)), ptr(at(z)), ptr(at(outs[0])), t.kind(), @intCast(n), s); + try t.on.tf_gnorm_out(@ptrFromInt(at(y)), @ptrFromInt(at(weight)), ptr(at(z)), ptr(at(outs[1])), t.kind(), @intCast(rows * 32), 128, eps, s); + try t.stream.synchronize(); + try same(outs[0], outs[1]); +} + +test "the merged MoE pick writes the scanning kernel's picks, weights, items and members" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 4, 16 }) |rows| try select(t, &rng, rows, 256, 8); + try select(t, &rng, 1, 128, 6); +} + +test "the merged conv split writes the chain's state, snapshots, q, k, v, gate and beta" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4, 16 }) |rows| try conv(t, &rng, rows); +} + +test "the merged gated norm writes rms then gnorm_silu's bytes" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 4, 16, 128 }) |rows| try gnorm(t, &rng, rows); +} diff --git a/zig/src/hip/kernel_tests/decode.zig b/zig/src/hip/kernel_tests/decode.zig new file mode 100644 index 00000000000..f7693e989e8 --- /dev/null +++ b/zig/src/hip/kernel_tests/decode.zig @@ -0,0 +1,135 @@ +//! The merged decode-step launches against the launches they replace, each against a float64 reference. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const Launcher = @import("../launches.zig").Launcher; + +fn p(b: anytype) ?*anyopaque { + return @ptrFromInt(at(b)); +} + +/// The router's logits for `rows` rows over (experts, d) fp32 weights: the merged launch no further from float64. +fn router(t: *Rig, rng: *rig.Rng, rows: usize, d: usize, experts: usize) !void { + const hx = try gpa.alloc(u16, rows * d); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + const hw = try gpa.alloc(f32, experts * d); + defer gpa.free(hw); + for (hw) |*v| v.* = rng.unit() / 8.0; + var x = try t.upload(hx); + defer x.free(); + var w = try t.upload(hw); + defer w.free(); + var max_err: [2]f64 = .{ 0, 0 }; + for ([2]*const Launcher{ &t.off, &t.on }, 0..) |l, v| { + var out = try t.alloc(rows * experts * 4); + defer out.free(); + try l.tf_moe_router(p(x), t.kind(), @ptrFromInt(at(w)), @ptrFromInt(at(out)), @intCast(rows), @intCast(d), @intCast(experts), t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(f32, out); + defer gpa.free(got); + for (0..rows) |r| for (0..experts) |e| { + var y: f64 = 0; + var norm: f64 = 0; + for (0..d) |i| { + const term = t.value(hx[r * d + i]) * @as(f64, hw[e * d + i]); + y += term; + norm += @abs(term); + } + max_err[v] = @max(max_err[v], @abs(@as(f64, got[r * experts + e]) - y) / norm); + }; + } + try std.testing.expect(max_err[1] <= 2 * max_err[0] + 1e-9); +} + +/// x = x + y (or the slots' weighted sum) and the next norm: one merged launch against combine, add and norm. +fn tails(t: *Rig, rng: *rig.Rng, rows: usize, width: usize, slots: usize) !void { + const n = rows * width; + const eps: f32 = 1e-6; + const hx = try gpa.alloc(u16, n); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + const hy16 = try gpa.alloc(u16, if (slots > 0) 0 else n); + defer gpa.free(hy16); + const hy32 = try gpa.alloc(f32, if (slots > 0) rows * slots * width else 0); + defer gpa.free(hy32); + for (hy16) |*v| v.* = t.bits(rng.unit() / 8.0); + for (hy32) |*v| v.* = rng.unit() / 8.0; + const hw = try gpa.alloc(f32, rows * @max(slots, 1)); + defer gpa.free(hw); + for (hw) |*v| v.* = (rng.unit() + 1.0) / @as(f32, @floatFromInt(@max(slots, 1))); + const hn = try gpa.alloc(f32, width); + defer gpa.free(hn); + for (hn) |*v| v.* = 1.0 + rng.unit() / 4.0; + var y = if (slots > 0) try t.upload(hy32) else try t.upload(hy16); + defer y.free(); + var wts = try t.upload(hw); + defer wts.free(); + var weight = try t.upload(hn); + defer weight.free(); + var tmp = try t.alloc(n * 2); + defer tmp.free(); + var errs: [2][2]f64 = .{ .{ 0, 0 }, .{ 0, 0 } }; + for (0..2) |v| { + var x = try t.upload(hx); + defer x.free(); + var normed = try t.alloc(n * 2); + defer normed.free(); + const s = t.stream.handle; + if (v == 0) { + const sum = if (slots > 0) p(tmp) else p(y); + if (slots > 0) try t.off.tf_moe_combine(@ptrFromInt(at(y)), @ptrFromInt(at(wts)), sum, t.kind(), @intCast(rows), @intCast(slots), @intCast(width), s); + try t.off.tf_add(p(x), sum, p(x), t.kind(), @intCast(n), s); + try t.off.tf_rms(p(x), @ptrFromInt(at(weight)), p(normed), t.kind(), @intCast(rows), @intCast(width), eps, s); + } else { + try t.on.tf_tail(p(x), p(y), if (slots > 0) @ptrFromInt(at(wts)) else null, @ptrFromInt(at(weight)), p(normed), t.kind(), @intCast(rows), @intCast(slots), @intCast(width), eps, s); + } + try t.stream.synchronize(); + const gx = try rig.download(u16, x); + defer gpa.free(gx); + const gn = try rig.download(u16, normed); + defer gpa.free(gn); + const want = try gpa.alloc(f64, width); + defer gpa.free(want); + for (0..rows) |r| { + var sq: f64 = 0; + var top: f64 = 0; + for (0..width) |c| { + var add: f64 = 0; + if (slots > 0) { + for (0..slots) |sl| add += @as(f64, hy32[(r * slots + sl) * width + c]) * @as(f64, hw[r * slots + sl]); + } else add = t.value(hy16[r * width + c]); + want[c] = t.value(hx[r * width + c]) + add; + sq += want[c] * want[c]; + top = @max(top, @abs(want[c])); + } + const inv = 1.0 / @sqrt(sq / @as(f64, @floatFromInt(width)) + eps); + for (0..width) |c| { + errs[v][0] = @max(errs[v][0], @abs(t.value(gx[r * width + c]) - want[c]) / top); + errs[v][1] = @max(errs[v][1], @abs(t.value(gn[r * width + c]) - want[c] * inv * hn[c]) / (top * inv * 1.25)); + } + } + } + try std.testing.expect(errs[1][0] <= 2 * errs[0][0] + 1e-7); + try std.testing.expect(errs[1][1] <= 2 * errs[0][1] + 1e-7); +} + +test "the merged router launch is no further from float64 than twice the launch it replaces" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4, 8 }) |rows| try router(t, &rng, rows, 2048, 257); +} + +test "the merged residual-and-norm tails are no further from float64 than twice the launches they replace" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 4, 16 }) |rows| { + try tails(t, &rng, rows, 2048, 0); + try tails(t, &rng, rows, 2048, 9); + } + try tails(t, &rng, 1, 4096, 0); +} diff --git a/zig/src/hip/kernel_tests/gdn.zig b/zig/src/hip/kernel_tests/gdn.zig new file mode 100644 index 00000000000..fe6b8922da6 --- /dev/null +++ b/zig/src/hip/kernel_tests/gdn.zig @@ -0,0 +1,197 @@ +//! The DeltaNet recurrence against a float64 recurrence on random inputs, and the same bits however a prompt is cut. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; + +const d = 128; +const Shape = struct { length: usize, key_heads: usize, value_heads: usize }; + +const Inputs = struct { + q: []f32, + k: []f32, + v: []f32, + gate: []f32, + beta: []f32, + state: []f32, + + /// L2-normalized q and k, gates exp(-A softplus(x)) in (0, 1], beta = sigmoid, a state of 0.1 scale. + fn make(sh: Shape, seed: u64) !Inputs { + var rng: rig.Rng = .{ .state = seed }; + const qk = sh.length * sh.key_heads * d; + const vy = sh.length * sh.value_heads * d; + const gb = sh.length * sh.value_heads; + const in: Inputs = .{ + .q = try gpa.alloc(f32, qk), + .k = try gpa.alloc(f32, qk), + .v = try gpa.alloc(f32, vy), + .gate = try gpa.alloc(f32, gb), + .beta = try gpa.alloc(f32, gb), + .state = try gpa.alloc(f32, sh.value_heads * d * d), + }; + for ([_][]f32{ in.q, in.k }) |a| { + for (0..a.len / d) |row| { + var ss: f64 = 0; + for (a[row * d ..][0..d]) |*x| { + const z = rng.normal(); + x.* = @floatCast(z); + ss += z * z; + } + const inv: f32 = @floatCast(1 / @sqrt(ss)); + for (a[row * d ..][0..d]) |*x| x.* *= inv; + } + } + for (in.v) |*x| x.* = @floatCast(rng.normal()); + for (in.state) |*x| x.* = @floatCast(0.1 * rng.normal()); + for (in.gate, in.beta, 0..) |*g, *b, i| { + const h = i % sh.value_heads; + const a_log = 0.5 + 7.5 * @as(f64, @floatFromInt(h)) / @as(f64, @floatFromInt(sh.value_heads)); + const x = rng.normal() - 2; + const sp = if (x > 20) x else @log(1 + @exp(x)); + g.* = @floatCast(@exp(-a_log * sp)); + b.* = @floatCast(1 / (1 + @exp(-rng.normal()))); + } + return in; + } + + fn free(in: Inputs) void { + for ([_][]f32{ in.q, in.k, in.v, in.gate, in.beta, in.state }) |a| gpa.free(a); + } +}; + +/// The recurrence in float64: y (L, Hv, d) and the final state. +fn reference(sh: Shape, in: Inputs, y: []f64, state: []f64) !void { + const s = try gpa.alloc(f64, d * d); + defer gpa.free(s); + const group = sh.value_heads / sh.key_heads; + for (0..sh.value_heads) |h| { + for (s, in.state[h * d * d ..][0 .. d * d]) |*a, b| a.* = b; + const kh = h / group; + for (0..sh.length) |t| { + const gb = t * sh.value_heads + h; + const decay: f64 = in.gate[gb]; + const beta: f64 = in.beta[gb]; + const k = in.k[(t * sh.key_heads + kh) * d ..][0..d]; + const q = in.q[(t * sh.key_heads + kh) * d ..][0..d]; + const v = in.v[gb * d ..][0..d]; + for (0..d) |r| { + const row = s[r * d ..][0..d]; + var kv: f64 = 0; + for (row, k) |*a, kk| { + a.* *= decay; + kv += a.* * kk; + } + const delta = (v[r] - kv) * beta; + var out: f64 = 0; + for (row, k, q) |*a, kk, qq| { + a.* += kk * delta; + out += a.* * qq; + } + y[gb * d + r] = out; + } + } + @memcpy(state[h * d * d ..][0 .. d * d], s); + } +} + +/// The largest error over the reference's largest value. +fn relative(got: []const f32, want: []const f64) f64 { + var scale: f64 = 0; + var max: f64 = 0; + for (got, want) |g, w| { + max = @max(max, @abs(@as(f64, g) - w)); + scale = @max(scale, @abs(w)); + } + return max / scale; +} + +/// One call of `length` rows from row `from`, state in place; q, k, v, gate and beta are offset to that row. +fn run(t: *Rig, sh: Shape, q: DeviceBuffer, k: DeviceBuffer, v: DeviceBuffer, gate: DeviceBuffer, beta: DeviceBuffer, state: DeviceBuffer, y: DeviceBuffer, from: usize, length: usize) !void { + const qk = from * sh.key_heads * d * 4; + const vy = from * sh.value_heads * d * 4; + const gb = from * sh.value_heads * 4; + try t.ops(&t.on).gatedDelta(rig.at(q) + qk, rig.at(k) + qk, rig.at(v) + vy, rig.at(gate) + gb, rig.at(beta) + gb, rig.at(state), rig.at(y) + vy, length, sh.key_heads, sh.value_heads, d, d, null); +} + +test "the DeltaNet stays within 5e-3 of the float64 recurrence at four lengths" { + const t = try Rig.open(1 << 30); + defer t.close(); + for ([_]Shape{ + .{ .length = 64, .key_heads = 2, .value_heads = 4 }, + .{ .length = 200, .key_heads = 2, .value_heads = 4 }, + .{ .length = 1000, .key_heads = 2, .value_heads = 4 }, + .{ .length = 4170, .key_heads = 2, .value_heads = 4 }, + }) |sh| { + const in = try Inputs.make(sh, 0x9e3779b97f4a7c15 + sh.length); + defer in.free(); + const ry = try gpa.alloc(f64, sh.length * sh.value_heads * d); + defer gpa.free(ry); + const rs = try gpa.alloc(f64, sh.value_heads * d * d); + defer gpa.free(rs); + try reference(sh, in, ry, rs); + var q = try t.upload(in.q); + defer q.free(); + var k = try t.upload(in.k); + defer k.free(); + var v = try t.upload(in.v); + defer v.free(); + var gate = try t.upload(in.gate); + defer gate.free(); + var beta = try t.upload(in.beta); + defer beta.free(); + var y = try t.alloc(ry.len * 4); + defer y.free(); + var state = try t.upload(in.state); + defer state.free(); + try run(t, sh, q, k, v, gate, beta, state, y, 0, sh.length); + try t.stream.synchronize(); + const gy = try rig.download(f32, y); + defer gpa.free(gy); + const gs = try rig.download(f32, state); + defer gpa.free(gs); + try std.testing.expect(relative(gy, ry) < 5e-3); + try std.testing.expect(relative(gs, rs) < 5e-3); + } +} + +test "a prompt cut on either side of 64 rows gives the same rows and state as one call" { + const t = try Rig.open(1 << 30); + defer t.close(); + const sh: Shape = .{ .length = 200, .key_heads = 2, .value_heads = 4 }; + const in = try Inputs.make(sh, 0x51ed); + defer in.free(); + var q = try t.upload(in.q); + defer q.free(); + var k = try t.upload(in.k); + defer k.free(); + var v = try t.upload(in.v); + defer v.free(); + var gate = try t.upload(in.gate); + defer gate.free(); + var beta = try t.upload(in.beta); + defer beta.free(); + var y = try t.alloc(sh.length * sh.value_heads * d * 4); + defer y.free(); + var state = try t.upload(in.state); + defer state.free(); + try run(t, sh, q, k, v, gate, beta, state, y, 0, sh.length); + try t.stream.synchronize(); + const wy = try rig.download(f32, y); + defer gpa.free(wy); + const ws = try rig.download(f32, state); + defer gpa.free(ws); + for ([_]usize{ 1, 63, 64, 65, 136 }) |c| { + try state.upload(0, std.mem.sliceAsBytes(in.state)); + try y.fill8(0); + try run(t, sh, q, k, v, gate, beta, state, y, 0, c); + try run(t, sh, q, k, v, gate, beta, state, y, c, sh.length - c); + try t.stream.synchronize(); + const gy = try rig.download(f32, y); + defer gpa.free(gy); + const gs = try rig.download(f32, state); + defer gpa.free(gs); + try std.testing.expectEqualSlices(u32, @ptrCast(wy), @ptrCast(gy)); + try std.testing.expectEqualSlices(u32, @ptrCast(ws), @ptrCast(gs)); + } +} diff --git a/zig/src/hip/kernel_tests/ops.zig b/zig/src/hip/kernel_tests/ops.zig new file mode 100644 index 00000000000..3556bbb1387 --- /dev/null +++ b/zig/src/hip/kernel_tests/ops.zig @@ -0,0 +1,513 @@ +//! Elementwise, rotation, gate, draw and routing kernels against host references, exact or within one rounding. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const ops = @import("../ops/ops.zig"); +const Tensor = ops.Tensor; +const Kind = ops.Kind; + +fn act(t: *const Rig) Kind { + return if (t.bf16) .bf16 else .f16; +} + +/// The activation's round-to-nearest-even of `v`, as torch rounds. +fn round(t: *const Rig, v: f64) u16 { + const f: f32 = @floatCast(v); + if (!t.bf16) return rig.f16Bits(f); + const u: u32 = @bitCast(f); + if (std.math.isNan(f)) return 0x7fc0; + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +fn tensor(b: anytype, kind: Kind) Tensor { + return .{ .ptr = at(b), .kind = kind }; +} + +/// Within `ulps` units in the last place of the activation type, relative to the value's own size. +fn close(t: *const Rig, got: u16, want: f64, ulps: f64) bool { + return closeBy(t, got, want, ulps, 0); +} + +/// `close` with `slack` more: what a rotation may move when powf and the host's pow differ by an ulp. +fn closeBy(t: *const Rig, got: u16, want: f64, ulps: f64, slack: f64) bool { + const step: f64 = if (t.bf16) 1.0 / 128.0 else 1.0 / 1024.0; + return @abs(t.value(got) - want) <= ulps * step * @max(@abs(want), 1e-3) + slack; +} + +test "casts, sums, column copies and cache writes give torch's bits" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0xCA57 }; + const n = 4099; + const hf = try gpa.alloc(f32, n); + defer gpa.free(hf); + for (hf) |*x| x.* = @floatCast(rng.normal() * 3.7); + var f = try t.upload(hf); + defer f.free(); + var a = try t.alloc(n * 2); + defer a.free(); + try o.cast(tensor(f, .f32), tensor(a, act(t)), n); + var back = try t.alloc(n * 4); + defer back.free(); + try o.cast(tensor(a, act(t)), tensor(back, .f32), n); + const hy = try gpa.alloc(u16, n); + defer gpa.free(hy); + for (hy) |*x| x.* = t.bits(rng.unit()); + var y = try t.upload(hy); + defer y.free(); + var sum = try t.alloc(n * 2); + defer sum.free(); + try o.add(tensor(a, act(t)), tensor(y, act(t)), tensor(sum, act(t)), n); + try t.stream.synchronize(); + const ga = try rig.download(u16, a); + defer gpa.free(ga); + const gb = try rig.download(f32, back); + defer gpa.free(gb); + const gs = try rig.download(u16, sum); + defer gpa.free(gs); + for (hf, ga, gb, hy, gs) |x, rounded, widened, other, s| { + try std.testing.expectEqual(round(t, x), rounded); + try std.testing.expectEqual(@as(f32, @floatCast(t.value(rounded))), widened); + try std.testing.expectEqual(round(t, @as(f32, @floatCast(t.value(rounded))) + @as(f32, @floatCast(t.value(other)))), s); + } + + // columns [5, 105) of 7 rows of 300, then rows into a 3-head cache at slot 11, from the host and the device + var cols = try t.alloc(7 * 100 * 2); + defer cols.free(); + try o.copyCols(tensor(y, act(t)), 300, 5, at(cols), 7, 100); + const kv_heads = 3; + const d = 20; + const len = 4; + const total = 32; + var caches: [2]@import("../memory.zig").DeviceBuffer = .{ try t.alloc(kv_heads * total * d * 2), try t.alloc(kv_heads * total * d * 2) }; + defer for (&caches) |*c| c.free(); + for (&caches) |*c| try c.fill8(0); + try o.kvWrite(tensor(y, act(t)), at(caches[0]), len, kv_heads, d, total, 11); + const slot = [_]i32{11}; + var dev_slot = try t.upload(&slot); + defer dev_slot.free(); + try o.kvWriteAt(tensor(y, act(t)), at(caches[1]), len, kv_heads, d, total, at(dev_slot)); + try t.stream.synchronize(); + const gc = try rig.download(u16, cols); + defer gpa.free(gc); + for (0..7) |r| try std.testing.expectEqualSlices(u16, hy[r * 300 + 5 ..][0..100], gc[r * 100 ..][0..100]); + for (caches) |c| { + const gk = try rig.download(u16, c); + defer gpa.free(gk); + for (0..kv_heads) |h| for (0..total) |p| for (0..d) |j| { + const want: u16 = if (p >= 11 and p < 11 + len) hy[((p - 11) * kv_heads + h) * d + j] else 0; + try std.testing.expectEqual(want, gk[(h * total + p) * d + j]); + }; + } +} + +test "argmax and top-k follow torch's order: the larger value, then the lower index" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0xA4C }; + const rows = 5; + const n = 3001; + const hl = try gpa.alloc(u16, rows * n); + defer gpa.free(hl); + for (hl) |*x| x.* = t.bits(rng.unit() * 8.0); + // ties: row 1's top value twice, row 3's at both ends + hl[1 * n + 7] = t.bits(9.0); + hl[1 * n + 2000] = t.bits(9.0); + hl[3 * n + 0] = t.bits(9.5); + hl[3 * n + n - 1] = t.bits(9.5); + var logits = try t.upload(hl); + defer logits.free(); + var arg = try t.alloc(rows * 4); + defer arg.free(); + try o.argmaxRows(tensor(logits, act(t)), rows, n, at(arg)); + const ks = [_]i32{ 1, 8, 0, 40, 3 }; + const stride = 40; + var dev_ks = try t.upload(&ks); + defer dev_ks.free(); + var ids = try t.alloc(rows * stride * 4); + defer ids.free(); + var vals = try t.alloc(rows * stride * 2); + defer vals.free(); + try ids.fill8(0xff); + try o.topkRows(tensor(logits, act(t)), rows, n, at(dev_ks), stride, at(ids), at(vals)); + try t.stream.synchronize(); + const ga = try rig.download(i32, arg); + defer gpa.free(ga); + const gi = try rig.download(i32, ids); + defer gpa.free(gi); + const gv = try rig.download(u16, vals); + defer gpa.free(gv); + const order = try gpa.alloc(usize, n); + defer gpa.free(order); + for (0..rows) |r| { + const row = hl[r * n ..][0..n]; + for (order, 0..) |*x, i| x.* = i; + const Ctx = struct { + t: *const Rig, + row: []const u16, + fn before(c: @This(), a: usize, b: usize) bool { + const va = c.t.value(c.row[a]); + const vb = c.t.value(c.row[b]); + return va > vb or (va == vb and a < b); + } + }; + std.mem.sort(usize, order, Ctx{ .t = t, .row = row }, Ctx.before); + try std.testing.expectEqual(@as(i32, @intCast(order[0])), ga[r]); + // the k chosen by (value desc, id asc), each with its value; the kernel writes them in its own order + const k: usize = @intCast(ks[r]); + const got = gi[r * stride ..][0..k]; + for (got, gv[r * stride ..][0..k]) |id, v| try std.testing.expectEqual(row[@intCast(id)], v); + const chosen = try gpa.alloc(i32, k); + defer gpa.free(chosen); + for (chosen, order[0..k]) |*c, i| c.* = @intCast(i); + const sorted = try gpa.dupe(i32, got); + defer gpa.free(sorted); + std.mem.sort(i32, sorted, {}, std.sort.asc(i32)); + std.mem.sort(i32, chosen, {}, std.sort.asc(i32)); + try std.testing.expectEqualSlices(i32, chosen, sorted); + } + try std.testing.expectEqual(@as(i32, 7), ga[1]); + try std.testing.expectEqual(@as(i32, 0), ga[3]); + // k = 0 leaves the row untouched + try std.testing.expectEqual(@as(i32, -1), gi[2 * stride]); +} + +test "the MoE route sorts pairs by expert, stably, into items of at most a tile" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x2017E }; + for ([_][3]usize{ .{ 257, 512, 16 }, .{ 128, 37, 4 }, .{ 64, 1000, 64 } }) |shape| { + const experts = shape[0]; + const pairs = shape[1]; + const tile = shape[2]; + const picks = try gpa.alloc(i32, pairs); + defer gpa.free(picks); + // a skewed pick so some experts fill several tiles and others none + for (picks) |*p| p.* = @intCast(@min(experts - 1, (rng.next() >> 40) % 16 * (rng.next() >> 50) % experts)); + const counts = try gpa.alloc(usize, experts); + defer gpa.free(counts); + @memset(counts, 0); + for (picks) |p| counts[@intCast(p)] += 1; + var capacity: usize = 0; + for (counts) |c| capacity += (c + tile - 1) / tile; + capacity += 3; + var dev_picks = try t.upload(picks); + defer dev_picks.free(); + var members = try t.alloc(pairs * 4); + defer members.free(); + var items = try t.alloc(capacity * 12); + defer items.free(); + try o.moeRoute(at(dev_picks), pairs, experts, tile, at(members), at(items), capacity); + try t.stream.synchronize(); + const gm = try rig.download(i32, members); + defer gpa.free(gm); + const gi = try rig.download(i32, items); + defer gpa.free(gi); + var place: usize = 0; + var slot: usize = 0; + for (0..experts) |e| { + const start = place; + for (picks, 0..) |p, i| if (p == e) { + try std.testing.expectEqual(@as(i32, @intCast(i)), gm[place]); + place += 1; + }; + var left = counts[e]; + var first = start; + while (left > 0) : (slot += 1) { + const take = @min(left, tile); + try std.testing.expectEqualSlices(i32, &.{ @intCast(e), @intCast(first), @intCast(take) }, gi[slot * 3 ..][0..3]); + first += take; + left -= take; + } + } + // the slots past the plan are empty items + for (slot..capacity) |s| try std.testing.expectEqual(@as(i32, 0), gi[s * 3 + 2]); + } +} + +fn silu(x: f64) f64 { + return x / (1 + @exp(-x)); +} + +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} + +test "silu products, attention gates and the MoE activation sit within one rounding of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x51E }; + const n = 2048; + const hg = try gpa.alloc(u16, n); + defer gpa.free(hg); + const hu = try gpa.alloc(u16, n); + defer gpa.free(hu); + for (hg, hu) |*g, *u| { + g.* = t.bits(rng.unit() * 6); + u.* = t.bits(rng.unit() * 2); + } + var g = try t.upload(hg); + defer g.free(); + var u = try t.upload(hu); + defer u.free(); + var out = try t.alloc(n * 2); + defer out.free(); + try o.siluMul(tensor(g, act(t)), tensor(u, act(t)), tensor(out, act(t)), n); + // the gate: out[r, h * d + j] = att * sigmoid(qg's second half), att as (heads, len, d) + const len = 4; + const heads = 8; + const d = 64; + const hatt = try gpa.alloc(f32, len * heads * d); + defer gpa.free(hatt); + for (hatt) |*x| x.* = rng.unit(); + const hqg = try gpa.alloc(u16, len * heads * 2 * d); + defer gpa.free(hqg); + for (hqg) |*x| x.* = t.bits(rng.unit() * 4); + var att = try t.upload(hatt); + defer att.free(); + var qg = try t.upload(hqg); + defer qg.free(); + var gated = try t.alloc(len * heads * d * 2); + defer gated.free(); + try o.attnGate(at(att), tensor(qg, act(t)), tensor(gated, act(t)), len, heads, d, false); + // the MoE activation: silu(min(g, limit)) * clamp(u, -limit, limit), both halves fp32 + const pairs = 6; + const width = 96; + const hboth = try gpa.alloc(f32, pairs * 2 * width); + defer gpa.free(hboth); + for (hboth) |*x| x.* = rng.unit() * 10; + var both = try t.upload(hboth); + defer both.free(); + var moe = try t.alloc(pairs * width * 2); + defer moe.free(); + const limit: f32 = 7; + try o.moeAct(at(both), tensor(moe, act(t)), pairs, width, limit); + try t.stream.synchronize(); + const go = try rig.download(u16, out); + defer gpa.free(go); + for (hg, hu, go) |gv, uv, got| { + const s = t.value(round(t, silu(t.value(gv)))); + try std.testing.expect(close(t, got, s * t.value(uv), 1)); + } + const gg = try rig.download(u16, gated); + defer gpa.free(gg); + for (0..len) |r| for (0..heads) |h| for (0..d) |j| { + const want = @as(f64, hatt[(h * len + r) * d + j]) * sigmoid(t.value(hqg[(r * heads + h) * 2 * d + d + j])); + try std.testing.expect(close(t, gg[(r * heads + h) * d + j], want, 1)); + }; + const gm = try rig.download(u16, moe); + defer gpa.free(gm); + for (0..pairs) |p| for (0..width) |c| { + const gv = @min(@as(f64, hboth[p * 2 * width + c]), limit); + const uv = std.math.clamp(@as(f64, hboth[p * 2 * width + width + c]), -limit, limit); + try std.testing.expect(close(t, gm[p * width + c], silu(gv) * uv, 1)); + }; +} + +/// How far a rotated value may move when powf is one ulp from the host's pow: the angle moves by pos * 2^-23. +fn angleSlack(pos: usize, x1: f64, x2: f64) f64 { + return @as(f64, @floatFromInt(pos)) * 0x1p-23 * (@abs(x1) + @abs(x2)); +} + +/// torch's rotation of one pair at position `pos`, in f32 as the kernel and torch compute the angle. +fn rotation(i: usize, half: usize, pos: usize, theta: f32) [2]f64 { + const freq: f32 = 1.0 / std.math.pow(f32, theta, @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(half))); + const ang: f32 = @as(f32, @floatFromInt(pos)) * freq; + return .{ @cos(@as(f64, ang)), @sin(@as(f64, ang)) }; +} + +test "RoPE for a prompt, a decode row and the fused q / k norm rotate within one rounding of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x20BE }; + const theta: f32 = 10_000_000; + const len = 5; + const heads = 4; + const d = 256; + const rotary = 64; + const half = rotary / 2; + const pos0 = 1000; + const hx = try gpa.alloc(u16, len * heads * d); + defer gpa.free(hx); + for (hx) |*x| x.* = t.bits(rng.unit() * 2); + var x = try t.upload(hx); + defer x.free(); + // the prompt's rotation, written (heads, len, d) + var out = try t.alloc(len * heads * d * 2); + defer out.free(); + try o.ropePrefill(tensor(x, act(t)), tensor(out, act(t)), len * d, d, len, heads, d, rotary, pos0, theta); + // a decode row: fp32 in and out, its position from the device + const hf = try gpa.alloc(f32, 3 * d); + defer gpa.free(hf); + for (hf) |*v| v.* = rng.unit(); + var f = try t.upload(hf); + defer f.free(); + var fy = try t.alloc(3 * d * 4); + defer fy.free(); + const positions = [_]i32{ 7, 70000, 123 }; + var dev_pos = try t.upload(&positions); + defer dev_pos.free(); + try o.ropeDecode(at(f), at(fy), 3, d, rotary, 0, theta, at(dev_pos), 1); + // the fused path: rms norm with a weight, then the rotation at each row's device position, into a cache + const hw = try gpa.alloc(f32, d); + defer gpa.free(hw); + for (hw) |*v| v.* = 1 + rng.unit() / 4; + var w = try t.upload(hw); + defer w.free(); + const total = 80000; + const qk_rows = 3; + var cache = try t.alloc(heads * total * d * 2); + defer cache.free(); + try o.qkRope(tensor(x, act(t)), heads * d, d, at(w), 1e-6, qk_rows, heads, d, rotary, theta, at(dev_pos), null, at(cache), total); + try t.stream.synchronize(); + const go = try rig.download(u16, out); + defer gpa.free(go); + for (0..len) |r| for (0..heads) |h| for (0..d) |j| { + const base = (r * heads + h) * d; + var want: f64 = t.value(hx[base + j]); + var slack: f64 = 0; + if (j < rotary) { + const i = if (j < half) j else j - half; + const cs = rotation(i, half, pos0 + r, theta); + const x1 = t.value(hx[base + i]); + const x2 = t.value(hx[base + i + half]); + want = if (j < half) x1 * cs[0] - x2 * cs[1] else x1 * cs[1] + x2 * cs[0]; + slack = angleSlack(pos0 + r, x1, x2); + } + try std.testing.expect(closeBy(t, go[(h * len + r) * d + j], want, 2, slack)); + }; + const gf = try rig.download(f32, fy); + defer gpa.free(gf); + for (0..3) |r| for (0..d) |j| { + const row = hf[r * d ..][0..d]; + var want: f64 = row[j]; + if (j < rotary) { + const i = if (j < half) j else j - half; + const cs = rotation(i, half, @intCast(positions[r]), theta); + want = if (j < half) row[i] * cs[0] - row[i + half] * cs[1] else row[i] * cs[1] + row[i + half] * cs[0]; + } + const i = if (j < half) j else if (j < rotary) j - half else j; + const slack = if (j < rotary) angleSlack(@intCast(positions[r]), row[i], row[@min(i + half, d - 1)]) else 0; + try std.testing.expect(@abs(gf[r * d + j] - want) < 1e-6 + slack); + }; + const gc = try gpa.alloc(u16, d); + defer gpa.free(gc); + for (0..qk_rows) |r| for (0..heads) |h| { + const p: usize = @intCast(positions[r]); + try cache.download(((h * total + p) * d) * 2, std.mem.sliceAsBytes(gc)); + const src = hx[(r * heads + h) * d ..][0..d]; + var ss: f64 = 0; + for (src) |v| ss += t.value(v) * t.value(v); + const inv = 1 / @sqrt(ss / d + 1e-6); + for (0..d) |j| { + const normed = struct { + fn of(tt: *const Rig, s: []const u16, weight: []const f32, k: usize, scale: f64) f64 { + return tt.value(round(tt, tt.value(s[k]) * scale * weight[k])); + } + }.of; + var want = normed(t, src, hw, j, inv); + var slack: f64 = 0; + if (j < rotary) { + const i = if (j < half) j else j - half; + const cs = rotation(i, half, p, theta); + const x1 = normed(t, src, hw, i, inv); + const x2 = normed(t, src, hw, i + half, inv); + want = if (j < half) x1 * cs[0] - x2 * cs[1] else x1 * cs[1] + x2 * cs[0]; + slack = angleSlack(p, x1, x2); + } + try std.testing.expect(closeBy(t, gc[j], want, 3, slack)); + } + }; +} + +test "the linear attention's prompt conv and DeltaNet gates sit within 1e-5 of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0xC0417 }; + const len = 37; + const channels = 300; + const kernel = 4; + const kept = kernel - 1; + const hx = try gpa.alloc(u16, len * channels); + defer gpa.free(hx); + for (hx) |*x| x.* = t.bits(rng.unit() * 2); + const hw = try gpa.alloc(f32, channels * kernel); + defer gpa.free(hw); + for (hw) |*x| x.* = rng.unit() / 2; + const hs = try gpa.alloc(f32, kept * channels); + defer gpa.free(hs); + for (hs) |*x| x.* = rng.unit(); + var x = try t.upload(hx); + defer x.free(); + var w = try t.upload(hw); + defer w.free(); + var state = try t.upload(hs); + defer state.free(); + var out = try t.alloc(len * channels * 4); + defer out.free(); + var next = try t.alloc(kept * channels * 4); + defer next.free(); + try o.convPrefill(tensor(x, act(t)), at(w), at(state), at(out), at(next), len, channels, kernel); + const count = 9; + const heads = 32; + const ha = try gpa.alloc(u16, count * heads); + defer gpa.free(ha); + const hb = try gpa.alloc(u16, count * heads); + defer gpa.free(hb); + for (ha, hb) |*a, *b| { + a.* = t.bits(rng.unit() * 6); + b.* = t.bits(rng.unit() * 4); + } + const hlog = try gpa.alloc(f32, 2 * heads); + defer gpa.free(hlog); + for (hlog) |*v| v.* = rng.unit(); + var a = try t.upload(ha); + defer a.free(); + var b = try t.upload(hb); + defer b.free(); + var logs = try t.upload(hlog); + defer logs.free(); + var gate = try t.alloc(count * heads * 4); + defer gate.free(); + var beta = try t.alloc(count * heads * 4); + defer beta.free(); + try o.gdnGatePrefill(tensor(a, act(t)), tensor(b, act(t)), at(logs), at(logs) + heads * 4, at(gate), at(beta), count, heads); + try t.stream.synchronize(); + const go = try rig.download(f32, out); + defer gpa.free(go); + const gn = try rig.download(f32, next); + defer gpa.free(gn); + for (0..channels) |c| { + const window = struct { + fn at_(tt: *const Rig, xs: []const u16, ss: []const f32, ch: usize, n_ch: usize, k: usize, kp: usize) f64 { + return if (k < kp) ss[k * n_ch + ch] else tt.value(xs[(k - kp) * n_ch + ch]); + } + }.at_; + for (0..len) |r| { + var acc: f64 = 0; + for (0..kernel) |tap| acc += window(t, hx, hs, c, channels, r + tap, kept) * hw[c * kernel + tap]; + try std.testing.expect(@abs(go[r * channels + c] - silu(acc)) < 1e-5); + } + for (0..kept) |k| try std.testing.expectEqual(@as(f32, @floatCast(window(t, hx, hs, c, channels, len + k, kept))), gn[k * channels + c]); + } + const gg = try rig.download(f32, gate); + defer gpa.free(gg); + const gb = try rig.download(f32, beta); + defer gpa.free(gb); + for (0..count * heads) |i| { + const h = i % heads; + const xv = t.value(ha[i]) + hlog[heads + h]; + const sp = if (xv > 20) xv else @log(1 + @exp(xv)); + const want_gate = @exp(-@exp(@as(f64, hlog[h])) * sp); + try std.testing.expect(@abs(gg[i] - want_gate) <= 1e-5 * @max(want_gate, 1e-3)); + try std.testing.expect(@abs(gb[i] - sigmoid(t.value(hb[i]))) < 1e-6); + } +} diff --git a/zig/src/hip/kernel_tests/rig.zig b/zig/src/hip/kernel_tests/rig.zig new file mode 100644 index 00000000000..e011a1ba5f2 --- /dev/null +++ b/zig/src/hip/kernel_tests/rig.zig @@ -0,0 +1,137 @@ +//! What the kernel tests share: the device, a launcher with every choice on and one with each off, and helpers. +const std = @import("std"); +const Runtime = @import("../runtime.zig").Runtime; +const Context = @import("../context.zig").Context; +const Stream = @import("../stream.zig").Stream; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; +const Arena = @import("../arena.zig").Arena; +const Launcher = @import("../launches.zig").Launcher; +const Ops = @import("../ops/ops.zig").Ops; +const kernels = @import("../kernels.zig"); +const caps = @import("../caps.zig"); + +pub const gpa = std.testing.allocator; + +pub const Rng = struct { + state: u64, + + pub fn next(r: *Rng) u64 { + r.state ^= r.state >> 12; + r.state ^= r.state << 25; + r.state ^= r.state >> 27; + return r.state *% 0x2545F4914F6CDD1D; + } + + /// Uniform on [-1, 1) in 1/1024 steps. + pub fn unit(r: *Rng) f32 { + const v: i32 = @intCast(r.next() >> 40 & 0x7ff); + return @as(f32, @floatFromInt(v - 1024)) / 1024.0; + } + + pub fn uniform(r: *Rng) f64 { + return (@as(f64, @floatFromInt(r.next() >> 11)) + 0.5) / 9007199254740992.0; + } + + pub fn normal(r: *Rng) f64 { + const a = r.uniform(); + const b = r.uniform(); + return @sqrt(-2 * @log(a)) * @cos(2 * std.math.pi * b); + } +}; + +pub const Rig = struct { + r: Runtime, + ctx: Context, + stream: Stream, + /// Every kernel choice on, as a run takes them. + on: Launcher, + /// Merged decode launches off: the kernels they replace. + off: Launcher, + arena: Arena, + /// The activation type: bf16 where the GPU has a bf16 dot2, fp16 on RDNA2. + bf16: bool, + + pub fn open(arena_bytes: usize) !*Rig { + const t = try gpa.create(Rig); + errdefer gpa.destroy(t); + t.r = try Runtime.open(); + errdefer t.r.close(); + t.ctx = try Context.init(&t.r, 0); + errdefer t.ctx.deinit(); + t.stream = try Stream.init(&t.r); + errdefer t.stream.deinit(); + t.on = try Launcher.load(&t.r, .{}, kernels.images); + errdefer t.on.unload(); + t.off = try Launcher.load(&t.r, .{ .fuse = false }, kernels.images); + errdefer t.off.unload(); + t.arena = try Arena.init(&t.r, arena_bytes); + t.bf16 = caps.Caps.of(kernels.arch).?.act == .bf16; + return t; + } + + pub fn close(t: *Rig) void { + t.arena.deinit(); + t.off.unload(); + t.on.unload(); + t.stream.deinit(); + t.ctx.deinit(); + t.r.close(); + gpa.destroy(t); + } + + pub fn ops(t: *Rig, l: *const Launcher) Ops { + return .{ .l = l, .bf16 = t.bf16, .stream = t.stream.handle, .arena = &t.arena }; + } + + pub fn upload(t: *Rig, host: anytype) !DeviceBuffer { + return DeviceBuffer.fromHost(&t.r, std.mem.sliceAsBytes(host)); + } + + pub fn alloc(t: *Rig, bytes: usize) !DeviceBuffer { + return DeviceBuffer.alloc(&t.r, bytes); + } + + /// The activation's 16-bit pattern of `v` and its value. + pub fn bits(t: *const Rig, v: f32) u16 { + return if (t.bf16) bf16Bits(v) else f16Bits(v); + } + + pub fn value(t: *const Rig, b: u16) f64 { + return if (t.bf16) bf16Value(b) else f16Value(b); + } + + /// The activation kind as the kernels number it: 1 fp16, 2 bf16. + pub fn kind(t: *const Rig) c_int { + return if (t.bf16) 2 else 1; + } +}; + +pub fn at(b: DeviceBuffer) u64 { + return @intFromPtr(b.ptr); +} + +pub fn download(comptime T: type, b: DeviceBuffer) ![]T { + const out = try gpa.alloc(T, b.len / @sizeOf(T)); + errdefer gpa.free(out); + try b.download(0, std.mem.sliceAsBytes(out)); + return out; +} + +pub fn f16Bits(v: f32) u16 { + const h: f16 = @floatCast(v); + return @bitCast(h); +} + +pub fn f16Value(b: u16) f64 { + const h: f16 = @bitCast(b); + return h; +} + +/// bf16 by truncation: test inputs are chosen exact in bf16. +pub fn bf16Bits(v: f32) u16 { + return @intCast(@as(u32, @bitCast(v)) >> 16); +} + +pub fn bf16Value(b: u16) f64 { + return @as(f32, @bitCast(@as(u32, b) << 16)); +} diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig new file mode 100644 index 00000000000..3323ec9e3b8 --- /dev/null +++ b/zig/src/hip/kernels.zig @@ -0,0 +1,12 @@ +//! The model-free kernels' code objects, built by hipcc for -Dhip-arch and embedded, one a source group. +const objects = @import("hip_kernels"); + +/// The source groups of zig/kernels/hip, in the order the build embeds them. +pub const Group = enum { ops, act, attention, gated_delta, prefill, decode, plan }; +pub const group_count = @typeInfo(Group).@"enum".field_names.len; + +/// The architecture the objects were built for; the loader takes them only on that device. +pub const arch: []const u8 = objects.arch; + +/// The objects in `Group` order; empty in a build without hipcc. +pub const images: [group_count][]align(8) const u8 = objects.images; diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig new file mode 100644 index 00000000000..1df41fc0093 --- /dev/null +++ b/zig/src/hip/launches.zig @@ -0,0 +1,305 @@ +//! The model-free kernels launched from Zig on the embedded code objects, one module a source group. + +const std = @import("std"); +const runtime = @import("runtime.zig"); +const kernels = @import("kernels.zig"); +const launch = @import("launch.zig"); +const Module = @import("module.zig").Module; +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; + +const util = @import("launches/util.zig"); + +pub const Error = util.Error; + +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const I = util.I; +const CI = util.CI; +const Dim3 = util.Dim3; +const Args = util.Args; +const Triple = util.Triple; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; + +const norms = @import("launches/norms.zig"); +const conv = @import("launches/conv.zig"); +const rope = @import("launches/rope.zig"); +const moe = @import("launches/moe.zig"); +const attention = @import("launches/attention.zig"); +const recurrence = @import("launches/recurrence.zig"); +const plan = @import("launches/plan.zig"); +const elementwise = @import("launches/elementwise.zig"); +const draw = @import("launches/draw.zig"); + +pub const ConvArgs = conv.ConvArgs; +pub const PlanArgs = plan.PlanArgs; +pub const PlanRef = plan.PlanRef; +pub const PlanKeep = plan.Keep; +pub const gdn_chunk = recurrence.gdn_chunk; + +pub const Launcher = struct { + r: *const runtime.Runtime, + mods: [kernels.group_count]Module, + rms: Triple, + conv_decode: Function, + conv_rows: Function, + rope_decode: Function, + moe_router: [2]Function, // fp16, bf16 + moe_select: Function, + moe_act: [2]Function, + moe_combine: Triple, + gdn_gate: Triple, + gated_delta_tile: [2]Function, // dk 128, 16 + gated_delta_wave: [2]Function, + score_keys: Triple, // by cache kind + apply_values: Triple, + causal: Triple, + fa_prefill: Triple, + fa_wide: [2]Function, // the 64-row prefill tile, fp16 and bf16 caches + fa_paged: [2]Function, // the same tile over a stream's pages + softmax_stats: Function, + sum_partials: Function, + op: Ops, + /// decode.hip's kernels: a round's few rows, and the launches that merge several small ones. + dec: Decode, + /// plan.hip's kernels and the DeltaNet's over a round's plan. + plan: PlanFns, + /// decode.hip's merged launches are on (off keeps the launches they replace). + fuse: bool, + /// The 64-row prefill attention tile is on. + wide: bool, + + const PlanFns = struct { + kv_write: Function, + score: [2]Function, // fp16, bf16 + apply: [2]Function, + keep: Function, + gather: Function, + gdn: [2]Function, // dk 128, 16 + gdn_replay: [2]Function, // dk 128, 16 + page_write: Function, + page_gather: Function, + }; + + const Decode = struct { + router: [2]Function, // fp16, bf16 + tail: Function, + conv_split: Function, + rms2: Function, + gnorm_out: Function, + select: Function, + }; + + const Ops = struct { + embed_rows: Function, + embed_dense: Function, + cast: Function, + silu_mul: Function, + add: Function, + attn_gate: Function, + gnorm_silu: Function, + copy_cols: Function, + rope_prefill: Function, + kv_write: Function, + kv_write_at: Function, + argmax: Function, + topk: Function, + conv_prefill: Function, + gdn_gate_prefill: Function, + dense_rows: Function, + moe_route: Function, + router_rows: [2]Function, // fp16, bf16 + router_tile: [2]Function, + router_small: [2]Function, + rms_rows: Function, + qk_rope: Function, + }; + + /// Which kernels a run takes where two give the same bits; every one defaults on. + pub const Choices = struct { fuse: bool = true, wide: bool = true }; + + /// Loads the code objects on the current device and resolves every kernel the launchers use. + pub fn load(r: *const runtime.Runtime, choices: Choices, images: [kernels.group_count][]align(8) const u8) Error!Launcher { + var l: Launcher = undefined; + l.r = r; + var loaded: usize = 0; + errdefer for (l.mods[0..loaded]) |*m| m.unload(); + for (images, 0..) |img, i| { + l.mods[i] = try Module.load(r, img); + loaded += 1; + } + const ops = l.mods[@backingInt(kernels.Group.ops)]; + const act = l.mods[@backingInt(kernels.Group.act)]; + const att = l.mods[@backingInt(kernels.Group.attention)]; + const gd = l.mods[@backingInt(kernels.Group.gated_delta)]; + const pre = l.mods[@backingInt(kernels.Group.prefill)]; + const dec = l.mods[@backingInt(kernels.Group.decode)]; + const pl = l.mods[@backingInt(kernels.Group.plan)]; + l.fuse = choices.fuse; + l.wide = choices.wide; + l.dec = .{ .router = .{ try dec.function("tf_router_decode_f16"), try dec.function("tf_router_decode_bf16") }, .tail = try dec.function("tf_tail"), .conv_split = try dec.function("tf_conv_split"), .rms2 = try dec.function("tf_rms2"), .gnorm_out = try dec.function("tf_gnorm_out"), .select = try dec.function("tf_select_decode") }; + l.plan = .{ + .kv_write = try pl.function("tf_plan_kv_write"), + .score = .{ try pl.function("tf_plan_score_f16"), try pl.function("tf_plan_score_bf16") }, + .apply = .{ try pl.function("tf_plan_apply_f16"), try pl.function("tf_plan_apply_bf16") }, + .keep = try pl.function("tf_plan_keep"), + .gather = try pl.function("tf_plan_gather"), + .gdn = .{ try gd.function("tf_gdn_plan_128"), try gd.function("tf_gdn_plan_16") }, + .gdn_replay = .{ try gd.function("tf_gdn_replay_128"), try gd.function("tf_gdn_replay_16") }, + .page_write = try pl.function("tf_page_write"), + .page_gather = try pl.function("tf_page_gather"), + }; + l.fa_wide = .{ try pre.function("tf_fa_wide_f16"), try pre.function("tf_fa_wide_bf16") }; + l.fa_paged = .{ try pre.function("tf_fa_paged_f16"), try pre.function("tf_fa_paged_bf16") }; + l.op = .{ + .embed_rows = try ops.function("tf_embed_rows"), + .embed_dense = try ops.function("tf_embed_dense"), + .cast = try ops.function("tf_cast"), + .silu_mul = try ops.function("tf_silu_mul"), + .add = try ops.function("tf_add"), + .attn_gate = try ops.function("tf_attn_gate"), + .gnorm_silu = try ops.function("tf_gnorm_silu"), + .copy_cols = try ops.function("tf_copy_cols"), + .rope_prefill = try ops.function("tf_rope_prefill"), + .kv_write = try ops.function("tf_kv_write"), + .kv_write_at = try ops.function("tf_kv_write_at"), + .argmax = try ops.function("tf_argmax"), + .topk = try ops.function("tf_topk"), + .conv_prefill = try ops.function("tf_conv_prefill"), + .gdn_gate_prefill = try ops.function("tf_gdn_gate_prefill"), + .dense_rows = try ops.function("tf_dense_rows"), + .moe_route = try ops.function("tf_moe_route"), + .router_rows = .{ try ops.function("tf_router_rows_f16"), try ops.function("tf_router_rows_bf16") }, + .router_tile = .{ try ops.function("tf_router_tile_f16"), try ops.function("tf_router_tile_bf16") }, + .router_small = .{ try ops.function("tf_router_small_f16"), try ops.function("tf_router_small_bf16") }, + .rms_rows = try ops.function("tf_rms_rows"), + .qk_rope = try ops.function("tf_qk_rope"), + }; + const ns = "_ZN2tf4rocm"; + l.rms = .{ + try act.function(ns ++ "10rms_kernelIfEEvPKT_PKfPS2_if"), + try act.function(ns ++ "10rms_kernelI6__halfEEvPKT_PKfPS3_if"), + try act.function(ns ++ "10rms_kernelI12hip_bfloat16EEvPKT_PKfPS3_if"), + }; + l.conv_decode = try act.function("tf_conv_decode"); + l.conv_rows = try act.function("tf_conv_rows"); + l.rope_decode = try act.function("tf_rope_decode"); + l.moe_router = .{ + try act.function(ns ++ "17moe_router_kernelI6__halfEEvPKT_PKfPfii"), + try act.function(ns ++ "17moe_router_kernelI12hip_bfloat16EEvPKT_PKfPfii"), + }; + l.moe_select = try act.function("tf_moe_select"); + l.moe_act = .{ + try act.function(ns ++ "14moe_act_kernelI6__halfEEvPKfPT_ifx"), + try act.function(ns ++ "14moe_act_kernelI12hip_bfloat16EEvPKfPT_ifx"), + }; + l.moe_combine = .{ + try act.function(ns ++ "18moe_combine_kernelIfEEvPKfS3_PT_ii"), + try act.function(ns ++ "18moe_combine_kernelI6__halfEEvPKfS4_PT_ii"), + try act.function(ns ++ "18moe_combine_kernelI12hip_bfloat16EEvPKfS4_PT_ii"), + }; + l.gdn_gate = .{ + try act.function(ns ++ "15gdn_gate_kernelIfEEvPKT_S4_PKfS6_PfS7_ii"), + try act.function(ns ++ "15gdn_gate_kernelI6__halfEEvPKT_S5_PKfS7_PfS8_ii"), + try act.function(ns ++ "15gdn_gate_kernelI12hip_bfloat16EEvPKT_S5_PKfS7_PfS8_ii"), + }; + l.gated_delta_tile = .{ + try gd.function(ns ++ "16gated_delta_tileILi128ELi8ELi16EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + try gd.function(ns ++ "16gated_delta_tileILi16ELi8ELi16EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + }; + l.gated_delta_wave = .{ + try gd.function(ns ++ "18gated_delta_kernelILi128EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + try gd.function(ns ++ "18gated_delta_kernelILi16EEEvPKfS3_S3_S3_S3_PfS4_iiiiS4_"), + }; + l.score_keys = .{ + try att.function("_Z10score_keysI6__halfEvPKfPKT_PfiiiifixxxPKi"), + try att.function("_Z10score_keysI12hip_bfloat16EvPKfPKT_PfiiiifixxxPKi"), + try att.function("_Z10score_keysIfEvPKfPKT_PfiiiifixxxPKi"), + }; + l.apply_values = .{ + try att.function("_Z12apply_valuesI6__halfEvPKfS2_PKT_PfiiiiixxxPKi"), + try att.function("_Z12apply_valuesI12hip_bfloat16EvPKfS2_PKT_PfiiiiixxxPKi"), + try att.function("_Z12apply_valuesIfEvPKfS1_PKT_PfiiiiixxxPKi"), + }; + l.causal = .{ + try att.function(ns ++ "13causal_kernelI6__halfEEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "13causal_kernelI12hip_bfloat16EEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "13causal_kernelIfEEvPKfPKT_S6_Pfiiiiifixxxxxx"), + }; + l.fa_prefill = .{ + try att.function(ns ++ "10fa_prefillI6__halfLi64EEEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "10fa_prefillI12hip_bfloat16Li64EEEvPKfPKT_S7_Pfiiiiifixxxxxx"), + try att.function(ns ++ "10fa_prefillIfLi32EEEvPKfPKT_S6_Pfiiiiifixxxxxx"), + }; + l.softmax_stats = try att.function("tf_softmax_stats"); + l.sum_partials = try att.function("tf_sum_partials"); + return l; + } + + pub fn unload(l: *Launcher) void { + for (&l.mods) |*m| m.unload(); + } + + pub const tf_rms = norms.tf_rms; + pub const tf_rms2 = norms.tf_rms2; + pub const tf_gnorm_out = norms.tf_gnorm_out; + pub const tf_tail = norms.tf_tail; + pub const tf_conv_decode = conv.tf_conv_decode; + pub const tf_conv_rows = conv.tf_conv_rows; + pub const tf_conv_split = conv.tf_conv_split; + pub const tf_conv_prefill = conv.tf_conv_prefill; + pub const tf_qk_rope = rope.tf_qk_rope; + pub const tf_rope_decode = rope.tf_rope_decode; + pub const tf_rope_prefill = rope.tf_rope_prefill; + pub const routerTile = moe.routerTile; + pub const routerWith = moe.routerWith; + pub const routerWindow = moe.routerWindow; + pub const tf_moe_router = moe.tf_moe_router; + pub const tf_moe_select = moe.tf_moe_select; + pub const tf_moe_act = moe.tf_moe_act; + pub const tf_moe_combine = moe.tf_moe_combine; + pub const tf_moe_route = moe.tf_moe_route; + pub const tf_causal = attention.tf_causal; + pub const tf_attn_gate = attention.tf_attn_gate; + pub const tf_kv_write = attention.tf_kv_write; + pub const tf_kv_write_at = attention.tf_kv_write_at; + pub const tf_argmax_rows = draw.tf_argmax_rows; + pub const tf_topk_rows = draw.tf_topk_rows; + pub const pagedCausal = attention.pagedCausal; + pub const tf_gdn_gate = recurrence.tf_gdn_gate; + pub const tf_gated_delta = recurrence.tf_gated_delta; + pub const planKvWrite = plan.planKvWrite; + pub const planCausal = plan.planCausal; + pub const planGatedDelta = plan.planGatedDelta; + pub const planKeep = plan.planKeep; + pub const planGdnReplay = plan.planGdnReplay; + pub const pagesWrite = plan.pagesWrite; + pub const pagesGather = plan.pagesGather; + pub const planGather = plan.planGather; + pub const tf_gdn_gate_prefill = recurrence.tf_gdn_gate_prefill; + pub const tf_gnorm_silu = recurrence.tf_gnorm_silu; + pub const tf_embed_rows = elementwise.tf_embed_rows; + pub const tf_embed_dense = elementwise.tf_embed_dense; + pub const tf_cast = elementwise.tf_cast; + pub const tf_silu_mul = elementwise.tf_silu_mul; + pub const tf_add = elementwise.tf_add; + pub const tf_copy_cols = elementwise.tf_copy_cols; + pub const tf_dense_rows = elementwise.tf_dense_rows; + + /// Launches on `s`; the counting stream runs nothing. + pub fn go(l: *const Launcher, f: Function, grid: Dim3, block: Dim3, shared: u32, s: S, args: *Args) Error!void { + if (s == util.counting) return; + try launch.launch(f, .{ .grid = grid, .block = block, .shared = shared }, Stream{ .r = l.r, .handle = s }, args); + } + + /// The 256-thread, one-element-a-thread launch of an ops.hip kernel over `n` elements. + pub fn flat(l: *const Launcher, f: Function, n: i64, s: S, a: *Args) Error!void { + if (n == 0) return; + try l.go(f, dim(cdiv(n, 256), 1, 1), dim(256, 1, 1), 0, s, a); + } +}; diff --git a/zig/src/hip/launches/attention.zig b/zig/src/hip/launches/attention.zig new file mode 100644 index 00000000000..ea31be1c9f4 --- /dev/null +++ b/zig/src/hip/launches/attention.zig @@ -0,0 +1,162 @@ +//! Attention launches: causal prefill and decode, the gate and the cache write. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; + +pub fn tf_causal(l: *const Launcher, q: CF, k: C, v: C, out: F, batch: c_int, qlen: c_int, span: c_int, heads: c_int, kv_heads: c_int, d: c_int, scale: f32, q_pos0: c_int, k_sb: c_longlong, k_sh: c_longlong, k_ss: c_longlong, v_sb: c_longlong, v_sh: c_longlong, v_ss: c_longlong, cache_kind: c_int, scores: F, stats: F, partials: F, s: S, pos: CI) Error!void { + if (d < 1 or d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or batch < 1 or qlen < 1 or span < 1 or q_pos0 < 0) { + return invalid("causal attention"); + } + if (cache_kind < 0 or cache_kind > 2) return invalid("causal attention cache kind"); + const kind: usize = @intCast(cache_kind); + const visible: c_int = @min(q_pos0 + 1, span); + if (scores != null) { + if (qlen != 1 or stats == null or partials == null) return invalid("the decode walk"); + // With a device position the keys in use are read on the device and the grid covers the whole cache. + const tiles: c_int = @intCast(if (pos != null) cdiv(span, 128) else cdiv(visible, 128)); + const head_grid = dim(heads, batch, 1); + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(scores)); + try a.add(span); + try a.add(heads); + try a.add(kv_heads); + try a.add(d); + try a.add(scale); + try a.add(visible); + try a.add(k_sb); + try a.add(k_sh); + try a.add(k_ss); + try a.add(ad(pos)); + // a warp scores a key: four warps a block + try l.go(l.score_keys[kind], dim(cdiv(span, 4), heads, batch), dim(128, 1, 1), 0, s, &a); + var b: Args = .{}; + try b.add(ad(scores)); + try b.add(ad(stats)); + try b.add(span); + try b.add(visible); + try b.add(ad(pos)); + try l.go(l.softmax_stats, head_grid, dim(256, 1, 1), 0, s, &b); + var c: Args = .{}; + try c.add(ad(scores)); + try c.add(ad(stats)); + try c.add(ad(v)); + try c.add(ad(partials)); + try c.add(span); + try c.add(heads); + try c.add(kv_heads); + try c.add(d); + try c.add(visible); + try c.add(v_sb); + try c.add(v_sh); + try c.add(v_ss); + try c.add(ad(pos)); + try l.go(l.apply_values[kind], dim(tiles, heads, batch), dim(256, 1, 1), 0, s, &c); + var e: Args = .{}; + try e.add(ad(partials)); + try e.add(ad(out)); + try e.add(tiles); + try e.add(d); + try l.go(l.sum_partials, head_grid, dim(256, 1, 1), 0, s, &e); + return; + } + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(v)); + try a.add(ad(out)); + try a.add(qlen); + try a.add(span); + try a.add(heads); + try a.add(kv_heads); + try a.add(d); + try a.add(scale); + try a.add(q_pos0); + try a.add(k_sb); + try a.add(k_sh); + try a.add(k_ss); + try a.add(v_sb); + try a.add(v_sh); + try a.add(v_ss); + // a 16-bit cache of whole 64-wide heads takes the 64-row tile (attention=f32: 16-row); odd heads a wave a query + if (kind < 2 and @rem(d, 64) == 0 and d <= 256 and @rem(k_ss, 8) == 0 and @rem(v_ss, 8) == 0 and l.wide) { + try l.go(l.fa_wide[kind], dim(cdiv(qlen, 64), heads, batch), dim(256, 1, 1), 0, s, &a); + } else if (d >= 2 and @rem(d, 2) == 0) { + try l.go(l.fa_prefill[kind], dim(cdiv(qlen, 16), heads, batch), dim(256, 1, 1), 0, s, &a); + } else { + try l.go(l.causal[kind], dim(qlen, heads, batch), dim(32, 1, 1), 0, s, &a); + } +} + +/// The 64-row prefill tile over a stream's pages: q (heads, qlen, d) fp32 against `span` positions, 16-bit cache. +pub fn pagedCausal(l: *const Launcher, q: u64, k: u64, v: u64, table: u64, out: u64, qlen: usize, span: usize, heads: usize, kv_heads: usize, d: usize, scale: f32, q_pos0: usize, count: usize, cache_kind: c_int, s: S) Error!void { + if (d % 64 != 0 or d > 256 or heads % kv_heads != 0 or cache_kind < 0 or cache_kind > 1) return invalid("paged attention"); + var a: Args = .{}; + try a.add(q); + try a.add(k); + try a.add(v); + try a.add(out); + try a.add(@as(c_int, @intCast(qlen))); + try a.add(@as(c_int, @intCast(span))); + try a.add(@as(c_int, @intCast(heads))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(scale); + try a.add(@as(c_int, @intCast(q_pos0))); + try a.add(table); + try a.add(@as(c_int, @intCast(count))); + try l.go(l.fa_paged[@intCast(cache_kind)], dim(cdiv(qlen, 64), heads, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_attn_gate(l: *const Launcher, att: CF, qg: C, out: P, kind: c_int, len: c_int, heads: c_int, d: c_int, rows_major: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(att)); + try a.add(ad(qg)); + try a.add(ad(out)); + try a.add(kind); + try a.add(len); + try a.add(heads); + try a.add(d); + try a.add(rows_major); + try l.flat(l.op.attn_gate, @as(i64, len) * heads * d, s, &a); +} + +pub fn tf_kv_write(l: *const Launcher, src: C, cache: P, kind: c_int, len: c_int, kv_heads: c_int, d: c_int, total: c_int, pos0: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(ad(cache)); + try a.add(kind); + try a.add(len); + try a.add(kv_heads); + try a.add(d); + try a.add(total); + try a.add(pos0); + try l.flat(l.op.kv_write, @as(i64, len) * kv_heads * d, s, &a); +} + +/// kv_write with the first slot read from the device (`pos`, one i32), so a captured graph replays at any position. +pub fn tf_kv_write_at(l: *const Launcher, src: C, cache: P, kind: c_int, len: c_int, kv_heads: c_int, d: c_int, total: c_int, pos: CI, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(ad(cache)); + try a.add(kind); + try a.add(len); + try a.add(kv_heads); + try a.add(d); + try a.add(total); + try a.add(ad(pos)); + try l.flat(l.op.kv_write_at, @as(i64, len) * kv_heads * d, s, &a); +} diff --git a/zig/src/hip/launches/conv.zig b/zig/src/hip/launches/conv.zig new file mode 100644 index 00000000000..59f2cb0af49 --- /dev/null +++ b/zig/src/hip/launches/conv.zig @@ -0,0 +1,97 @@ +//! Causal conv launches: decode, window rows, prefill and the split with its norms and gates. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const C = util.C; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; +const PlanArgs = @import("plan.zig").PlanArgs; + +/// decode.hip's ConvArgs: the linear attention's conv launch. +pub const ConvArgs = extern struct { + x: u64, + kind: c_int, + weight: u64, + state: u64, + states: u64 = 0, + qn: u64, + kn: u64, + v: u64, + channels: c_int, + kernel: c_int, + rows: c_int, + kw: c_int, + vw: c_int, + qw: u64 = 0, + kw_w: u64 = 0, + eps: f32 = 0, + norm: c_int = 0, + ga: u64 = 0, + gb: u64 = 0, + a_log: u64 = 0, + dt_bias: u64 = 0, + gate: u64 = 0, + beta: u64 = 0, + gcount: c_int = 0, + heads: c_int = 0, + /// A round's plan: a grid row a slot, its rows and state from the plan (no plan: this launch's own). + plan: PlanArgs = .{}, + layer: c_int = 0, + slots: c_int = 1, +}; + +pub fn tf_conv_decode(l: *const Launcher, x: CF, weight: CF, state: F, y: F, batch: c_int, channels: c_int, kernel: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(weight)); + try a.add(ad(state)); + try a.add(ad(y)); + try a.add(channels); + try a.add(kernel); + try l.go(l.conv_decode, dim(cdiv(channels, 128), batch, 1), dim(128, 1, 1), 0, s, &a); +} + +pub fn tf_conv_rows(l: *const Launcher, x: CF, weight: CF, state: F, y: F, states: F, rows: c_int, channels: c_int, kernel: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(weight)); + try a.add(ad(state)); + try a.add(ad(y)); + try a.add(ad(states)); + try a.add(channels); + try a.add(kernel); + try a.add(rows); + try l.go(l.conv_rows, dim(cdiv(channels, 128), 1, 1), dim(128, 1, 1), 0, s, &a); +} + +/// A window's rows through the linear attention's conv, split into q, k and v, normed and gated when `c` asks. +pub fn tf_conv_split(l: *const Launcher, c: ConvArgs, s: S) Error!void { + if (c.kernel < 1 or c.kernel > 8 or (c.norm != 0 and (c.norm != 128 or @rem(c.kw, 128) != 0))) return invalid("conv split"); + var a: Args = .{}; + try a.add(c); + const gate_blocks = if (c.ga != 0) cdiv(c.gcount, 128) else 0; + try l.go(l.dec.conv_split, dim(cdiv(c.channels, 128) + gate_blocks, c.slots, 1), dim(128, 1, 1), 0, s, &a); +} + +pub fn tf_conv_prefill(l: *const Launcher, x: C, kind: c_int, weight: CF, state: CF, out: F, new_state: F, len: c_int, channels: c_int, kernel: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(kind); + try a.add(ad(weight)); + try a.add(ad(state)); + try a.add(ad(out)); + try a.add(ad(new_state)); + try a.add(len); + try a.add(channels); + try a.add(kernel); + // a thread a channel over 16 rows (conv_prefill_kernel's kConvRows), at most 8 taps + if (kernel > 8) return invalid("conv_prefill"); + try l.go(l.op.conv_prefill, dim(cdiv(channels, 256), @max(1, cdiv(len, 16)), 1), dim(256, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/draw.zig b/zig/src/hip/launches/draw.zig new file mode 100644 index 00000000000..deba1ab5fe3 --- /dev/null +++ b/zig/src/hip/launches/draw.zig @@ -0,0 +1,37 @@ +//! Argmax and top-k of logits rows: one 1024-thread block a row. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const C = util.C; +const P = util.P; +const I = util.I; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; + +/// out[r] = torch.argmax of row r of (rows, n) logits of `kind` (1 fp16, 2 bf16). +pub fn tf_argmax_rows(l: *const Launcher, logits: C, kind: c_int, rows: c_int, n: c_int, out: I, s: S) Error!void { + if (rows == 0) return; + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(kind); + try a.add(n); + try a.add(ad(out)); + try l.go(l.op.argmax, dim(rows, 1, 1), dim(1024, 1, 1), 0, s, &a); +} + +/// Row r's ks[r] largest by (value desc, id asc) into ids and 16-bit values, `stride` apart; ks[r] = 0 skips the row. +pub fn tf_topk_rows(l: *const Launcher, logits: C, rows: c_int, n: c_int, ks: CI, stride: c_int, ids: I, values: P, s: S) Error!void { + if (rows == 0) return; + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(n); + try a.add(ad(ks)); + try a.add(stride); + try a.add(ad(ids)); + try a.add(ad(values)); + try l.go(l.op.topk, dim(rows, 1, 1), dim(1024, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/elementwise.zig b/zig/src/hip/launches/elementwise.zig new file mode 100644 index 00000000000..4f767f37fdb --- /dev/null +++ b/zig/src/hip/launches/elementwise.zig @@ -0,0 +1,94 @@ +//! Element-wise launches: embedding rows, casts, sums, column copies and the draft projection. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; + +pub fn tf_embed_rows(l: *const Launcher, words: C, scale: C, bias: C, scale_kind: c_int, ids: CI, n: c_int, bits: c_int, group: c_int, k: c_int, out: P, out_kind: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(words)); + try a.add(ad(scale)); + try a.add(ad(bias)); + try a.add(scale_kind); + try a.add(ad(ids)); + try a.add(n); + try a.add(bits); + try a.add(group); + try a.add(k); + try a.add(ad(out)); + try a.add(out_kind); + try l.flat(l.op.embed_rows, @as(i64, n) * k, s, &a); +} + +pub fn tf_embed_dense(l: *const Launcher, table: CF, ids: CI, n: c_int, k: c_int, out: P, out_kind: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(table)); + try a.add(ad(ids)); + try a.add(n); + try a.add(k); + try a.add(ad(out)); + try a.add(out_kind); + try l.flat(l.op.embed_dense, @as(i64, n) * k, s, &a); +} + +pub fn tf_cast(l: *const Launcher, src: C, skind: c_int, dst: P, dkind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(skind); + try a.add(ad(dst)); + try a.add(dkind); + try a.add(n); + try l.flat(l.op.cast, n, s, &a); +} + +pub fn tf_silu_mul(l: *const Launcher, gate: C, up: C, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(gate)); + try a.add(ad(up)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.flat(l.op.silu_mul, n, s, &a); +} + +pub fn tf_add(l: *const Launcher, x: C, y: C, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.flat(l.op.add, n, s, &a); +} + +pub fn tf_copy_cols(l: *const Launcher, src: C, stride: c_longlong, offset: c_int, dst: P, kind: c_int, rows: c_int, cols: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(src)); + try a.add(stride); + try a.add(offset); + try a.add(ad(dst)); + try a.add(kind); + try a.add(rows); + try a.add(cols); + try l.flat(l.op.copy_cols, @as(i64, rows) * cols, s, &a); +} + +pub fn tf_dense_rows(l: *const Launcher, x: C, kind: c_int, w: CF, out: P, rows: c_int, n: c_int, k: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(kind); + try a.add(ad(w)); + try a.add(ad(out)); + try a.add(rows); + try a.add(n); + try a.add(k); + try l.go(l.op.dense_rows, dim(n, rows, 1), dim(32, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/moe.zig b/zig/src/hip/launches/moe.zig new file mode 100644 index 00000000000..c998a43b094 --- /dev/null +++ b/zig/src/hip/launches/moe.zig @@ -0,0 +1,122 @@ +//! MoE launches: router, select, plan, activation and combine. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const I = util.I; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const tri = util.tri; +const invalid = util.invalid; + +/// The most rows the router's wave-an-expert kernel takes in prefill. +pub const router_small_rows = 32; + +/// The router's logits at any row count so prompt rows ignore cuts: 64 x 64 tiles, or a wave an expert, same bits. +pub fn routerTile(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S) Error!void { + return routerWith(l, x, kind, rows, logits, r, d, e, s, r <= router_small_rows); +} + +pub fn routerWith(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S, small: bool) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(rows)); + try a.add(ad(logits)); + try a.add(r); + try a.add(d); + try a.add(e); + const k: usize = if (kind == 1) 0 else 1; + if (small) return l.go(l.op.router_small[k], dim(cdiv(e, 8), cdiv(r, 32), 1), dim(256, 1, 1), 0, s, &a); + try l.go(l.op.router_tile[k], dim(cdiv(e, 64), cdiv(r, 64), 1), dim(256, 1, 1), 0, s, &a); +} + +/// A lane round's router at any row count; false (nothing launched) where the shape keeps the other kernels. +pub fn routerWindow(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S) Error!bool { + if (!l.fuse or r < 1 or @rem(d, 4) != 0 or ad(rows) % 16 != 0 or ad(x) % 8 != 0) return false; + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(rows)); + try a.add(ad(logits)); + try a.add(r); + try a.add(d); + try a.add(e); + try l.go(l.dec.router[if (kind == 1) 0 else 1], dim(cdiv(e, 4), cdiv(r, 16), 1), dim(128, 1, 1), 0, s, &a); + return true; +} + +pub fn tf_moe_router(l: *const Launcher, x: C, kind: c_int, rows: CF, logits: F, r: c_int, d: c_int, e: c_int, s: S) Error!void { + // a prompt's rows take the 64 x 64 tiles, a round's few rows a wave an expert; each logit's sum is the same + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(rows)); + try a.add(ad(logits)); + try a.add(r); + try a.add(d); + try a.add(e); + const k: usize = if (kind == 1) 0 else 1; + if (l.fuse and r <= 16 and @rem(d, 4) == 0 and ad(rows) % 16 == 0 and ad(x) % 8 == 0) { + return l.go(l.dec.router[k], dim(cdiv(e, 4), 1, 1), dim(128, 1, 1), 0, s, &a); + } + if (r >= 64 and @rem(d, 32) == 0) return l.go(l.op.router_tile[k], dim(cdiv(e, 64), cdiv(r, 64), 1), dim(256, 1, 1), 0, s, &a); + try l.go(l.op.router_rows[k], dim(cdiv(e, 8), cdiv(r, 8), 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_moe_select(l: *const Launcher, logits: CF, pick: I, wts: F, items: I, members: I, capacity: c_int, r: c_int, experts: c_int, top_k: c_int, s: S) Error!void { + if (experts > 1024 or top_k < 1 or top_k > 31) return invalid("moe select"); + var a: Args = .{}; + try a.add(ad(logits)); + try a.add(ad(pick)); + try a.add(ad(wts)); + try a.add(ad(items)); + try a.add(ad(members)); + try a.add(capacity); + try a.add(experts); + try a.add(top_k); + if (l.fuse) return l.go(l.dec.select, dim(r, 1, 1), dim(256, 1, 1), 0, s, &a); + try l.go(l.moe_select, dim(r, 1, 1), dim(32, 1, 1), 0, s, &a); +} + +pub fn tf_moe_act(l: *const Launcher, both: CF, out: P, kind: c_int, pairs: c_int, width: c_int, limit: f32, s: S) Error!void { + const total = @as(i64, pairs) * width; + var a: Args = .{}; + try a.add(ad(both)); + try a.add(ad(out)); + try a.add(width); + try a.add(limit); + try a.add(total); + try l.go(l.moe_act[if (kind == 1) 0 else 1], dim(cdiv(total, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_moe_combine(l: *const Launcher, y: CF, wts: CF, out: P, kind: c_int, r: c_int, slots: c_int, d: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(wts)); + try a.add(ad(out)); + try a.add(slots); + try a.add(d); + try l.go(l.moe_combine[tri(kind)], dim(cdiv(d, 256), r, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_moe_route(l: *const Launcher, picks: CI, pairs: c_int, experts: c_int, tile: c_int, members: I, items: I, capacity: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(picks)); + try a.add(pairs); + try a.add(experts); + try a.add(tile); + try a.add(ad(members)); + try a.add(ad(items)); + try a.add(capacity); + // every expert's count, start and end, and each pair segment's 16-bit counts, in dynamic shared memory + const ex: usize = @intCast(experts); + const segs: usize = if (ex <= 256) 64 else 16; + if (ex > 1024) return invalid("moe_route"); + try l.go(l.op.moe_route, dim(1, 1, 1), dim(256, 1, 1), @intCast(3 * ex * 4 + segs * ex * 2), s, &a); +} diff --git a/zig/src/hip/launches/norms.zig b/zig/src/hip/launches/norms.zig new file mode 100644 index 00000000000..ca9a007c56c --- /dev/null +++ b/zig/src/hip/launches/norms.zig @@ -0,0 +1,83 @@ +//! Norm launches and the decode tails that fuse a norm. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const tri = util.tri; +const invalid = util.invalid; + +pub fn tf_rms(l: *const Launcher, x: C, weight: CF, y: P, kind: c_int, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + if (width <= 1024) { + // a wave a row, rms_kernel's sums + try a.add(kind); + try a.add(ad(weight)); + try a.add(ad(y)); + try a.add(rows); + try a.add(width); + try a.add(eps); + return l.go(l.op.rms_rows, dim(cdiv(rows, 8), 1, 1), dim(256, 1, 1), 0, s, &a); + } + try a.add(ad(weight)); + try a.add(ad(y)); + try a.add(width); + try a.add(eps); + try l.go(l.rms[tri(kind)], dim(rows, 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Two sets of fp32 rows of `width` (at most 1024), each with its own weight, normed in one launch. +pub fn tf_rms2(l: *const Launcher, x0: CF, w0: CF, y0: F, x1: CF, w1: CF, y1: F, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + if (width > 1024) return invalid("rms2"); + var a: Args = .{}; + try a.add(ad(x0)); + try a.add(ad(w0)); + try a.add(ad(y0)); + try a.add(ad(x1)); + try a.add(ad(w1)); + try a.add(ad(y1)); + try a.add(rows); + try a.add(width); + try a.add(eps); + try l.go(l.dec.rms2, dim(cdiv(rows, 8), 2, 1), dim(256, 1, 1), 0, s, &a); +} + +/// out = rms(y) * weight * round(silu(z)) rounded to the kind, rows of `width` (at most 1024). +pub fn tf_gnorm_out(l: *const Launcher, y: CF, weight: CF, z: C, out: P, kind: c_int, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + if (width > 1024) return invalid("gnorm out"); + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(weight)); + try a.add(ad(z)); + try a.add(ad(out)); + try a.add(kind); + try a.add(rows); + try a.add(width); + try a.add(eps); + try l.go(l.dec.gnorm_out, dim(cdiv(rows, 8), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// x = round(x + t), t being y or the weighted sum of the row's `slots`; normed = rms(x) * weight, a block a row. +pub fn tf_tail(l: *const Launcher, x: P, y: C, wts: CF, weight: CF, normed: P, kind: c_int, rows: c_int, slots: c_int, width: c_int, eps: f32, s: S) Error!void { + if (width > 8192 or rows < 1) return invalid("tail"); + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(ad(wts)); + try a.add(ad(weight)); + try a.add(ad(normed)); + try a.add(kind); + try a.add(slots); + try a.add(width); + try a.add(eps); + try l.go(l.dec.tail, dim(rows, 1, 1), dim(512, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/plan.zig b/zig/src/hip/launches/plan.zig new file mode 100644 index 00000000000..2a7b0bb3b59 --- /dev/null +++ b/zig/src/hip/launches/plan.zig @@ -0,0 +1,188 @@ +//! A lane round's launches over its device plan: cache writes, the attention walk, the recurrence and the keep. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const Args = util.Args; +const Error = util.Error; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; + +/// plan.hpp's PlanArgs: device addresses of the round's per-row and per-slot arrays (all zero: no plan). +pub const PlanArgs = extern struct { + pos: u64 = 0, + slot: u64 = 0, + first: u64 = 0, + count: u64 = 0, + desc: u64 = 0, + snaps: u64 = 0, + pages: u32 = 0, + pool: u32 = 0, +}; + +/// A plan's shape: `rows` rows (a bucket, padding included) over `slots` slots. +pub const PlanRef = struct { args: PlanArgs, rows: usize, slots: usize }; + +/// Rows of keys (fp32, rotated) and values (fp16 or bf16) into each row's slot at its position. +pub fn planKvWrite(l: *const Launcher, keys: u64, values: u64, kind: c_int, p: PlanRef, layer: usize, kv_heads: usize, d: usize, s: S) Error!void { + var a: Args = .{}; + try a.add(keys); + try a.add(values); + try a.add(kind); + try a.add(@as(c_int, @intCast(p.rows))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(layer))); + try l.flat(l.plan.kv_write, @intCast(p.rows * kv_heads * d), s, &a); +} + +/// One query a row (rows, heads, d) fp32 over its slot's caches up to its position; the walk covers `span` keys. +pub fn planCausal(l: *const Launcher, q: u64, out: u64, scores: u64, stats: u64, partials: u64, p: PlanRef, layer: usize, heads: usize, kv_heads: usize, d: usize, span: usize, scale: f32, kind: c_int, s: S) Error!void { + if (d > 256 or heads < 1 or kv_heads < 1 or @rem(heads, kv_heads) != 0 or kind < 1 or kind > 2) return invalid("planned attention"); + const which: usize = @intCast(kind - 1); + const rows = p.rows; + const tiles: c_int = @intCast(cdiv(span, 128)); + const span_c: c_int = @intCast(span); + const heads_c: c_int = @intCast(heads); + const kv_c: c_int = @intCast(kv_heads); + const d_c: c_int = @intCast(d); + const layer_c: c_int = @intCast(layer); + // a block takes `group` query heads of one KV head (at most plan.hip's kMaxGroup): the cache is read once for them + var group = @divExact(heads, kv_heads); + while (group > 16) group = @divExact(group, smallestFactor(group)); + const blocks = @divExact(heads, group); + var a: Args = .{}; + try a.add(q); + try a.add(scores); + try a.add(span_c); + try a.add(heads_c); + try a.add(kv_c); + try a.add(d_c); + try a.add(scale); + try a.add(p.args); + try a.add(layer_c); + // a warp scores a key for the block's heads: four warps a block, the heads' queries in shared memory + try l.go(l.plan.score[which], dim(cdiv(span, 4), blocks, rows), dim(128, 1, 1), @intCast(group * d * 4), s, &a); + var b: Args = .{}; + try b.add(scores); + try b.add(stats); + try b.add(span_c); + try b.add(@as(c_int, 0)); + try b.add(p.args.pos); + try l.go(l.softmax_stats, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &b); + var c: Args = .{}; + try c.add(scores); + try c.add(stats); + try c.add(partials); + try c.add(span_c); + try c.add(heads_c); + try c.add(kv_c); + try c.add(d_c); + try c.add(p.args); + try c.add(layer_c); + try l.go(l.plan.apply[which], dim(tiles, blocks, rows), dim(256, 1, 1), 0, s, &c); + var e: Args = .{}; + try e.add(partials); + try e.add(out); + try e.add(tiles); + try e.add(d_c); + try l.go(l.sum_partials, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &e); +} + +fn smallestFactor(n: usize) usize { + var f: usize = 2; + while (@rem(n, f) != 0) f += 1; + return f; +} + +/// The DeltaNet recurrence of every slot's rows (q, k, v, gate, beta, y flat over rows), state in the slot's caches. +pub fn planGatedDelta(l: *const Launcher, q: u64, k: u64, v: u64, gate: u64, beta: u64, y: u64, p: PlanRef, layer: usize, key_heads: usize, value_heads: usize, dk: usize, dv: usize, s: S) Error!void { + if ((dk != 16 and dk != 128) or @rem(dv, 8) != 0 or key_heads < 1 or @rem(value_heads, key_heads) != 0) return invalid("planned gated delta"); + var a: Args = .{}; + try a.add(q); + try a.add(k); + try a.add(v); + try a.add(gate); + try a.add(beta); + try a.add(y); + try a.add(@as(c_int, @intCast(key_heads))); + try a.add(@as(c_int, @intCast(value_heads))); + try a.add(@as(c_int, @intCast(dv))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(layer))); + const wide: usize = if (dk == 128) 0 else 1; + try l.go(l.plan.gdn[wide], dim(@divExact(dv, 8), value_heads, p.slots), dim(32, 8, 1), 0, s, &a); +} + +/// Row r of `dst` (`words` words each) from the address in `srcs[r]` (device u64s), for `rows` rows. +pub fn planGather(l: *const Launcher, srcs: u64, dst: u64, words: usize, rows: usize, s: S) Error!void { + if (words % 4 != 0 or rows == 0) return invalid("planned gather"); + var a: Args = .{}; + try a.add(srcs); + try a.add(dst); + try a.add(@as(c_int, @intCast(words))); + try l.go(l.plan.gather, dim(cdiv(words, 256), rows, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Writes positions pos0 .. pos0 + len of a stream's pages from 16-bit `src` at h * s_head + r * s_row + j. +pub fn pagesWrite(l: *const Launcher, src: u64, pool: u64, table: u64, len: usize, kv_heads: usize, d: usize, s_head: usize, s_row: usize, pos0: usize, count: usize, s: S) Error!void { + var a: Args = .{}; + try a.add(src); + try a.add(pool); + try a.add(table); + try a.add(@as(c_int, @intCast(len))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(@as(c_longlong, @intCast(s_head))); + try a.add(@as(c_longlong, @intCast(s_row))); + try a.add(@as(c_int, @intCast(pos0))); + try a.add(@as(c_int, @intCast(count))); + try l.flat(l.plan.page_write, @intCast(len * kv_heads * d), s, &a); +} + +/// The first `len` positions of a stream's pages as (kv_heads, len, d) 16-bit values in `dst`. +pub fn pagesGather(l: *const Launcher, pool: u64, table: u64, dst: u64, len: usize, kv_heads: usize, d: usize, count: usize, s: S) Error!void { + var a: Args = .{}; + try a.add(pool); + try a.add(table); + try a.add(dst); + try a.add(@as(c_int, @intCast(len))); + try a.add(@as(c_int, @intCast(kv_heads))); + try a.add(@as(c_int, @intCast(d))); + try a.add(@as(c_int, @intCast(count))); + try l.flat(l.plan.page_gather, @intCast(len * kv_heads * d), s, &a); +} + +/// What a keep reads: the plan, kept rows a slot (negative: unlisted), final rows, word counts (of four), layers. +pub const Keep = struct { keep: u64, hidden: u64, hidden_words: usize, channels: usize, taps: usize, layers: usize }; + +/// Keeps the listed slots' rows: conv windows from the round's first window and the kept rows' inputs, final rows. +pub fn planKeep(l: *const Launcher, p: PlanRef, k: Keep, s: S) Error!void { + if (k.hidden_words % 4 != 0) return invalid("planned keep"); + var a: Args = .{}; + try a.add(p.args); + try a.add(k.keep); + try a.add(k.hidden); + try a.add(@as(c_int, @intCast(k.hidden_words))); + try a.add(@as(c_int, @intCast(k.channels))); + try a.add(@as(c_int, @intCast(k.taps))); + try a.add(@as(c_int, @intCast(k.layers))); + try l.go(l.plan.keep, dim(64, k.layers + 1, p.slots), dim(256, 1, 1), 0, s, &a); +} + +/// The kept slots' DeltaNet states run through their kept rows, every linear layer in one launch. +pub fn planGdnReplay(l: *const Launcher, keep: u64, p: PlanRef, key_heads: usize, value_heads: usize, dk: usize, dv: usize, layers: usize, s: S) Error!void { + if ((dk != 16 and dk != 128) or @rem(dv, 8) != 0 or key_heads < 1 or @rem(value_heads, key_heads) != 0) return invalid("planned replay"); + var a: Args = .{}; + try a.add(keep); + try a.add(@as(c_int, @intCast(p.rows))); + try a.add(@as(c_int, @intCast(key_heads))); + try a.add(@as(c_int, @intCast(value_heads))); + try a.add(@as(c_int, @intCast(dv))); + try a.add(p.args); + try a.add(@as(c_int, @intCast(p.slots))); + const wide: usize = if (dk == 128) 0 else 1; + try l.go(l.plan.gdn_replay[wide], dim(@divExact(dv, 8), value_heads, p.slots * layers), dim(32, 8, 1), 0, s, &a); +} diff --git a/zig/src/hip/launches/recurrence.zig b/zig/src/hip/launches/recurrence.zig new file mode 100644 index 00000000000..a654d56a2bb --- /dev/null +++ b/zig/src/hip/launches/recurrence.zig @@ -0,0 +1,79 @@ +//! DeltaNet launches: gate, recurrence and the gated norm. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const tri = util.tri; +const invalid = util.invalid; + +pub fn tf_gdn_gate(l: *const Launcher, av: C, bv: C, kind: c_int, a_log: CF, dt_bias: CF, gate: F, beta: F, count: c_int, heads: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(av)); + try a.add(ad(bv)); + try a.add(ad(a_log)); + try a.add(ad(dt_bias)); + try a.add(ad(gate)); + try a.add(ad(beta)); + try a.add(count); + try a.add(heads); + try l.go(l.gdn_gate[tri(kind)], dim(cdiv(count, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_gated_delta(l: *const Launcher, q: CF, k: CF, v: CF, gate: CF, beta: CF, state: F, y: F, batch: c_int, length: c_int, key_heads: c_int, value_heads: c_int, dk: c_int, dv: c_int, s: S, states: F) Error!void { + if ((dk != 16 and dk != 128) or dv < 1 or key_heads < 1 or @rem(value_heads, key_heads) != 0 or batch < 1 or length < 1) { + return invalid("gated delta"); + } + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(v)); + try a.add(ad(gate)); + try a.add(ad(beta)); + try a.add(ad(state)); + try a.add(ad(y)); + try a.add(length); + try a.add(key_heads); + try a.add(value_heads); + try a.add(dv); + try a.add(ad(states)); + const wide: usize = if (dk == 128) 0 else 1; + // Eight rows share one k/q tile; a short dv stays on the one-row wave, which is the same scan. + if (@rem(dv, 8) == 0) { + try l.go(l.gated_delta_tile[wide], dim(@divExact(dv, 8), value_heads, batch), dim(32, 8, 1), 0, s, &a); + } else { + try l.go(l.gated_delta_wave[wide], dim(dv, value_heads, batch), dim(32, 1, 1), 0, s, &a); + } +} + +pub fn tf_gdn_gate_prefill(l: *const Launcher, av: C, bv: C, kind: c_int, a_log: CF, dt_bias: CF, gate: F, beta: F, count: c_int, heads: c_int, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(av)); + try a.add(ad(bv)); + try a.add(kind); + try a.add(ad(a_log)); + try a.add(ad(dt_bias)); + try a.add(ad(gate)); + try a.add(ad(beta)); + try a.add(count); + try a.add(heads); + try l.flat(l.op.gdn_gate_prefill, @as(i64, count) * heads, s, &a); +} + +pub fn tf_gnorm_silu(l: *const Launcher, y: CF, z: C, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(z)); + try a.add(ad(out)); + try a.add(kind); + try a.add(n); + try l.flat(l.op.gnorm_silu, n, s, &a); +} diff --git a/zig/src/hip/launches/rope.zig b/zig/src/hip/launches/rope.zig new file mode 100644 index 00000000000..69ec48c0fd0 --- /dev/null +++ b/zig/src/hip/launches/rope.zig @@ -0,0 +1,68 @@ +//! RoPE launches: decode, prefill and the window's fused q / k norm and rotation. + +const Launcher = @import("../launches.zig").Launcher; +const util = @import("util.zig"); +const S = util.S; +const P = util.P; +const C = util.C; +const F = util.F; +const CF = util.CF; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; +const invalid = util.invalid; + +pub fn tf_qk_rope(l: *const Launcher, src: C, kind: c_int, s_row: c_longlong, s_head: c_int, weight: CF, eps: f32, rows: c_int, heads: c_int, width: c_int, rotary: c_int, theta: f32, pos: CI, wide: F, cache: P, total: c_int, s: S) Error!void { + if (width > 512) return invalid("qk_rope"); + var a: Args = .{}; + try a.add(ad(src)); + try a.add(kind); + try a.add(s_row); + try a.add(s_head); + try a.add(ad(weight)); + try a.add(eps); + try a.add(rows); + try a.add(heads); + try a.add(width); + try a.add(rotary); + try a.add(theta); + try a.add(ad(pos)); + try a.add(ad(wide)); + try a.add(ad(cache)); + try a.add(total); + // a wave a (row, head), 8 a block + try l.go(l.op.qk_rope, dim(cdiv(@as(i64, rows) * heads, 8), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +pub fn tf_rope_decode(l: *const Launcher, x: CF, y: F, rows: c_int, width: c_int, rotary: c_int, pos: c_int, theta: f32, s: S, pos_dev: CI, per: c_int) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(ad(y)); + try a.add(width); + try a.add(rotary); + try a.add(pos); + try a.add(theta); + try a.add(ad(pos_dev)); + try a.add(per); + try l.go(l.rope_decode, dim(rows, 1, 1), dim(32, 1, 1), 0, s, &a); +} + +pub fn tf_rope_prefill(l: *const Launcher, x: C, kind: c_int, out: P, out_kind: c_int, s_head: c_longlong, s_row: c_longlong, len: c_int, heads: c_int, d: c_int, rotary: c_int, pos0: c_int, theta: f32, s: S) Error!void { + var a: Args = .{}; + try a.add(ad(x)); + try a.add(kind); + try a.add(ad(out)); + try a.add(out_kind); + try a.add(s_head); + try a.add(s_row); + try a.add(len); + try a.add(heads); + try a.add(d); + try a.add(rotary); + try a.add(pos0); + try a.add(theta); + try l.flat(l.op.rope_prefill, @as(i64, len) * heads * d, s, &a); +} diff --git a/zig/src/hip/launches/util.zig b/zig/src/hip/launches/util.zig new file mode 100644 index 00000000000..ffa49027728 --- /dev/null +++ b/zig/src/hip/launches/util.zig @@ -0,0 +1,49 @@ +//! The launchers' shared shorthand: argument types, device addresses and grid arithmetic. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); +const launch = @import("../launch.zig"); +const Function = @import("../module.zig").Function; + +pub const Error = runtime.Error; + +/// A stream handle; `counting` launches nothing, so a dry run measures the scratch a forward takes. +pub const S = abi.Stream; +pub const counting: S = @ptrFromInt(0x1); +pub const P = ?*anyopaque; +pub const C = ?*const anyopaque; +pub const F = ?[*]f32; +pub const CF = ?[*]const f32; +pub const I = ?[*]i32; +pub const CI = ?[*]const i32; + +pub const Dim3 = launch.Dim3; +pub const Args = launch.Args; + +/// A device address as the kernel argument it is. +pub fn ad(p: anytype) u64 { + return @intFromPtr(p); +} + +pub fn dim(x: anytype, y: anytype, z: anytype) Dim3 { + return .{ .x = @intCast(x), .y = @intCast(y), .z = @intCast(z) }; +} + +/// ceil(n / by) as a grid extent. +pub fn cdiv(n: anytype, by: anytype) usize { + return (@as(usize, @intCast(n)) + by - 1) / by; +} + +/// The kernel of a triple for an activation kind: fp16 and bf16 by number, anything else the first. +pub fn tri(kind: c_int) usize { + return if (kind == 1 or kind == 2) @intCast(kind) else 0; +} + +/// By kind (0 fp32, 1 fp16, 2 bf16) or by cache kind (0 fp16, 1 bf16, 2 fp32), the kernel one instantiation. +pub const Triple = [3]Function; + +pub fn invalid(what: []const u8) Error { + std.log.err("{s}: shape", .{what}); + return error.Invalid; +} diff --git a/zig/src/hip/ops/attention.zig b/zig/src/hip/ops/attention.zig new file mode 100644 index 00000000000..7e356c4e4cf --- /dev/null +++ b/zig/src/hip/ops/attention.zig @@ -0,0 +1,87 @@ +//! Attention launches: the gate, RoPE, cache writes and the causal kernels over a cache. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const Kind = t.Kind; +const p = t.p; +const f = t.f; +const int = t.int; + +/// The gated attention's o input from att fp32, (heads, len, d) or (len, heads, d) with `rows_major`, and the gate. +pub fn attnGate(o: Ops, att: u64, qg: Tensor, out: Tensor, len: usize, heads: usize, d: usize, rows_major: bool) Error!void { + try o.l.tf_attn_gate(f(att), p(qg.ptr), p(out.ptr), @backingInt(out.kind), int(len), int(heads), int(d), @intFromBool(rows_major), o.stream); +} + +/// Prefill RoPE of x (len, heads, d), rounded to x's kind, stored as `out` kind at out[h * s_head + r * s_row + j]. +pub fn ropePrefill(o: Ops, x: Tensor, out: Tensor, s_head: usize, s_row: usize, len: usize, heads: usize, d: usize, rotary: usize, pos0: usize, theta: f32) Error!void { + try o.l.tf_rope_prefill(p(x.ptr), @backingInt(x.kind), p(out.ptr), @backingInt(out.kind), @intCast(s_head), @intCast(s_row), int(len), int(heads), int(d), int(rotary), int(pos0), theta, o.stream); +} + +/// A window's q or k heads RMS-normed with `weight`, rotated at `pos`, rounded; into fp32 `wide` and/or cache slots. +pub fn qkRope(o: Ops, src: Tensor, s_row: usize, s_head: usize, weight: u64, eps: f32, rows: usize, heads: usize, width: usize, rotary: usize, theta: f32, pos: u64, wide: ?u64, cache: ?u64, total: usize) Error!void { + if (width > 512 or src.kind == .f32) return error.BadShape; + try o.l.tf_qk_rope(p(src.ptr), @backingInt(src.kind), @intCast(s_row), int(s_head), f(weight), eps, int(rows), int(heads), int(width), int(rotary), theta, @ptrFromInt(pos), if (wide) |w| f(w) else null, if (cache) |c| p(c) else null, int(total), o.stream); +} + +/// The decode RoPE over fp32 rows; `pos_dev` (int32, one a group of `per` rows) or the host `pos`. +pub fn ropeDecode(o: Ops, x: u64, y: u64, rows: usize, width: usize, rotary: usize, pos: usize, theta: f32, pos_dev: ?u64, per: usize) Error!void { + try o.l.tf_rope_decode(f(x), f(y), int(rows), int(width), int(rotary), int(pos), theta, o.stream, if (pos_dev) |a| @ptrFromInt(a) else null, int(per)); +} + +pub fn kvWrite(o: Ops, src: Tensor, cache: u64, len: usize, kv_heads: usize, d: usize, total: usize, pos0: usize) Error!void { + try o.l.tf_kv_write(p(src.ptr), p(cache), @backingInt(src.kind), int(len), int(kv_heads), int(d), int(total), int(pos0), o.stream); +} + +/// kv_write with the first slot read from the device (one int32), for graphs replayed at new positions. +pub fn kvWriteAt(o: Ops, src: Tensor, cache: u64, len: usize, kv_heads: usize, d: usize, total: usize, pos: u64) Error!void { + try o.l.tf_kv_write_at(p(src.ptr), p(cache), @backingInt(src.kind), int(len), int(kv_heads), int(d), int(total), @ptrFromInt(pos), o.stream); +} + +/// The cache's layout: `kv_heads` heads of `total` slots of `d` values (batch 1). +pub const Cache = struct { k: u64, v: u64, kind: Kind, kv_heads: usize, total: usize, d: usize }; + +/// Prefill attention on the prefill tile (any query count): q (heads, qlen, d) fp32 over the first `span` slots. +pub fn causalPrefill(o: Ops, q: u64, c: Cache, out: u64, qlen: usize, span: usize, heads: usize, scale: f32, q_pos0: usize) Error!void { + if (c.d > 256 or heads % c.kv_heads != 0) return error.BadShape; + const sh: c_longlong = @intCast(c.total * c.d); + const ss: c_longlong = @intCast(c.d); + try o.l.tf_causal(f(q), p(c.k), p(c.v), f(out), 1, int(qlen), int(span), int(heads), int(c.kv_heads), int(c.d), scale, int(q_pos0), sh * @as(c_longlong, @intCast(c.kv_heads)), sh, ss, sh * @as(c_longlong, @intCast(c.kv_heads)), sh, ss, c.kind.cache(), null, null, null, o.stream, null); +} + +/// One attention layer of a stream's paged cache: key and value pools (`count` 64-position pages a head), page table. +pub const Paged = struct { k: u64, v: u64, table: u64, kind: Kind, kv_heads: usize, d: usize, count: usize }; + +fn zigLaunches(o: Ops) Error!*const @import("../launches.zig").Launcher { + return o.l; +} + +/// 16-bit `src` values (h * s_head + r * s_row + j elements) of `len` positions from `pos0` into a pool by the table. +pub fn pageWrite(o: Ops, src: u64, pool: u64, table: u64, len: usize, kv_heads: usize, d: usize, s_head: usize, s_row: usize, pos0: usize, count: usize) Error!void { + try (try zigLaunches(o)).pagesWrite(src, pool, table, len, kv_heads, d, s_head, s_row, pos0, count, o.stream); +} + +/// Prefill attention over a stream's pages: the 64-row tile reads pages; other shapes read a flat copy. +pub fn causalPaged(o: Ops, q: u64, c: Paged, out: u64, qlen: usize, span: usize, heads: usize, scale: f32, q_pos0: usize) Error!void { + if (c.d > 256 or heads % c.kv_heads != 0 or c.kind == .f32) return error.BadShape; + const z = try zigLaunches(o); + if (c.d % 64 == 0 and z.wide) return z.pagedCausal(q, c.k, c.v, c.table, out, qlen, span, heads, c.kv_heads, c.d, scale, q_pos0, c.count, c.kind.cache(), o.stream); + const bytes = c.kv_heads * span * c.d * 2; + const flat: Cache = .{ .k = try o.arena.take(bytes), .v = try o.arena.take(bytes), .kind = c.kind, .kv_heads = c.kv_heads, .total = span, .d = c.d }; + try z.pagesGather(c.k, c.table, flat.k, span, c.kv_heads, c.d, c.count, o.stream); + try z.pagesGather(c.v, c.table, flat.v, span, c.kv_heads, c.d, c.count, o.stream); + try causalPrefill(o, q, flat, out, qlen, span, heads, scale, q_pos0); +} + +/// causal_at: `rows` queries (rows, heads, 1, d) fp32 each at its device position over one shared cache. +pub fn causalAt(o: Ops, q: u64, c: Cache, out: u64, rows: usize, heads: usize, scale: f32, pos: u64) Error!void { + if (c.d > 256 or heads % c.kv_heads != 0) return error.BadShape; + const span = c.total; + const scores = try o.arena.of(f32, rows * heads * span); + const stats = try o.arena.of(f32, rows * heads * 2); + const partials = try o.arena.of(f32, rows * heads * ((span + 127) / 128) * c.d); + const sh: c_longlong = @intCast(c.total * c.d); + const ss: c_longlong = @intCast(c.d); + try o.l.tf_causal(f(q), p(c.k), p(c.v), f(out), int(rows), 1, int(span), int(heads), int(c.kv_heads), int(c.d), scale, 0, 0, sh, ss, 0, sh, ss, c.kind.cache(), f(scores), f(stats), f(partials), o.stream, @ptrFromInt(pos)); +} diff --git a/zig/src/hip/ops/draw.zig b/zig/src/hip/ops/draw.zig new file mode 100644 index 00000000000..6e6463acab3 --- /dev/null +++ b/zig/src/hip/ops/draw.zig @@ -0,0 +1,22 @@ +//! The draw inputs read from logits rows: argmax and the top ids. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// torch.argmax of each of `rows` logits rows (width `n`, fp16 or bf16) into device i32 `out`. +pub fn argmaxRows(o: Ops, logits: Tensor, rows: usize, n: usize, out: u64) Error!void { + if (logits.kind == .f32) return error.BadShape; + try o.l.tf_argmax_rows(p(logits.ptr), @backingInt(logits.kind), int(rows), int(n), i(out), o.stream); +} + +/// Each row's `ks[r]` largest by (value desc, id asc): ids (i32) and the values' 16-bit patterns, `stride` apart. +pub fn topkRows(o: Ops, logits: Tensor, rows: usize, n: usize, ks: u64, stride: usize, ids: u64, values: u64) Error!void { + if (logits.kind == .f32) return error.BadShape; + try o.l.tf_topk_rows(p(logits.ptr), int(rows), int(n), i(ks), int(stride), i(ids), p(values), o.stream); +} diff --git a/zig/src/hip/ops/elementwise.zig b/zig/src/hip/ops/elementwise.zig new file mode 100644 index 00000000000..a5497c4b8a5 --- /dev/null +++ b/zig/src/hip/ops/elementwise.zig @@ -0,0 +1,26 @@ +//! Casts and the elementwise launches. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const int = t.int; + +pub fn cast(o: Ops, src: Tensor, dst: Tensor, n: usize) Error!void { + try o.l.tf_cast(p(src.ptr), @backingInt(src.kind), p(dst.ptr), @backingInt(dst.kind), @intCast(n), o.stream); +} + +pub fn siluMul(o: Ops, gate: Tensor, up: Tensor, out: Tensor, n: usize) Error!void { + if (gate.kind != up.kind or gate.kind != out.kind) return error.BadShape; + try o.l.tf_silu_mul(p(gate.ptr), p(up.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} + +pub fn add(o: Ops, x: Tensor, y: Tensor, out: Tensor, n: usize) Error!void { + if (x.kind != y.kind or x.kind != out.kind) return error.BadShape; + try o.l.tf_add(p(x.ptr), p(y.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} + +pub fn copyCols(o: Ops, src: Tensor, stride: usize, offset: usize, dst: u64, rows: usize, cols: usize) Error!void { + try o.l.tf_copy_cols(p(src.ptr), @intCast(stride), int(offset), p(dst), @backingInt(src.kind), int(rows), int(cols), o.stream); +} diff --git a/zig/src/hip/ops/moe.zig b/zig/src/hip/ops/moe.zig new file mode 100644 index 00000000000..effaebbe812 --- /dev/null +++ b/zig/src/hip/ops/moe.zig @@ -0,0 +1,42 @@ +//! The mixture-of-experts launches: the router, the pick, the plan, the activation and the combine. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// MoE combine, residual and next norm in one launch: x = round(x + round(sum_s wts * y)), normed = rms(x) * weight. +pub fn moeTail(o: Ops, x: Tensor, y: u64, wts: u64, weight: u64, normed: Tensor, rows: usize, slots: usize, width: usize, eps: f32) Error!void { + if (x.kind != normed.kind or x.kind == .f32 or slots == 0) return error.BadShape; + const z = o.l; + try z.tf_tail(p(x.ptr), f(y), f(wts), f(weight), p(normed.ptr), @backingInt(x.kind), int(rows), int(slots), int(width), eps, o.stream); +} + +pub fn moeRouter(o: Ops, x: Tensor, rows32: u64, logits: u64, r: usize, d: usize, e: usize) Error!void { + if (o.window) if (o.l.routerWindow(p(x.ptr), @backingInt(x.kind), f(rows32), f(logits), int(r), int(d), int(e), o.stream)) |ran| { + if (ran) return; + } else |err| return err; + if (o.prefill and d % 32 == 0) return o.l.routerTile(p(x.ptr), @backingInt(x.kind), f(rows32), f(logits), int(r), int(d), int(e), o.stream); + try o.l.tf_moe_router(p(x.ptr), @backingInt(x.kind), f(rows32), f(logits), int(r), int(d), int(e), o.stream); +} + +/// The pick rule per row; with `plan` (one row) it also writes the plan's items and members. +pub fn moeSelect(o: Ops, logits: u64, pick: u64, wts: u64, plan: ?struct { items: u64, members: u64 }, capacity: usize, r: usize, experts: usize, top_k: usize) Error!void { + try o.l.tf_moe_select(f(logits), i(pick), f(wts), if (plan) |pl| i(pl.items) else null, if (plan) |pl| i(pl.members) else null, int(capacity), int(r), int(experts), int(top_k), o.stream); +} + +pub fn moeRoute(o: Ops, picks: u64, pairs: usize, experts: usize, tile: usize, members: u64, items: u64, capacity: usize) Error!void { + try o.l.tf_moe_route(@ptrFromInt(picks), int(pairs), int(experts), int(tile), i(members), i(items), int(capacity), o.stream); +} + +pub fn moeAct(o: Ops, both: u64, out: Tensor, pairs: usize, width: usize, limit: f32) Error!void { + try o.l.tf_moe_act(f(both), p(out.ptr), @backingInt(out.kind), int(pairs), int(width), limit, o.stream); +} + +pub fn moeCombine(o: Ops, y: u64, wts: u64, out: Tensor, r: usize, slots: usize, d: usize) Error!void { + try o.l.tf_moe_combine(f(y), f(wts), p(out.ptr), @backingInt(out.kind), int(r), int(slots), int(d), o.stream); +} diff --git a/zig/src/hip/ops/norms.zig b/zig/src/hip/ops/norms.zig new file mode 100644 index 00000000000..5bfb46d2f02 --- /dev/null +++ b/zig/src/hip/ops/norms.zig @@ -0,0 +1,39 @@ +//! Norm launches and the decode tails that fuse a norm. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const int = t.int; + +pub fn rms(o: Ops, x: Tensor, weight: ?u64, y: Tensor, rows: usize, width: usize, eps: f32) Error!void { + if (x.kind != y.kind or width < 1 or width > 8192) return error.BadShape; + if (rows == 0) return; + try o.l.tf_rms(p(x.ptr), if (weight) |w| f(w) else null, p(y.ptr), @backingInt(x.kind), int(rows), int(width), eps, o.stream); +} + +/// Two sets of fp32 rows (width at most 1024), each normed with its own weight, in one launch. +pub fn rms2(o: Ops, x0: u64, w0: u64, y0: u64, x1: u64, w1: u64, y1: u64, rows: usize, width: usize, eps: f32) Error!void { + const z = o.l; + try z.tf_rms2(f(x0), f(w0), f(y0), f(x1), f(w1), f(y1), int(rows), int(width), eps, o.stream); +} + +/// The linear attention's gated norm: out = rms(y) * weight * round(silu(z)) in z's kind, `width` at most 1024. +pub fn gnormOut(o: Ops, y: u64, weight: u64, z: Tensor, out: Tensor, rows: usize, width: usize, eps: f32) Error!void { + if (z.kind != out.kind or z.kind == .f32) return error.BadShape; + const zig = o.l; + try zig.tf_gnorm_out(f(y), f(weight), p(z.ptr), p(out.ptr), @backingInt(z.kind), int(rows), int(width), eps, o.stream); +} + +/// x = round(x + y) and normed = rms(x) * weight (fp32) in one launch: a residual and the norm after it. +pub fn addRms(o: Ops, x: Tensor, y: Tensor, weight: u64, normed: Tensor, rows: usize, width: usize, eps: f32) Error!void { + if (x.kind != y.kind or x.kind != normed.kind or x.kind == .f32) return error.BadShape; + const z = o.l; + try z.tf_tail(p(x.ptr), p(y.ptr), null, f(weight), p(normed.ptr), @backingInt(x.kind), int(rows), 0, int(width), eps, o.stream); +} + +pub fn gnormSilu(o: Ops, y: u64, z: Tensor, out: Tensor, n: usize) Error!void { + try o.l.tf_gnorm_silu(f(y), p(z.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} diff --git a/zig/src/hip/ops/ops.zig b/zig/src/hip/ops/ops.zig new file mode 100644 index 00000000000..beada05c68c --- /dev/null +++ b/zig/src/hip/ops/ops.zig @@ -0,0 +1,79 @@ +//! Typed launches of the model-free kernels: shapes checked here, as the kernels trust them; `Ops` holds them. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const Launcher = @import("../launches.zig").Launcher; +const Arena = @import("../arena.zig").Arena; +const types = @import("types.zig"); +const attention = @import("attention.zig"); +const recurrence = @import("recurrence.zig"); +const norms = @import("norms.zig"); +const elementwise = @import("elementwise.zig"); +const moe = @import("moe.zig"); +const draw = @import("draw.zig"); + +pub const Kind = types.Kind; +pub const Error = types.Error; +pub const Tensor = types.Tensor; + +pub const Ops = struct { + l: *const Launcher, + /// The activations are bf16 (fp16 where the GPU has no bf16 dot2: RDNA2). + bf16: bool, + stream: abi.Stream, + arena: *Arena, + /// A prompt's span: products and router take prefill's kernel, so rows have the same bits however cut. + prefill: bool = false, + /// A lane round's forward: decode tiles at any row count, so a row's bits ignore the rows it shares a round with. + window: bool = false, + + /// Whether decode.hip's merged launches are on. + pub fn fused(o: Ops) bool { + return o.l.fuse; + } + + pub const attnGate = attention.attnGate; + pub const ropePrefill = attention.ropePrefill; + pub const qkRope = attention.qkRope; + pub const ropeDecode = attention.ropeDecode; + pub const kvWrite = attention.kvWrite; + pub const kvWriteAt = attention.kvWriteAt; + pub const Cache = attention.Cache; + pub const Paged = attention.Paged; + pub const pageWrite = attention.pageWrite; + pub const causalPaged = attention.causalPaged; + pub const causalPrefill = attention.causalPrefill; + pub const causalAt = attention.causalAt; + pub const convPrefill = recurrence.convPrefill; + pub const convDecode = recurrence.convDecode; + pub const convRows = recurrence.convRows; + pub const gdnGatePrefill = recurrence.gdnGatePrefill; + pub const gdnGate = recurrence.gdnGate; + pub const gatedDelta = recurrence.gatedDelta; + pub const rms = norms.rms; + pub const rms2 = norms.rms2; + pub const gnormOut = norms.gnormOut; + pub const addRms = norms.addRms; + pub const gnormSilu = norms.gnormSilu; + pub const cast = elementwise.cast; + pub const siluMul = elementwise.siluMul; + pub const add = elementwise.add; + pub const copyCols = elementwise.copyCols; + pub const moeTail = moe.moeTail; + pub const moeRouter = moe.moeRouter; + pub const moeSelect = moe.moeSelect; + pub const moeRoute = moe.moeRoute; + pub const moeAct = moe.moeAct; + pub const moeCombine = moe.moeCombine; + pub const argmaxRows = draw.argmaxRows; + pub const topkRows = draw.topkRows; +}; + +test "dtype numberings of the three kernel families" { + try std.testing.expectEqual(@as(c_int, 1), @backingInt(Kind.f16)); + try std.testing.expectEqual(@as(c_int, 0), Kind.f16.cache()); +} + +test "every launch compiles" { + std.testing.refAllDecls(Ops); +} diff --git a/zig/src/hip/ops/plan.zig b/zig/src/hip/ops/plan.zig new file mode 100644 index 00000000000..16b3d9d03b9 --- /dev/null +++ b/zig/src/hip/ops/plan.zig @@ -0,0 +1,100 @@ +//! A lane round's launches over its device plan: arguments depend only on the plan's shape and the layer. + +const t = @import("types.zig"); +const launches = @import("../launches.zig"); +const Ops = @import("ops.zig").Ops; + +const Tensor = t.Tensor; +const Error = t.Error; + +pub const Args = launches.PlanArgs; +pub const Plan = launches.PlanRef; +pub const Keep = launches.PlanKeep; + +fn launcher(o: Ops) Error!*const launches.Launcher { + return o.l; +} + +fn int(n: usize) c_int { + return @intCast(n); +} + +/// The conv's norm weights of q and k heads (heads of 128) and the delta rule's gate and beta computed beside it. +pub const Norm = struct { q: u64, k: u64, eps: f32 }; +pub const Gates = struct { a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64, beta: u64, count: usize, heads: usize }; + +/// The round's rows through the linear attention's conv from each slot's window, split into q, k, v fp32. +pub fn convSplit(o: Ops, x: Tensor, weight: u64, qn: u64, kn: u64, v: u64, p: Plan, layer: usize, channels: usize, kernel: usize, kw: usize, vw: usize, norm: ?Norm, gates: ?Gates) Error!void { + if (kernel < 1 or kernel > 8 or x.kind == .f32) return error.BadShape; + const z = try launcher(o); + var c: launches.ConvArgs = .{ + .x = x.ptr, + .kind = @backingInt(x.kind), + .weight = weight, + .state = 0, + .qn = qn, + .kn = kn, + .v = v, + .channels = int(channels), + .kernel = int(kernel), + .rows = int(p.rows), + .kw = int(kw), + .vw = int(vw), + .plan = p.args, + .layer = int(layer), + .slots = int(p.slots), + }; + if (norm) |nm| { + c.qw = nm.q; + c.kw_w = nm.k; + c.eps = nm.eps; + c.norm = 128; + } + if (gates) |g| { + if (g.a.kind != x.kind or g.b.kind != x.kind) return error.BadShape; + c.ga = g.a.ptr; + c.gb = g.b.ptr; + c.a_log = g.a_log; + c.dt_bias = g.dt_bias; + c.gate = g.gate; + c.beta = g.beta; + c.gcount = int(g.count); + c.heads = int(g.heads); + } + try z.tf_conv_split(c, o.stream); +} + +/// The DeltaNet recurrence of every slot's rows: q, k (rows, Hk, dk), v, y (rows, Hv, dv), gate, beta (rows, Hv) fp32. +pub fn gatedDelta(o: Ops, q: u64, k: u64, v: u64, gate: u64, beta: u64, y: u64, p: Plan, layer: usize, key_heads: usize, value_heads: usize, dk: usize, dv: usize) Error!void { + try (try launcher(o)).planGatedDelta(q, k, v, gate, beta, y, p, layer, key_heads, value_heads, dk, dv, o.stream); +} + +/// Each row's keys (fp32, rotated) and values (the activation kind) into its slot's caches at its position. +pub fn kvWrite(o: Ops, keys: u64, values: Tensor, p: Plan, layer: usize, kv_heads: usize, d: usize) Error!void { + if (values.kind == .f32) return error.BadShape; + try (try launcher(o)).planKvWrite(keys, values.ptr, @backingInt(values.kind), p, layer, kv_heads, d, o.stream); +} + +/// One query a row (rows, heads, d) fp32 over its slot's caches up to its position, the walk over `span` keys. +pub fn causal(o: Ops, q: u64, kind: t.Kind, out: u64, p: Plan, layer: usize, heads: usize, kv_heads: usize, d: usize, span: usize, scale: f32) Error!void { + const tiles = (span + 127) / 128; + const scores = try o.arena.of(f32, p.rows * heads * span); + const stats = try o.arena.of(f32, p.rows * heads * 2); + const partials = try o.arena.of(f32, p.rows * heads * tiles * d); + try (try launcher(o)).planCausal(q, out, scores, stats, partials, p, layer, heads, kv_heads, d, span, scale, @backingInt(kind), o.stream); +} + +/// Keeps the listed slots' rows (see `launches.PlanKeep`). +pub fn keep(o: Ops, p: Plan, k: Keep) Error!void { + try (try launcher(o)).planKeep(p, k, o.stream); +} + +/// The kept slots' DeltaNet states replayed through their kept rows (see `launches.planGdnReplay`). +pub fn gdnReplay(o: Ops, keep_counts: u64, p: Plan, key_heads: usize, value_heads: usize, dk: usize, dv: usize, layers: usize) Error!void { + try (try launcher(o)).planGdnReplay(keep_counts, p, key_heads, value_heads, dk, dv, layers, o.stream); +} + +/// Row r of `dst` (`words` words each) from the address in `srcs[r]` (device u64s), for `rows` rows. +pub fn gather(o: Ops, srcs: u64, dst: u64, words: usize, rows: usize) Error!void { + try (try launcher(o)).planGather(srcs, dst, words, rows, o.stream); +} diff --git a/zig/src/hip/ops/recurrence.zig b/zig/src/hip/ops/recurrence.zig new file mode 100644 index 00000000000..cf2b5f8be57 --- /dev/null +++ b/zig/src/hip/ops/recurrence.zig @@ -0,0 +1,36 @@ +//! The linear attention: the conv, the gates and the DeltaNet recurrence. + +const t = @import("types.zig"); +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const p = t.p; +const f = t.f; +const int = t.int; + +pub fn convPrefill(o: Ops, x: Tensor, weight: u64, state: ?u64, out: u64, new_state: u64, len: usize, channels: usize, kernel: usize) Error!void { + if (kernel < 1 or kernel > 8) return error.BadShape; + try o.l.tf_conv_prefill(p(x.ptr), @backingInt(x.kind), f(weight), if (state) |s| f(s) else null, f(out), f(new_state), int(len), int(channels), int(kernel), o.stream); +} + +pub fn convDecode(o: Ops, x: u64, weight: u64, state: u64, y: u64, channels: usize, kernel: usize) Error!void { + try o.l.tf_conv_decode(f(x), f(weight), f(state), f(y), 1, int(channels), int(kernel), o.stream); +} + +pub fn convRows(o: Ops, x: u64, weight: u64, state: u64, y: u64, states: ?u64, rows: usize, channels: usize, kernel: usize) Error!void { + try o.l.tf_conv_rows(f(x), f(weight), f(state), f(y), if (states) |s| f(s) else null, int(rows), int(channels), int(kernel), o.stream); +} + +pub fn gdnGatePrefill(o: Ops, a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64, beta: u64, count: usize, heads: usize) Error!void { + try o.l.tf_gdn_gate_prefill(p(a.ptr), p(b.ptr), @backingInt(a.kind), f(a_log), f(dt_bias), f(gate), f(beta), int(count), int(heads), o.stream); +} + +/// The fused gate over `elements` values of a and b (rows times heads). +pub fn gdnGate(o: Ops, a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64, beta: u64, elements: usize, heads: usize) Error!void { + try o.l.tf_gdn_gate(p(a.ptr), p(b.ptr), @backingInt(a.kind), f(a_log), f(dt_bias), f(gate), f(beta), int(elements), int(heads), o.stream); +} + +/// The DeltaNet recurrence in fp32, state in place, the same walk at every length. +pub fn gatedDelta(o: Ops, q: u64, k: u64, v: u64, gate: u64, beta: u64, state: u64, y: u64, length: usize, key_heads: usize, value_heads: usize, dk: usize, dv: usize, states: ?u64) Error!void { + try o.l.tf_gated_delta(f(q), f(k), f(v), f(gate), f(beta), f(state), f(y), 1, int(length), int(key_heads), int(value_heads), int(dk), int(dv), o.stream, if (states) |s| f(s) else null); +} diff --git a/zig/src/hip/ops/types.zig b/zig/src/hip/ops/types.zig new file mode 100644 index 00000000000..7f6e521cfda --- /dev/null +++ b/zig/src/hip/ops/types.zig @@ -0,0 +1,44 @@ +//! The types the launches share: buffer kinds, a device tensor and the address casts. + +const runtime = @import("../runtime.zig"); + +/// act.hpp's numbering: the activation and fp32 buffers the torch-op kernels read and write. +pub const Kind = enum(c_int) { + f32 = 0, + f16 = 1, + bf16 = 2, + + pub fn size(k: Kind) usize { + return if (k == .f32) 4 else 2; + } + + /// The attention kernel's cache numbering: 0 fp16, 1 bf16, 2 fp32. + pub fn cache(k: Kind) c_int { + return switch (k) { + .f16 => 0, + .bf16 => 1, + .f32 => 2, + }; + } +}; + +pub const Error = runtime.Error || error{ OutOfDeviceMemory, BadShape }; + +/// A device buffer of `kind` values. +pub const Tensor = struct { ptr: u64, kind: Kind }; + +pub fn p(addr: u64) ?*anyopaque { + return @ptrFromInt(addr); +} + +pub fn f(addr: u64) ?[*]f32 { + return @ptrFromInt(addr); +} + +pub fn i(addr: u64) ?[*]i32 { + return @ptrFromInt(addr); +} + +pub fn int(v: anytype) c_int { + return @intCast(v); +} diff --git a/zig/tests/hip_kernels.md b/zig/tests/hip_kernels.md new file mode 100644 index 00000000000..cebd41e6441 --- /dev/null +++ b/zig/tests/hip_kernels.md @@ -0,0 +1,26 @@ +# HIP model-free kernels + +`zig build hip-kernel-test -Dhip-arch=gfx1100` + +The kernels a model engine composes, compiled by hipcc for one `-Dhip-arch` with the caps table's instruction +switches, embedded, and launched from Zig on #463's runtime. No model or checkpoint is involved. + +The GPU tests check: + +- Every kernel the launchers use resolves in the embedded code objects for the device's architecture. +- The planned decode walk over a permuted page table writes the flat walk's bits for 8, 6, 4 and 1 query heads + a KV head, and sits within 1e-5 of float64 at positions 0, 37, 300 and 1023. +- The 64-row prompt tile over pages writes the flat tile's bits, within the cache type's rounding of float64. +- The DeltaNet recurrence, token-serial and chunked, within 5e-3 of a float64 recurrence at 64 to 4170 tokens. +- The merged decode launches (router, residual-and-norm tails) no further from float64 than twice the launches + they replace; the merged conv split, MoE pick and gated norm writing the replaced chains' bytes. +- Casts, sums, column copies, cache writes, argmax, top-k and the MoE route giving torch's bits; silu products, + gates, the MoE activation and RoPE within one rounding of float64. + +Build notes: + +- `-Dhipcc` and `-Dhip-include` as for `hip-gpu-test`. +- `-Dhip-device-lib=` names ROCm's device bitcode directory. The default is `/lib/llvm/amdgcn/bitcode`, + TheRock's layout; Arch's ROCm keeps it in `/amdgcn/bitcode`, and Ubuntu's packaged HIP in the LLVM clang + resource directory (`/usr/lib/llvm-21/lib/clang/21/amdgcn/bitcode` for HIP 7.1). +- No kernel includes rocWMMA, so ROCm packages without its header (Ubuntu's HIP 7.1) build them too.