From b731206a8195f1f1d28850e0b5007f70d98c1510 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:23:32 +0200 Subject: [PATCH 01/52] feat(hip): the model-free kernels on #463's runtime: attention, DeltaNet, norms, RoPE, MoE routing and decode plans The kernels a model engine composes, built by hipcc for -Dhip-arch with the caps table's instruction switches and embedded as one code object a source group, launched from Zig: elementwise ops and casts, norms and the merged decode tails, RoPE, the attention walks (flat, planned over a page table with the query heads of a KV head read together, the 64-row prompt tile flat and paged), the DeltaNet recurrence token-serial and chunked, the linear attention's conv and gates, the MoE router, pick and route, argmax and top-k, and a lane round's plan kernels. A typed Ops layer checks shapes; an arena hands out a forward's scratch, and a counting stream measures it without launching. hip-kernel-test checks each against a host or float64 reference, and the merged and paged forms against the forms they replace, bit for bit where they promise it; -Dhip-device-lib names ROCm's bitcode. The sources hold device code only: plain kernels by C name, templates instantiated for the types the launches use. --- zig/build/hip.zig | 51 ++ zig/kernels/hip/attention/attention.hip | 236 ++++++++++ zig/kernels/hip/attention/attention_fa.hip | 462 +++++++++++++++++++ zig/kernels/hip/attention/prefill.hip | 278 +++++++++++ zig/kernels/hip/decode/decode.hip | 423 +++++++++++++++++ zig/kernels/hip/decode/pages.hpp | 14 + zig/kernels/hip/decode/plan.hip | 219 +++++++++ zig/kernels/hip/decode/plan.hpp | 30 ++ zig/kernels/hip/ops/act.hip | 279 +++++++++++ zig/kernels/hip/ops/attention.hpp | 49 ++ zig/kernels/hip/ops/common.hpp | 47 ++ zig/kernels/hip/ops/draw.hpp | 137 ++++++ zig/kernels/hip/ops/elementwise.hpp | 82 ++++ zig/kernels/hip/ops/linear.hpp | 65 +++ zig/kernels/hip/ops/moe.hpp | 218 +++++++++ zig/kernels/hip/ops/norms.hpp | 42 ++ zig/kernels/hip/ops/ops.hip | 10 + zig/kernels/hip/ops/rope.hpp | 87 ++++ zig/kernels/hip/recurrence/gated_delta.hip | 302 ++++++++++++ zig/kernels/hip/recurrence/gdn_prefill.hip | 475 +++++++++++++++++++ zig/src/hip/admission_tests.zig | 3 + zig/src/hip/arena.zig | 74 +++ zig/src/hip/kernel_tests.zig | 26 ++ zig/src/hip/kernel_tests/attention.zig | 225 +++++++++ zig/src/hip/kernel_tests/chain.zig | 222 +++++++++ zig/src/hip/kernel_tests/decode.zig | 135 ++++++ zig/src/hip/kernel_tests/gdn.zig | 153 ++++++ zig/src/hip/kernel_tests/ops.zig | 513 +++++++++++++++++++++ zig/src/hip/kernel_tests/rig.zig | 137 ++++++ zig/src/hip/kernels.zig | 12 + zig/src/hip/launches.zig | 314 +++++++++++++ zig/src/hip/launches/attention.zig | 162 +++++++ zig/src/hip/launches/conv.zig | 97 ++++ zig/src/hip/launches/draw.zig | 37 ++ zig/src/hip/launches/elementwise.zig | 94 ++++ zig/src/hip/launches/moe.zig | 122 +++++ zig/src/hip/launches/norms.zig | 83 ++++ zig/src/hip/launches/plan.zig | 188 ++++++++ zig/src/hip/launches/recurrence.zig | 167 +++++++ zig/src/hip/launches/rope.zig | 68 +++ zig/src/hip/launches/util.zig | 49 ++ zig/src/hip/ops/attention.zig | 87 ++++ zig/src/hip/ops/draw.zig | 22 + zig/src/hip/ops/elementwise.zig | 26 ++ zig/src/hip/ops/moe.zig | 42 ++ zig/src/hip/ops/norms.zig | 39 ++ zig/src/hip/ops/ops.zig | 79 ++++ zig/src/hip/ops/plan.zig | 100 ++++ zig/src/hip/ops/recurrence.zig | 59 +++ zig/src/hip/ops/types.zig | 44 ++ zig/tests/hip_kernels.md | 24 + 51 files changed, 6909 insertions(+) create mode 100644 zig/kernels/hip/attention/attention.hip create mode 100644 zig/kernels/hip/attention/attention_fa.hip create mode 100644 zig/kernels/hip/attention/prefill.hip create mode 100644 zig/kernels/hip/decode/decode.hip create mode 100644 zig/kernels/hip/decode/pages.hpp create mode 100644 zig/kernels/hip/decode/plan.hip create mode 100644 zig/kernels/hip/decode/plan.hpp create mode 100644 zig/kernels/hip/ops/act.hip create mode 100644 zig/kernels/hip/ops/attention.hpp create mode 100644 zig/kernels/hip/ops/common.hpp create mode 100644 zig/kernels/hip/ops/draw.hpp create mode 100644 zig/kernels/hip/ops/elementwise.hpp create mode 100644 zig/kernels/hip/ops/linear.hpp create mode 100644 zig/kernels/hip/ops/moe.hpp create mode 100644 zig/kernels/hip/ops/norms.hpp create mode 100644 zig/kernels/hip/ops/ops.hip create mode 100644 zig/kernels/hip/ops/rope.hpp create mode 100644 zig/kernels/hip/recurrence/gated_delta.hip create mode 100644 zig/kernels/hip/recurrence/gdn_prefill.hip create mode 100644 zig/src/hip/arena.zig create mode 100644 zig/src/hip/kernel_tests.zig create mode 100644 zig/src/hip/kernel_tests/attention.zig create mode 100644 zig/src/hip/kernel_tests/chain.zig create mode 100644 zig/src/hip/kernel_tests/decode.zig create mode 100644 zig/src/hip/kernel_tests/gdn.zig create mode 100644 zig/src/hip/kernel_tests/ops.zig create mode 100644 zig/src/hip/kernel_tests/rig.zig create mode 100644 zig/src/hip/kernels.zig create mode 100644 zig/src/hip/launches.zig create mode 100644 zig/src/hip/launches/attention.zig create mode 100644 zig/src/hip/launches/conv.zig create mode 100644 zig/src/hip/launches/draw.zig create mode 100644 zig/src/hip/launches/elementwise.zig create mode 100644 zig/src/hip/launches/moe.zig create mode 100644 zig/src/hip/launches/norms.zig create mode 100644 zig/src/hip/launches/plan.zig create mode 100644 zig/src/hip/launches/recurrence.zig create mode 100644 zig/src/hip/launches/rope.zig create mode 100644 zig/src/hip/launches/util.zig create mode 100644 zig/src/hip/ops/attention.zig create mode 100644 zig/src/hip/ops/draw.zig create mode 100644 zig/src/hip/ops/elementwise.zig create mode 100644 zig/src/hip/ops/moe.zig create mode 100644 zig/src/hip/ops/norms.zig create mode 100644 zig/src/hip/ops/ops.zig create mode 100644 zig/src/hip/ops/plan.zig create mode 100644 zig/src/hip/ops/recurrence.zig create mode 100644 zig/src/hip/ops/types.zig create mode 100644 zig/tests/hip_kernels.md diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 64f05a07863..c20bddcaf22 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", "recurrence/gdn_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: [8][]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..e50c9ed37c8 --- /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..aa5499542b2 --- /dev/null +++ b/zig/kernels/hip/ops/attention.hpp @@ -0,0 +1,49 @@ +#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..4cebf7bcc0a --- /dev/null +++ b/zig/kernels/hip/ops/common.hpp @@ -0,0 +1,47 @@ +#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..335f002a682 --- /dev/null +++ b/zig/kernels/hip/ops/draw.hpp @@ -0,0 +1,137 @@ +#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..9fbac8b884b --- /dev/null +++ b/zig/kernels/hip/ops/elementwise.hpp @@ -0,0 +1,82 @@ +#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..fd2ce6950a9 --- /dev/null +++ b/zig/kernels/hip/ops/linear.hpp @@ -0,0 +1,65 @@ +#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..885f8881021 --- /dev/null +++ b/zig/kernels/hip/ops/moe.hpp @@ -0,0 +1,218 @@ +#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..27c50aec8bd --- /dev/null +++ b/zig/kernels/hip/ops/rope.hpp @@ -0,0 +1,87 @@ +#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/kernels/hip/recurrence/gdn_prefill.hip b/zig/kernels/hip/recurrence/gdn_prefill.hip new file mode 100644 index 00000000000..ff7098ec340 --- /dev/null +++ b/zig/kernels/hip/recurrence/gdn_prefill.hip @@ -0,0 +1,475 @@ +// SPDX-License-Identifier: Apache-2.0 + +// SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +// Chunked Gated DeltaNet for long prompts after FLA's chunk_gated_delta_rule, in five kernels: prep, kt, wy, h, o. + +// fp16 operands and fp32 accumulation through v_dot2_f32_f16; the state and every sum stay fp32. + +// Shared-memory rows are 16-byte aligned and four banks apart: a 16-byte read of eight consecutive rows is one pass. + +#include + + +namespace { + +using half_t = _Float16; +using half2_t = _Float16 __attribute__((ext_vector_type(2))); + +constexpr int kBT = 64; // chunk +constexpr int kD = 128; // head size, keys and values +constexpr int kThreads = 256; +constexpr int kBV = 16; // value rows of a state block +constexpr int kLd = kD + 8; // a 128-wide fp16 row in shared memory +constexpr int kTLd = kBT + 8; // a 64-wide one +constexpr int kTile = kBT * kD; // a chunk's tile, in values + +struct alignas(16) Quad { + half2_t p[4]; +}; + +__device__ __forceinline__ float dot2(half2_t a, half2_t b, float c) { return __builtin_amdgcn_fdot2(a, b, c, false); } +__device__ __forceinline__ Quad ld_quad(const half_t* p) { return *reinterpret_cast(p); } +__device__ __forceinline__ Quad zero_quad() { + Quad z; + for (int i = 0; i < 4; ++i) z.p[i] = half2_t{static_cast(0), static_cast(0)}; + return z; +} + +// A barrier for data that moved through shared memory only: the global stores in flight need not land first. +__device__ __forceinline__ void lds_sync() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); +} + +// x from the lane whose index differs in bit 0, or in bit 1 (within a quad). +__device__ __forceinline__ float quad_xor1(float x) { + return __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(0, __builtin_bit_cast(int, x), 0xB1, 0xF, 0xF, true)); +} +__device__ __forceinline__ float quad_xor2(float x) { + return __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(0, __builtin_bit_cast(int, x), 0x4E, 0xF, 0xF, true)); +} + +// acc[r][c] += (row r of a) . (row c of b) over the 8-wide groups from g_first by g_stride below g_end, for c < NC. +template +__device__ __forceinline__ void tile_acc(float (&acc)[4][4], const half_t* a, int lda, const half_t* b, int b_step, + int g_first, int g_end, int g_stride) { +#pragma unroll 2 + for (int g = g_first; g < g_end; g += g_stride) { + Quad x[4], y[NC]; +#pragma unroll + for (int r = 0; r < 4; ++r) x[r] = ld_quad(a + r * lda + 8 * g); +#pragma unroll + for (int c = 0; c < NC; ++c) y[c] = ld_quad(b + c * b_step + 8 * g); +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int i = 0; i < 4; ++i) acc[r][c] = dot2(x[r].p[i], y[c].p[i], acc[r][c]); + } +} + +// The same over every group with `nc` (1 to 4, the same for the whole wave) columns. +__device__ __forceinline__ void tile_acc_wave(float (&acc)[4][4], const half_t* a, int lda, const half_t* b, int b_step, + int nc) { + switch (nc) { + case 1: tile_acc<1>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; + case 2: tile_acc<2>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; + case 3: tile_acc<3>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; + default: tile_acc<4>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; + } +} + +// A chunk tile as the 16-byte pieces a thread fetches, rows from `n` on zero, stored into shared rows of kLd. +struct Tile { + Quad piece[4]; + + __device__ __forceinline__ void fetch(const half_t* src, int n) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = threadIdx.x + j * kThreads; + piece[j] = (idx >> 4) < n ? ld_quad(src + idx * 8) : zero_quad(); + } + } + + __device__ __forceinline__ void store(half_t* dst) const { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = threadIdx.x + j * kThreads; + *reinterpret_cast(&dst[(idx >> 4) * kLd + 8 * (idx & 15)]) = piece[j]; + } + } +}; + +} // namespace + +// q, k (key heads) and v (value heads) to fp16 tiles [chunk][head][64][128]. +extern "C" __global__ void __launch_bounds__(kThreads) +tf_gdn_prep(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, + half_t* __restrict__ qh, half_t* __restrict__ kh, half_t* __restrict__ vh, int length, int key_heads, + int value_heads) { + const long long id = static_cast(blockIdx.x) * kThreads + threadIdx.x; + const long long nk = static_cast(length) * key_heads * (kD / 4); + const long long nv = static_cast(length) * value_heads * (kD / 4); + if (id < nk + nv) { + const bool is_v = id >= nk; + const long long at = is_v ? id - nk : id; + const int heads = is_v ? value_heads : key_heads; + const int d4 = static_cast(at & 31); + const long long row = at >> 5; // t * heads + head + const int head = static_cast(row % heads); + const long long t = row / heads; + const long long out = (((t >> 6) * heads + head) * kBT + (t & 63)) * kD + 4 * d4; + auto put = [&](const float* src, half_t* dst) { + const float4 a = reinterpret_cast(src)[at]; + half2_t* o = reinterpret_cast(dst + out); + o[0] = half2_t{static_cast(a.x), static_cast(a.y)}; + o[1] = half2_t{static_cast(a.z), static_cast(a.w)}; + }; + if (is_v) { + put(v, vh); + } else { + put(q, qh); + put(k, kh); + } + } +} + +// kt[chunk][key head][key][token]: each chunk's keys transposed, tokens past the end zero. +extern "C" __global__ void __launch_bounds__(kThreads) +tf_gdn_kt(const half_t* __restrict__ kh, half_t* __restrict__ kt, int length, int key_heads) { + __shared__ alignas(16) half_t sT[kD * kTLd]; + const int tid = threadIdx.x; + const int chunk = blockIdx.x; + const int head = blockIdx.y; + const int n = min(kBT, length - chunk * kBT); + const half_t* tile = kh + (static_cast(chunk) * key_heads + head) * kTile; + for (int idx = tid; idx < kBT * (kD / 8); idx += kThreads) { + const int t = idx & 63, cg = idx >> 6; + Quad x = zero_quad(); + if (t < n) x = ld_quad(tile + t * kD + 8 * cg); +#pragma unroll + for (int i = 0; i < 4; ++i) { + sT[(8 * cg + 2 * i) * kTLd + t] = x.p[i][0]; + sT[(8 * cg + 2 * i + 1) * kTLd + t] = x.p[i][1]; + } + } + lds_sync(); + half_t* out = kt + (static_cast(chunk) * key_heads + head) * kD * kBT; + for (int idx = tid; idx < kD * (kBT / 8); idx += kThreads) { + const int key = idx >> 3, c8 = idx & 7; + *reinterpret_cast(&out[key * kBT + 8 * c8]) = ld_quad(&sT[key * kTLd + 8 * c8]); + } +} + +extern "C" __global__ void __launch_bounds__(kThreads) +tf_gdn_wy(const half_t* __restrict__ kh, const half_t* __restrict__ vh, const float* __restrict__ beta, + const float* __restrict__ gate, float* __restrict__ gc, half_t* __restrict__ w, half_t* __restrict__ u, int length, int key_heads, + int value_heads) { + __shared__ alignas(16) half_t sK[kBT * kLd]; + __shared__ alignas(16) float sA[kBT * kBT]; + __shared__ float sGc[kBT]; + __shared__ float sBeta[kBT]; + __shared__ float sBe[kBT]; + const int tid = threadIdx.x; + const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const int head = blockIdx.y; + const int chunk = blockIdx.x; + const int t0 = chunk * kBT; + const int n = min(kBT, length - t0); + const int key_head = head / (value_heads / key_heads); + const long long vtile = (static_cast(chunk) * value_heads + head) * kTile; + + Tile rows; + rows.fetch(kh + (static_cast(chunk) * key_heads + key_head) * kTile, n); + float rhs[kBT]; + const bool is_w = tid < kD; + const int col = tid & (kD - 1); + if (!is_w) { +#pragma unroll + for (int i = 0; i < kBT; ++i) rhs[i] = i < n ? static_cast(vh[vtile + i * kD + col]) : 0.f; + } + rows.store(sK); + if (tid < 32) { + // the chunk's running sum of log gate (a gate of 0 clamped), two tokens a lane + const long long at0 = static_cast(t0 + tid) * value_heads + head; + const long long at1 = at0 + 32LL * value_heads; + float a = tid < n ? logf(fmaxf(gate[at0], 1e-30f)) : 0.f; + float b = tid + 32 < n ? logf(fmaxf(gate[at1], 1e-30f)) : 0.f; +#pragma unroll + for (int d = 1; d < 32; d <<= 1) { + const float xa = __shfl_up(a, d, 32); + const float xb = __shfl_up(b, d, 32); + if (tid >= d) { + a += xa; + b += xb; + } + } + b += __shfl(a, 31, 32); + sGc[tid] = a; + sGc[tid + 32] = b; + if (tid < n) gc[at0] = a; + if (tid + 32 < n) gc[at1] = b; + } else if (tid < 96) { + const int i = tid - 32; + sBeta[i] = i < n ? beta[static_cast(t0 + i) * value_heads + head] : 0.f; + } + lds_sync(); + if (tid < kBT) sBe[tid] = sBeta[tid] * __expf(sGc[tid]); + + // A: each thread a 4 x 4 tile of rows 4 ti .. and columns tj + 16 c, the columns past the wave's last row skipped + { + const int ti = tid >> 4, tj = tid & 15; + const int nc = (8 * wave + 7) / 16 + 1; + float acc[4][4] = {}; + tile_acc_wave(acc, sK + ti * 4 * kLd, kLd, sK + tj * kLd, 16 * kLd, nc); +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int i = ti * 4 + r, j = tj + 16 * c; + sA[i * kBT + j] = i > j ? sBeta[i] * __expf(sGc[i] - sGc[j]) * acc[r][c] : 0.f; + } + } + lds_sync(); + if (is_w) { +#pragma unroll + for (int i = 0; i < kBT; ++i) rhs[i] = i < n ? sBe[i] * static_cast(sK[i * kLd + col]) : 0.f; + } else { +#pragma unroll + for (int i = 0; i < kBT; ++i) rhs[i] *= sBeta[i]; + } + + // (I + A) x = rhs down the rows, a column a thread: the first 128 threads w, the rest u + half_t* ocol = (is_w ? w : u) + vtile + col; +#pragma unroll + for (int i = 0; i < kBT; ++i) { + float s0 = 0.f, s1 = 0.f, s2 = 0.f, s3 = 0.f; + int m = 0; +#pragma unroll + for (; m + 4 <= i; m += 4) { + const float4 a = *reinterpret_cast(&sA[i * kBT + m]); + s0 = fmaf(a.x, rhs[m], s0); + s1 = fmaf(a.y, rhs[m + 1], s1); + s2 = fmaf(a.z, rhs[m + 2], s2); + s3 = fmaf(a.w, rhs[m + 3], s3); + } +#pragma unroll + for (; m < i; ++m) s0 = fmaf(sA[i * kBT + m], rhs[m], s0); + rhs[i] -= (s0 + s1) + (s2 + s3); + if (i < n) ocol[i * kD] = static_cast(rhs[i]); + } +} + +// vt[chunk][head][value][token] gets v_new = u - w H^T; hbuf[chunk][head][value][key] each chunk's start state (fp16). +extern "C" __global__ void __launch_bounds__(kThreads) +tf_gdn_h(const half_t* __restrict__ kt, const half_t* __restrict__ w, const half_t* __restrict__ u, + half_t* __restrict__ vt, const float* __restrict__ gc, float* __restrict__ state, half_t* __restrict__ hbuf, + int length, int key_heads, int value_heads) { + __shared__ alignas(16) half_t sH[kBV * kLd]; + __shared__ alignas(16) half_t sW[kBT * kLd]; + __shared__ alignas(16) half_t sKT[kD * kTLd]; + __shared__ alignas(16) half_t sVg[kBV * kTLd]; + __shared__ float sDecay[kBT]; + const int tid = threadIdx.x; + const int v0 = blockIdx.x * kBV; + const int head = blockIdx.y; + const int key_head = head / (value_heads / key_heads); + const int chunks = (length + kBT - 1) / kBT; + // the state: lane pairs share a (4 value rows, 4 keys) tile and both hold it + const int vq = tid >> 6, kg = (tid >> 1) & 31, half_id = tid & 1; + // the correction: a (4 tokens, 4 values) tile split over four lanes by key group + const int ks = tid & 3, ti = tid >> 4, vj = (tid >> 2) & 3; + + float h[4][4]; + float* st = state + (static_cast(head) * kD + v0 + 4 * vq) * kD + kg; +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) h[r][c] = st[r * kD + 32 * c]; + + Tile wt; + Quad ktp[4]; + half_t up[4]; + float g_next = 0.f, d_next = 0.f; + const int t_mine = 4 * ti + ks; + auto fetch_u = [&](int chunk) { + const int n = min(kBT, length - chunk * kBT); + const half_t* src = u + (static_cast(chunk) * value_heads + head) * kTile + t_mine * kD + v0 + vj; +#pragma unroll + for (int c = 0; c < 4; ++c) up[c] = t_mine < n ? src[4 * c] : static_cast(0); + }; + auto fetch_kt = [&](int chunk) { + const half_t* src = kt + (static_cast(chunk) * key_heads + key_head) * kD * kBT; +#pragma unroll + for (int j = 0; j < 4; ++j) ktp[j] = ld_quad(src + (tid + j * kThreads) * 8); + }; + auto fetch_gc = [&](int chunk) { + const int t0 = chunk * kBT; + const int n = min(kBT, length - t0); + g_next = gc[static_cast(t0 + n - 1) * value_heads + head]; + d_next = tid < n ? gc[static_cast(t0 + tid) * value_heads + head] : 0.f; + }; + auto fetch_w = [&](int chunk) { + wt.fetch(w + (static_cast(chunk) * value_heads + head) * kTile, min(kBT, length - chunk * kBT)); + }; + fetch_w(0); + fetch_kt(0); + fetch_u(0); + fetch_gc(0); + + for (int chunk = 0; chunk < chunks; ++chunk) { + const int n = min(kBT, length - chunk * kBT); + const float g_last = g_next; + // the start state: to shared memory for the correction, and out for o +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) + if ((r >> 1) == half_id) sH[(4 * vq + r) * kLd + kg + 32 * c] = static_cast(h[r][c]); + wt.store(sW); + if (tid < kBT) sDecay[tid] = tid < n ? __expf(g_last - d_next) : 0.f; + if (chunk + 1 < chunks) { + fetch_w(chunk + 1); + fetch_gc(chunk + 1); + } + lds_sync(); + + // the keys transposed for the update, the start state out +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = tid + j * kThreads; + *reinterpret_cast(&sKT[(idx >> 3) * kTLd + 8 * (idx & 7)]) = ktp[j]; + } + if (chunk + 1 < chunks) fetch_kt(chunk + 1); + { + const int row = tid >> 4, cg = tid & 15; + *reinterpret_cast( + &hbuf[((static_cast(chunk) * value_heads + head) * kD + v0 + row) * kD + 8 * cg]) = + ld_quad(&sH[row * kLd + 8 * cg]); + } + + // v_new[t][v] = u - sum_k w[t][k] H[v][k]: 4 x 4 tiles, the key groups split over four lanes + { + float acc[4][4] = {}; + tile_acc<4>(acc, sW + ti * 4 * kLd, kLd, sH + vj * kLd, 4 * kLd, ks, kD / 8, 4); +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) { + acc[r][c] += quad_xor1(acc[r][c]); + acc[r][c] += quad_xor2(acc[r][c]); + } +#pragma unroll + for (int c = 0; c < 4; ++c) { + const float mine = ks == 0 ? acc[0][c] : ks == 1 ? acc[1][c] : ks == 2 ? acc[2][c] : acc[3][c]; + const float vn = t_mine < n ? static_cast(up[c]) - mine : 0.f; + const int v = vj + 4 * c; + vt[((static_cast(chunk) * value_heads + head) * kD + v0 + v) * kBT + t_mine] = + static_cast(vn); + sVg[v * kTLd + t_mine] = static_cast(vn * sDecay[t_mine]); + } + } + if (chunk + 1 < chunks) fetch_u(chunk + 1); + lds_sync(); + + // H = exp(g_last) H + sum_t vg[t][v] kT[key][t]: the tokens split over a lane pair + { + float acc[4][4] = {}; + tile_acc<4>(acc, sVg + 4 * vq * kTLd, kTLd, sKT + kg * kTLd, 32 * kTLd, 4 * half_id, 4 * half_id + 4, 1); + const float decay = __expf(g_last); +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) h[r][c] = h[r][c] * decay + (acc[r][c] + quad_xor1(acc[r][c])); + } + } +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) + if ((r >> 1) == half_id) st[r * kD + 32 * c] = h[r][c]; +} + +// A block a (chunk, head): the scores once, then each half of the values (the next half's tiles fetched meanwhile). +extern "C" __global__ void __launch_bounds__(kThreads) +tf_gdn_o(const half_t* __restrict__ qh, const half_t* __restrict__ kh, const half_t* __restrict__ vt, + const half_t* __restrict__ hbuf, const float* __restrict__ gc, float* __restrict__ y, int length, + int key_heads, int value_heads) { + __shared__ alignas(16) half_t sQ[kBT * kLd]; + __shared__ alignas(16) half_t sK[kBT * kLd]; // the keys, then the start state's 64 value rows + __shared__ alignas(16) half_t sS[kBT * kTLd]; + __shared__ alignas(16) half_t sVT[kBT * kTLd]; + __shared__ float sGc[kBT]; + const int tid = threadIdx.x; + const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const int chunk = blockIdx.x; + const int head = blockIdx.y; + const int t0 = chunk * kBT; + const int n = min(kBT, length - t0); + const int key_head = head / (value_heads / key_heads); + const int ti = tid >> 4, tj = tid & 15; + + const half_t* hsrc = hbuf + (static_cast(chunk) * value_heads + head) * kD * kD; + const half_t* vsrc = vt + (static_cast(chunk) * value_heads + head) * kD * kBT; + Tile tq, tk, th; + Quad pv[2]; + auto fetch_half = [&](int half) { +#pragma unroll + for (int j = 0; j < 4; ++j) th.piece[j] = ld_quad(hsrc + half * 64 * kD + (tid + j * kThreads) * 8); +#pragma unroll + for (int j = 0; j < 2; ++j) pv[j] = ld_quad(vsrc + half * 64 * kBT + (tid + j * kThreads) * 8); + }; + const long long ktile = (static_cast(chunk) * key_heads + key_head) * kTile; + tq.fetch(qh + ktile, n); + tk.fetch(kh + ktile, n); + fetch_half(0); + if (tid < kBT) sGc[tid] = tid < n ? gc[static_cast(t0 + tid) * value_heads + head] : 0.f; + tq.store(sQ); + tk.store(sK); + lds_sync(); + + // the masked, decayed scores q_t.k_j: a 4 x 4 tile of rows 4 ti .. and columns tj + 16 c + { + const int nc = (8 * wave + 7) / 16 + 1; + float acc[4][4] = {}; + tile_acc_wave(acc, sQ + ti * 4 * kLd, kLd, sK + tj * kLd, 16 * kLd, nc); +#pragma unroll + for (int r = 0; r < 4; ++r) +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int i = ti * 4 + r, j = tj + 16 * c; + sS[i * kTLd + j] = static_cast(j <= i ? acc[r][c] * __expf(sGc[i] - sGc[j]) : 0.f); + } + } + lds_sync(); + + for (int half = 0; half < 2; ++half) { + // the start state over the keys (reusing the key tile) and the new values by token, then the next half's + th.store(sK); +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int idx = tid + j * kThreads; + *reinterpret_cast(&sVT[(idx >> 3) * kTLd + 8 * (idx & 7)]) = pv[j]; + } + if (half == 0) fetch_half(1); + lds_sync(); + + float inter[4][4] = {}; + float intra[4][4] = {}; + tile_acc<4>(inter, sQ + ti * 4 * kLd, kLd, sK + tj * kLd, 16 * kLd, 0, kD / 8, 1); + tile_acc<4>(intra, sS + ti * 4 * kTLd, kTLd, sVT + tj * kTLd, 16 * kTLd, 0, ti / 2 + 1, 1); +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int t = ti * 4 + r; + if (t >= n) continue; + const float e = __expf(sGc[t]); + float* row = y + (static_cast(t0 + t) * value_heads + head) * kD + half * 64 + tj; +#pragma unroll + for (int c = 0; c < 4; ++c) row[16 * c] = e * inter[r][c] + intra[r][c]; + } + if (half == 0) lds_sync(); + } +} 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..0dd72ed0d27 --- /dev/null +++ b/zig/src/hip/kernel_tests/gdn.zig @@ -0,0 +1,153 @@ +//! The DeltaNet recurrence, token-serial and chunked, against a float64 recurrence on random inputs. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; + +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; +} + +test "the serial and chunked DeltaNet stay 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(); + // `off` runs the token-serial kernel, `on` the chunked one for these lengths + for ([_]*const @import("../launches.zig").Launcher{ &t.off, &t.on }) |l| { + try state.upload(0, std.mem.sliceAsBytes(in.state)); + try y.fill8(0); + t.arena.reset(); + try t.ops(l).gatedDelta(rig.at(q), rig.at(k), rig.at(v), rig.at(gate), rig.at(beta), rig.at(state), rig.at(y), sh.length, sh.key_heads, sh.value_heads, d, d, null); + 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); + } + } +} 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..6afc5c6afd3 --- /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 and the chunked DeltaNet 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, .chunked = 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..513a88c1f5f --- /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, gdn_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..dcf6426df65 --- /dev/null +++ b/zig/src/hip/launches.zig @@ -0,0 +1,314 @@ +//! 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 GdnScratch = recurrence.GdnScratch; +pub const gdnScratch = recurrence.gdnScratch; + +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 + gdn_chunked: [5]Function, // prep, kt, wy, h, o + 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, + /// The DeltaNet prefill runs chunked (off keeps the one-token recurrence). + chunked: 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, chunked: 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.chunked = choices.chunked; + 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") }; + const gp = l.mods[@backingInt(kernels.Group.gdn_prefill)]; + l.gdn_chunked = .{ try gp.function("tf_gdn_prep"), try gp.function("tf_gdn_kt"), try gp.function("tf_gdn_wy"), try gp.function("tf_gdn_h"), try gp.function("tf_gdn_o") }; + 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 gdnChunked = recurrence.gdnChunked; + 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..86e5369a16d --- /dev/null +++ b/zig/src/hip/launches/recurrence.zig @@ -0,0 +1,167 @@ +//! DeltaNet launches: gate, serial and chunked recurrence, and the gated norm. + +const std = @import("std"); +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; + +/// The chunked DeltaNet's chunk, in rows. +pub const gdn_chunk = 64; + +/// Byte sizes of the chunked DeltaNet's scratch, rows padded to whole chunks. +pub const GdnScratch = struct { qk: usize, gc: usize, wu: usize, h: usize, total: usize }; + +pub fn gdnScratch(length: usize, key_heads: usize, value_heads: usize) GdnScratch { + const chunks = cdiv(length, gdn_chunk); + const rows = chunks * gdn_chunk; + const qk = std.mem.alignForward(usize, rows * key_heads * 128 * 2, 256); + const gc = std.mem.alignForward(usize, length * value_heads * 4, 256); + const wu = std.mem.alignForward(usize, rows * value_heads * 128 * 2, 256); + const h = chunks * value_heads * 128 * 128 * 2; + return .{ .qk = qk, .gc = gc, .wu = wu, .h = h, .total = 3 * qk + gc + 4 * wu + h }; +} + +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); + } +} + +/// The chunked DeltaNet prefill of `length` rows (dk = dv = 128, batch 1), `scratch` of `gdnScratch` bytes. +pub fn gdnChunked(l: *const Launcher, q: CF, k: CF, v: CF, gate: CF, beta: CF, state: F, y: F, length: usize, key_heads: usize, value_heads: usize, scratch: u64, s: S) Error!void { + if (length < 1 or key_heads < 1 or @rem(value_heads, key_heads) != 0) return invalid("gdn chunked"); + const sc = gdnScratch(length, key_heads, value_heads); + const qh = scratch; + const kh = qh + sc.qk; + const kt = kh + sc.qk; + const vh = kt + sc.qk; + const gc = vh + sc.wu; + const w = gc + sc.gc; + const u = w + sc.wu; + const vt = u + sc.wu; + const hb = vt + sc.wu; + const chunks = cdiv(length, gdn_chunk); + const len: c_int = @intCast(length); + const hk: c_int = @intCast(key_heads); + const hv: c_int = @intCast(value_heads); + var a: Args = .{}; + try a.add(ad(q)); + try a.add(ad(k)); + try a.add(ad(v)); + try a.add(qh); + try a.add(kh); + try a.add(vh); + try a.add(len); + try a.add(hk); + try a.add(hv); + try l.go(l.gdn_chunked[0], dim(cdiv(length * (key_heads + value_heads) * 32, 256), 1, 1), dim(256, 1, 1), 0, s, &a); + var t: Args = .{}; + try t.add(kh); + try t.add(kt); + try t.add(len); + try t.add(hk); + try l.go(l.gdn_chunked[1], dim(chunks, key_heads, 1), dim(256, 1, 1), 0, s, &t); + var b: Args = .{}; + try b.add(kh); + try b.add(vh); + try b.add(ad(beta)); + try b.add(ad(gate)); + try b.add(gc); + try b.add(w); + try b.add(u); + try b.add(len); + try b.add(hk); + try b.add(hv); + try l.go(l.gdn_chunked[2], dim(chunks, value_heads, 1), dim(256, 1, 1), 0, s, &b); + var c: Args = .{}; + try c.add(kt); + try c.add(w); + try c.add(u); + try c.add(vt); + try c.add(gc); + try c.add(ad(state)); + try c.add(hb); + try c.add(len); + try c.add(hk); + try c.add(hv); + try l.go(l.gdn_chunked[3], dim(8, value_heads, 1), dim(256, 1, 1), 0, s, &c); + var d: Args = .{}; + try d.add(qh); + try d.add(kh); + try d.add(vt); + try d.add(hb); + try d.add(gc); + try d.add(ad(y)); + try d.add(len); + try d.add(hk); + try d.add(hv); + try l.go(l.gdn_chunked[4], dim(chunks, value_heads, 1), dim(256, 1, 1), 0, s, &d); +} + +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..da9dbedb110 --- /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, router and recurrence 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..5971aafb59e --- /dev/null +++ b/zig/src/hip/ops/recurrence.zig @@ -0,0 +1,59 @@ +//! The linear attention: the conv, the gates and the DeltaNet recurrence. + +const t = @import("types.zig"); +const launches = @import("../launches.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; + +/// Rows from which the DeltaNet prefill runs chunked, and the rows of one chunked segment (a multiple of the chunk). +const gdn_min_rows = 64; +const gdn_segment = 4096; + +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 chunked recurrence in segments of `gdn_segment` rows, whose scratch the arena hands back after each. +fn gatedDeltaChunked(o: Ops, z: *const launches.Launcher, q: u64, k: u64, v: u64, gate: u64, beta: u64, state: u64, y: u64, length: usize, key_heads: usize, value_heads: usize) Error!void { + var start: usize = 0; + while (start < length) : (start += gdn_segment) { + const rows = @min(gdn_segment, length - start); + const mark = o.arena.mark(); + defer o.arena.release(mark); + const scratch = try o.arena.take(launches.gdnScratch(rows, key_heads, value_heads).total); + const qk = start * key_heads * 128 * 4; + const vy = start * value_heads * 128 * 4; + const gb = start * value_heads * 4; + try z.gdnChunked(f(q + qk), f(k + qk), f(v + vy), f(gate + gb), f(beta + gb), f(state), f(y + vy), rows, key_heads, value_heads, scratch, o.stream); + } +} + +/// The DeltaNet recurrence, state in place; a prefill of `gdn_min_rows` rows or more runs chunked unless reference. +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 { + if (states == null and (length >= gdn_min_rows or o.prefill) and dk == 128 and dv == 128 and value_heads % key_heads == 0) { + if (o.l.chunked) return gatedDeltaChunked(o, o.l, q, k, v, gate, beta, state, y, length, key_heads, value_heads); + } + 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..121e6e2a0ef --- /dev/null +++ b/zig/tests/hip_kernels.md @@ -0,0 +1,24 @@ +# 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`. From 67d94795185f60f7eaaf173a62b367dddb28f17c Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:52:06 +0200 Subject: [PATCH 02/52] feat(core): weight formats behind one interface, MLX affine 2- to 8-bit and dense, with tensor-parallel cuts core/quant reads a checkpoint's MLX affine projections (bits 2, 3, 4, 5, 6 and 8, any group) or dense ones, detects the format from the tensors, cuts a projection by output rows, by a rank's whole input groups or into its two K halves, splits an expert stack across ranks, and hands a backend the upload. Every cut keeps the codes and group tables byte for byte: a test quantizes with affine4_host and checks each cut dequantizes to the same bits as the rows and columns it covers, and it fails when a cut is off by one group. --- zig/src/core/quant/convert.zig | 68 ++++++ zig/src/core/quant/dense.zig | 107 ++++++++++ zig/src/core/quant/exact_test.zig | 70 +++++++ zig/src/core/quant/mlx.zig | 330 ++++++++++++++++++++++++++++++ zig/src/core/quant/quant.zig | 200 ++++++++++++++++++ zig/src/core/quant/slice.zig | 97 +++++++++ zig/src/core/quant/types.zig | 58 ++++++ zig/src/core/root.zig | 2 + 8 files changed, 932 insertions(+) create mode 100644 zig/src/core/quant/convert.zig create mode 100644 zig/src/core/quant/dense.zig create mode 100644 zig/src/core/quant/exact_test.zig create mode 100644 zig/src/core/quant/mlx.zig create mode 100644 zig/src/core/quant/quant.zig create mode 100644 zig/src/core/quant/slice.zig create mode 100644 zig/src/core/quant/types.zig diff --git a/zig/src/core/quant/convert.zig b/zig/src/core/quant/convert.zig new file mode 100644 index 00000000000..cc38b2905bb --- /dev/null +++ b/zig/src/core/quant/convert.zig @@ -0,0 +1,68 @@ +//! Host-side element conversions the Python loader does with torch: `.float()` and bf16 rounding. + +const std = @import("std"); +const st = @import("../safetensors.zig"); + +const Tensor = st.Tensor; +const DType = st.DType; + +pub const Error = error{ UnexpectedTensor, UnsupportedQuantization } || std.mem.Allocator.Error; + +/// One element as fp32 (bf16 and fp16 widen exactly). +pub fn load(dtype: DType, bytes: []const u8, i: usize) f32 { + return switch (dtype) { + .f32 => @bitCast(std.mem.readInt(u32, bytes[4 * i ..][0..4], .little)), + .bf16 => @bitCast(@as(u32, std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)) << 16), + .f16 => @floatCast(@as(f16, @bitCast(std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)))), + else => unreachable, + }; +} + +pub fn isFloat(dtype: DType) bool { + return switch (dtype) { + .f16, .bf16, .f32, .f64 => true, + else => false, + }; +} + +/// The group-table dtypes the kernels read as stored. +pub fn tableDtype(dtype: DType) bool { + return dtype == .f32 or dtype == .bf16 or dtype == .f16; +} + +/// torch's fp32 -> bf16: round to nearest even, NaN stays a NaN. +pub fn bf16(x: f32) u16 { + const bits: u32 = @bitCast(x); + if (std.math.isNan(x)) return @intCast((bits >> 16) | 0x40); + return @intCast((bits + 0x7FFF + ((bits >> 16) & 1)) >> 16); +} + +/// Writes `src` as little-endian fp32 into `dst` (4 bytes an element). +pub fn widenInto(dst: []u8, src: Tensor) Error!void { + const n = src.numel(); + if (dst.len != n * 4) return error.UnexpectedTensor; + switch (src.dtype) { + .f32, .bf16, .f16 => for (0..n) |i| std.mem.writeInt(u32, dst[4 * i ..][0..4], @bitCast(load(src.dtype, src.bytes, i)), .little), + .f64 => for (0..n) |i| { + const v: f64 = @bitCast(std.mem.readInt(u64, src.bytes[8 * i ..][0..8], .little)); + std.mem.writeInt(u32, dst[4 * i ..][0..4], @bitCast(@as(f32, @floatCast(v))), .little); + }, + else => return error.UnexpectedTensor, + } +} + +/// `.float().contiguous()` of a floating tensor into memory of `a` (an fp32 tensor is shared, not copied). +pub fn float32(a: std.mem.Allocator, src: Tensor) Error!Tensor { + if (src.dtype == .f32) return src; + const out = try a.alloc(u8, src.numel() * 4); + try widenInto(out, src); + return .{ .dtype = .f32, .rank = src.rank, .shape = src.shape, .bytes = out }; +} + +test "bf16 rounds to nearest even" { + try std.testing.expectEqual(@as(u16, 0x3F80), bf16(1.0)); + try std.testing.expectEqual(@as(u16, 0x3F80), bf16(@bitCast(@as(u32, 0x3F807FFF)))); + try std.testing.expectEqual(@as(u16, 0x3F82), bf16(@bitCast(@as(u32, 0x3F818000)))); + try std.testing.expectEqual(@as(u16, 0x3F80), bf16(@bitCast(@as(u32, 0x3F808000)))); + try std.testing.expect(std.math.isNan(@as(f32, @bitCast(@as(u32, bf16(std.math.nan(f32))) << 16)))); +} diff --git a/zig/src/core/quant/dense.zig b/zig/src/core/quant/dense.zig new file mode 100644 index 00000000000..a36f114e6f4 --- /dev/null +++ b/zig/src/core/quant/dense.zig @@ -0,0 +1,107 @@ +//! Weights kept in float: fp32 [N, K], the unquantized projections a conversion leaves (an MTP head's fc). + +const std = @import("std"); +const types = @import("types.zig"); +const slice = @import("slice.zig"); +const convert = @import("convert.zig"); + +const Tensor = types.Tensor; +const Allocator = std.mem.Allocator; +const join = types.join; + +pub const id: types.Format = .dense; +pub const decoder: types.Decoder = .dense; + +/// A float weight is not named by the config: nothing here declares it. +pub const Config = void; + +pub fn detect(a: Allocator, src: types.Sources) Allocator.Error!?Config { + _ = a; + _ = src; + return null; +} + +pub const Host = struct { weight: Tensor }; + +/// Whether `key` holds a float matrix with no table of scales beside it. +pub fn matches(t: anytype, key: []const u8) bool { + var buf: [256]u8 = undefined; + const w = t.get(join(&buf, &.{ key, ".weight" })) catch return false; + return convert.isFloat(w.dtype) and w.rank == 2 and !t.has(join(&buf, &.{ key, ".scales" })); +} + +/// The float weight widened to fp32. +pub fn read(a: Allocator, t: anytype, key: []const u8) !Host { + var buf: [256]u8 = undefined; + return .{ .weight = try convert.float32(a, try t.get(join(&buf, &.{ key, ".weight" }))) }; +} + +pub fn rows(h: Host) usize { + return h.weight.shape[0]; +} + +pub fn bytes(h: Host) usize { + return h.weight.bytes.len; +} + +/// Both halves along K, copied. +pub fn halves(a: Allocator, p: Host) ![2]Host { + const half = p.weight.shape[1] / 2; + return .{ + .{ .weight = try slice.takeCols(a, p.weight, 0, half) }, + .{ .weight = try slice.takeCols(a, p.weight, half, p.weight.shape[1]) }, + }; +} + +pub fn sliceRows(a: Allocator, p: Host, spans: []const slice.Span) slice.Error!Host { + return .{ .weight = try slice.takeRows(a, p.weight, spans) }; +} + +pub fn sliceCols(a: Allocator, p: Host, r: slice.Rank, what: []const u8) slice.Error!Host { + const width = try slice.even(p.weight.shape[1], r.world, what); + return .{ .weight = try slice.takeCols(a, p.weight, r.rank * width, (r.rank + 1) * width) }; +} + +pub fn sliceStack(a: Allocator, p: Host, r: slice.Rank, part: usize) slice.Error!Host { + return .{ .weight = try slice.takeExperts(a, p.weight, r, part) }; +} + +pub const Device = struct { weight: types.Buf }; + +pub fn upload(u: types.Uploader, h: Host) !Device { + return .{ .weight = try u.tensor(h.weight) }; +} + +/// What the kernels read: the fp32 weight's address. +pub const Matrix = struct { weight: u64 }; + +pub const View = struct { n: u32, k: u32, matrix: Matrix }; + +pub fn view(d: Device, stacked: bool) error{UnsupportedTables}!View { + const lead: usize = @intFromBool(stacked); + return .{ .n = @intCast(d.weight.dim(lead)), .k = @intCast(d.weight.dim(lead + 1)), .matrix = .{ .weight = d.weight.ptr } }; +} + +pub fn elements(h: Host) usize { + return h.weight.numel(); +} + +/// The weight as fp64, row by row. +pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void { + if (out.len != h.weight.numel()) return error.UnexpectedTensor; + for (out, 0..) |*o, i| o.* = convert.load(.f32, h.weight.bytes, i); +} + +test "a float weight halves along K and cuts its rows" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var data = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + const h: Host = .{ .weight = .{ .dtype = .f32, .rank = 2, .shape = .{ 2, 4, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&data) } }; + const pair = try halves(a, h); + try std.testing.expectEqualSlices(f32, &.{ 3, 4, 7, 8 }, @alignCast(std.mem.bytesAsSlice(f32, pair[1].weight.bytes))); + const low = try sliceRows(a, h, &.{.{ .from = 1, .to = 2 }}); + var out: [4]f64 = undefined; + try reference(low, &out); + try std.testing.expectEqualSlices(f64, &.{ 5, 6, 7, 8 }, &out); +} diff --git a/zig/src/core/quant/exact_test.zig b/zig/src/core/quant/exact_test.zig new file mode 100644 index 00000000000..1dd571b2d0a --- /dev/null +++ b/zig/src/core/quant/exact_test.zig @@ -0,0 +1,70 @@ +//! Every cut of an MLX affine projection dequantizes to the same bits as the uncut rows and columns it covers. +const std = @import("std"); +const mlx = @import("mlx.zig"); +const slice = @import("slice.zig"); +const ref = @import("../affine4_host.zig"); +const Tensor = @import("types.zig").Tensor; + +const n = 8; +const k = 512; +const groups = k / ref.group; + +fn tensor(dtype: anytype, rows: usize, cols: usize, bytes: []u8) Tensor { + return .{ .dtype = dtype, .rank = 2, .shape = .{ rows, cols, 1, 1, 1 }, .bytes = bytes }; +} + +/// The cut's values, row-major, by the reference dequantizer. +fn values(a: std.mem.Allocator, h: mlx.Host) ![]f32 { + const out = try a.alloc(f32, h.words.shape[0] * h.scales.shape[1] * h.group); + ref.dequantize(try aligned(a, u32, h.words.bytes), try aligned(a, u16, h.scales.bytes), try aligned(a, u16, h.biases.bytes), out); + return out; +} + +/// A cut's bytes as typed elements (a cut is a byte slice of any alignment). +fn aligned(a: std.mem.Allocator, comptime T: type, bytes: []const u8) ![]T { + const out = try a.alloc(T, bytes.len / @sizeOf(T)); + @memcpy(std.mem.sliceAsBytes(out), bytes); + return out; +} + +fn expectCut(full: []const f32, cut: []const f32, rows: []const usize, col0: usize, cols: usize) !void { + try std.testing.expectEqual(rows.len * cols, cut.len); + for (rows, 0..) |row, r| for (0..cols) |c| { + const want: u32 = @bitCast(full[row * k + col0 + c]); + const got: u32 = @bitCast(cut[r * cols + c]); + try std.testing.expectEqual(want, got); + }; +} + +test "row spans, rank column groups and K halves keep every dequantized bit" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x7f0d); + const x = try a.alloc(f32, n * k); + for (x) |*v| v.* = prng.random().floatNorm(f32) * 0.05; + const words = try a.alloc(u32, n * k / 8); + const scales = try a.alloc(u16, n * groups); + const biases = try a.alloc(u16, n * groups); + ref.quantize(x, words, scales, biases); + const h: mlx.Host = .{ + .words = tensor(.i32, n, k / 8, std.mem.sliceAsBytes(words)), + .scales = tensor(.bf16, n, groups, std.mem.sliceAsBytes(scales)), + .biases = tensor(.bf16, n, groups, std.mem.sliceAsBytes(biases)), + .bits = 4, + .group = ref.group, + }; + const full = try values(a, h); + const all = [_]usize{ 0, 1, 2, 3, 4, 5, 6, 7 }; + + const spans = [_]slice.Span{ .{ .from = 1, .to = 3 }, .{ .from = 5, .to = 8 } }; + try expectCut(full, try values(a, try mlx.sliceRows(a, h, &spans)), &.{ 1, 2, 5, 6, 7 }, 0, k); + + for ([_]usize{ 1, 2, 4, 8 }) |world| for (0..world) |rank| { + const cut = try mlx.sliceCols(a, h, .{ .rank = rank, .world = world }, "exact"); + try expectCut(full, try values(a, cut), &all, rank * k / world, k / world); + }; + + const pair = try mlx.halves(a, h); + for (pair, 0..) |half, i| try expectCut(full, try values(a, half), &all, i * k / 2, k / 2); +} diff --git a/zig/src/core/quant/mlx.zig b/zig/src/core/quant/mlx.zig new file mode 100644 index 00000000000..f2334eb01a6 --- /dev/null +++ b/zig/src/core/quant/mlx.zig @@ -0,0 +1,330 @@ +//! MLX affine weights: i32 words of `bits`-wide codes, a scale and bias a group of K; host and device side. + +const std = @import("std"); +const types = @import("types.zig"); +const slice = @import("slice.zig"); +const convert = @import("convert.zig"); + +const Tensor = types.Tensor; +const Allocator = std.mem.Allocator; +const join = types.join; +const refuse = types.refuse; + +pub const id: types.Format = .mlx; +pub const decoder: types.Decoder = .mlx; + +pub const bit_widths = [_]u8{ 2, 3, 4, 5, 6, 8 }; + +/// One affine width: groups of `group` weights share a scale and a bias, `bits` per weight. +pub const Width = struct { bits: u8, group: u16 }; + +/// The config's `quantization` table: the global width and the per-tensor overrides (mixed-width conversions). +pub const Config = struct { + global: Width, + /// A per-tensor entry; `null` marks one this format refuses, which fails when the tensor is looked up. + overrides: std.StringHashMapUnmanaged(?Width) = .empty, + + /// The tensor's own width when the table names it as an object, else the global one. + pub fn width(q: Config, key: []const u8) error{UnsupportedQuantization}!Width { + if (q.overrides.get(key)) |w| return w orelse error.UnsupportedQuantization; + return q.global; + } +}; + +/// The affine width an object of the config names, or null when it is not one the kernels run. +fn affineWidth(o: std.json.ObjectMap) ?Width { + const bits = intOrNull(o.get("bits")) orelse return null; + const group = intOrNull(o.get("group_size")) orelse return null; + if (o.get("mode")) |m| if (m != .string or !std.mem.eql(u8, m.string, "affine")) return null; + if (std.mem.indexOfScalar(i64, &.{ 2, 3, 4, 5, 6, 8 }, bits) == null) return null; + if (std.mem.indexOfScalar(i64, &.{ 32, 64, 128 }, group) == null) return null; + return .{ .bits = @intCast(bits), .group = @intCast(group) }; +} + +fn intOrNull(v: ?std.json.Value) ?i64 { + const value = v orelse return null; + return switch (value) { + .integer => |i| i, + .float => |f| if (f == @floor(f) and @abs(f) < 1e15) @as(i64, @intFromFloat(f)) else null, + else => null, + }; +} + +/// The checkpoint's `quantization` object when it is MLX affine (`mode` absent or "affine"), else null. +pub fn detect(a: Allocator, src: types.Sources) Allocator.Error!?Config { + const obj = src.quantization; + var q: Config = .{ .global = affineWidth(obj) orelse return null }; + var it = obj.iterator(); + while (it.next()) |kv| if (kv.value_ptr.* == .object) try q.overrides.put(a, kv.key_ptr.*, affineWidth(kv.value_ptr.object)); + return q; +} + +/// An affine projection as stored: i32 words [N, K * bits / 32], tables [N, K / group]; a stack leads with E + 1. +pub const Host = struct { words: Tensor, scales: Tensor, biases: Tensor, bits: u8, group: u16 }; + +/// Whether `key` holds an MLX affine projection (a table of scales beside its words). +pub fn matches(t: anytype, key: []const u8) bool { + var buf: [256]u8 = undefined; + return t.has(join(&buf, &.{ key, ".scales" })); +} + +/// The fp32 scale and bias tables when the pair is not one of the dtypes the kernels read as stored. +pub fn tables(a: Allocator, scale: Tensor, bias: Tensor) convert.Error![2]Tensor { + if (scale.dtype == bias.dtype and convert.tableDtype(scale.dtype)) return .{ scale, bias }; + return .{ try convert.float32(a, scale), try convert.float32(a, bias) }; +} + +/// `_packed`: an affine projection as stored (group tables widened to fp32 only when not fp32, bf16 or fp16 pairs). +pub fn read(a: Allocator, t: anytype, key: []const u8) !Host { + var buf: [256]u8 = undefined; + var other: [256]u8 = undefined; + var words = try t.get(join(&buf, &.{ key, ".weight" })); + const w = try t.width(key); + if ((words.dtype != .u32 and words.dtype != .i32) or words.rank != 2) return refuse(key, "weight is not packed int32 words"); + words.dtype = .i32; + const scale = try t.get(join(&buf, &.{ key, ".scales" })); + const bias = try t.get(join(&other, &.{ key, ".biases" })); + if (scale.rank != 2 or bias.rank != 2 or !std.mem.eql(usize, scale.shape[0..2], bias.shape[0..2])) return refuse(key, "scale and bias must share shape (N, K / group)"); + const k = scale.shape[1] * w.group; + if (words.shape[1] != k * w.bits / 32 or words.shape[0] != scale.shape[0]) return refuse(key, "packed shape does not match K, bits and group"); + const pair = try tables(a, scale, bias); + return .{ .words = words, .scales = pair[0], .biases = pair[1], .bits = w.bits, .group = w.group }; +} + +/// Output rows N of a projection. +pub fn rows(h: Host) usize { + return h.words.shape[0]; +} + +/// The bytes of the three tensors. +pub fn bytes(h: Host) usize { + return h.words.bytes.len + h.scales.bytes.len + h.biases.bytes.len; +} + +/// `_halves`: a fused [embedding | hidden] projection split in two along K, words and group tables alike. +pub fn halves(a: Allocator, p: Host) ![2]Host { + const groups = p.scales.shape[1]; + const half = groups * p.group / 2; + if (groups % 2 != 0 or half * p.bits % 32 != 0) return refuse("fc", "does not split on a word boundary"); + const word = p.words.shape[1] / 2; + const tab = groups / 2; + var out: [2]Host = undefined; + for (&out, 0..) |*o, i| { + const w = if (i == 0) [2]usize{ 0, word } else [2]usize{ word, p.words.shape[1] }; + const g = if (i == 0) [2]usize{ 0, tab } else [2]usize{ tab, groups }; + o.* = .{ + .words = try slice.takeCols(a, p.words, w[0], w[1]), + .scales = try slice.takeCols(a, p.scales, g[0], g[1]), + .biases = try slice.takeCols(a, p.biases, g[0], g[1]), + .bits = p.bits, + .group = p.group, + }; + } + return out; +} + +/// `_rows`: output rows `spans` of a projection, the share of a column-split one. +pub fn sliceRows(a: Allocator, p: Host, spans: []const slice.Span) slice.Error!Host { + return .{ .words = try slice.takeRows(a, p.words, spans), .scales = try slice.takeRows(a, p.scales, spans), .biases = try slice.takeRows(a, p.biases, spans), .bits = p.bits, .group = p.group }; +} + +/// `_cols`: one rank's whole input groups of a row-split projection, whose fp32 outputs the ranks sum. +pub fn sliceCols(a: Allocator, p: Host, r: slice.Rank, what: []const u8) slice.Error!Host { + const groups = try slice.even(p.scales.shape[1], r.world, what); + const words = groups * p.group * p.bits / 32; + return .{ + .words = try slice.takeCols(a, p.words, r.rank * words, (r.rank + 1) * words), + .scales = try slice.takeCols(a, p.scales, r.rank * groups, (r.rank + 1) * groups), + .biases = try slice.takeCols(a, p.biases, r.rank * groups, (r.rank + 1) * groups), + .bits = p.bits, + .group = p.group, + }; +} + +/// A stack of E + 1 experts cut to a rank's `part` of them (the shared one last, kept on rank 0). +pub fn sliceStack(a: Allocator, p: Host, r: slice.Rank, part: usize) slice.Error!Host { + return .{ .words = try slice.takeExperts(a, p.words, r, part), .scales = try slice.takeExperts(a, p.scales, r, part), .biases = try slice.takeExperts(a, p.biases, r, part), .bits = p.bits, .group = p.group }; +} + +/// An uploaded projection (or stack of them): the same tensors on the device. +pub const Device = struct { words: types.Buf, scales: types.Buf, biases: types.Buf, bits: u8, group: u16 }; + +/// The checkpoint's words and tables on the device as stored: this format keeps its layout. +pub fn upload(u: types.Uploader, h: Host) !Device { + return .{ .words = try u.tensor(h.words), .scales = try u.tensor(h.scales), .biases = try u.tensor(h.biases), .bits = h.bits, .group = h.group }; +} + +/// What the kernels read of an MLX projection: the three addresses, the tables' type and the width. +pub const Matrix = struct { words: u64, scale: u64, bias: u64, tables: types.Tables, bits: u8, group: u16 }; + +pub const View = struct { n: u32, k: u32, matrix: Matrix }; + +fn tableKind(dtype: types.DType) error{UnsupportedTables}!types.Tables { + return switch (dtype) { + .f32 => .f32, + .f16 => .f16, + .bf16 => .bf16, + else => error.UnsupportedTables, + }; +} + +/// The projection's (N, K) and addresses; a stack (E + 1, N, ...) reads as one expert's shape at the stack's addresses. +pub fn view(d: Device, stacked: bool) error{UnsupportedTables}!View { + const lead: usize = @intFromBool(stacked); + const n = d.words.dim(lead); + const k = d.words.dim(lead + 1) * 32 / d.bits; + const matrix: Matrix = .{ .words = d.words.ptr, .scale = d.scales.ptr, .bias = d.biases.ptr, .tables = try tableKind(d.scales.dtype), .bits = d.bits, .group = d.group }; + return .{ .n = @intCast(n), .k = @intCast(k), .matrix = matrix }; +} + +fn table64(dtype: types.DType, data: []const u8, i: usize) f64 { + return @as(f64, convert.load(dtype, data, i)); +} + +/// Weights of a projection: its rows (a stack's leading dimensions folded) by K. +pub fn elements(h: Host) usize { + var n_rows: usize = 1; + for (h.words.shape[0 .. h.words.rank - 1]) |d| n_rows *= d; + return n_rows * h.scales.shape[h.scales.rank - 1] * h.group; +} + +/// fp64 dequantization of every row of `h` (leading dimensions folded), scale * code + bias, into `out` [rows, K]. +pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void { + const rank = h.words.rank; + var n_rows: usize = 1; + for (h.words.shape[0 .. rank - 1]) |d| n_rows *= d; + const groups = h.scales.shape[h.scales.rank - 1]; + const k = groups * h.group; + const words_row = h.words.shape[rank - 1]; + if (out.len != n_rows * k or words_row * 32 != k * h.bits) return error.UnexpectedTensor; + const mask: u64 = (@as(u64, 1) << @intCast(h.bits)) - 1; + for (0..n_rows) |r| for (0..k) |c| { + const bit = c * h.bits; + const at = r * words_row + (bit >> 5); + const lo: u64 = std.mem.readInt(u32, h.words.bytes[4 * at ..][0..4], .little); + const hi: u64 = if ((bit & 31) + h.bits > 32) std.mem.readInt(u32, h.words.bytes[4 * (at + 1) ..][0..4], .little) else 0; + const code: f64 = @floatFromInt(((lo | hi << 32) >> @intCast(bit & 31)) & mask); + const g = r * groups + c / h.group; + out[r * k + c] = code * table64(h.scales.dtype, h.scales.bytes, g) + table64(h.biases.dtype, h.biases.bytes, g); + }; +} + +/// MLX affine words and tables as fp32 [R, K] the way torch computes them (product rounded, then sum), widths 2, 4, 8. +pub fn dequant(a: Allocator, words: Tensor, scale: Tensor, bias: Tensor, group: usize) convert.Error![]f32 { + if (words.rank != 2 or scale.rank != 2 or bias.rank != 2 or !std.mem.eql(usize, scale.shape[0..2], bias.shape[0..2])) return error.UnexpectedTensor; + if (words.dtype != .u32 and words.dtype != .i32) return error.UnexpectedTensor; + if (!convert.isFloat(scale.dtype) or scale.dtype == .f64 or !convert.isFloat(bias.dtype) or bias.dtype == .f64) return error.UnexpectedTensor; + const n_rows = words.shape[0]; + const k = scale.shape[1] * group; + if (k == 0 or 32 * words.shape[1] / k == 0) return error.UnexpectedTensor; + const bits = 32 * words.shape[1] / k; + if (bits != 2 and bits != 4 and bits != 8) return error.UnsupportedQuantization; + const per = 32 / bits; + if (words.shape[1] * per != k or scale.shape[0] != n_rows) return error.UnexpectedTensor; + const out = try a.alloc(f32, n_rows * k); + const mask: u32 = (@as(u32, 1) << @intCast(bits)) - 1; + for (0..n_rows) |r| for (0..k) |c| { + const word = std.mem.readInt(u32, words.bytes[4 * (r * words.shape[1] + c / per) ..][0..4], .little); + const code: f32 = @floatFromInt((word >> @intCast(bits * (c % per))) & mask); + const g = r * scale.shape[1] + c / group; + const s = convert.load(scale.dtype, scale.bytes, g); + const b = convert.load(bias.dtype, bias.bytes, g); + // torch multiplies, then adds: two roundings + const prod = code * s; + out[r * k + c] = prod + b; + }; + return out; +} + +fn hostOf(words: []const u32, scales: []const u16, biases: []const u16, rows_n: usize, bits: u8, group: u16) Host { + const groups = scales.len / rows_n; + return .{ + .words = .{ .dtype = .i32, .rank = 2, .shape = .{ rows_n, words.len / rows_n, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(words) }, + .scales = .{ .dtype = .bf16, .rank = 2, .shape = .{ rows_n, groups, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(scales) }, + .biases = .{ .dtype = .bf16, .rank = 2, .shape = .{ rows_n, groups, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(biases) }, + .bits = bits, + .group = group, + }; +} + +test "the reference unpacks low code first, across words for 3 bits" { + var four = [_]u32{0x76543210}; + var scale = [_]u16{0x4000}; // bf16 2.0 + var bias = [_]u16{0xBF80}; // bf16 -1.0 + var out4: [8]f64 = undefined; + try reference(hostOf(&four, &scale, &bias, 1, 4, 8), &out4); + try std.testing.expectEqualSlices(f64, &.{ -1, 1, 3, 5, 7, 9, 11, 13 }, &out4); + // 32 codes of 3 bits: code i is i % 8, packed little-endian over three words + var three: [3]u32 = @splat(0); + for (0..32) |i| { + const bit = i * 3; + const v: u64 = (i % 8) << @intCast(bit & 31); + three[bit >> 5] |= @truncate(v); + if ((bit & 31) + 3 > 32) three[(bit >> 5) + 1] |= @truncate(v >> 32); + } + var scale3 = [_]u16{0x3F80}; // 1.0 + var bias3 = [_]u16{0x0000}; + var out3: [32]f64 = undefined; + try reference(hostOf(&three, &scale3, &bias3, 1, 3, 32), &out3); + for (out3, 0..) |v, i| try std.testing.expectEqual(@as(f64, @floatFromInt(i % 8)), v); +} + +test "dequant unpacks 4-bit words low nibble first" { + var words = [_]u32{0x76543210}; + var scale = [_]u16{0x4000}; + var bias = [_]u16{0xBF80}; + const h = hostOf(&words, &scale, &bias, 1, 4, 8); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const out = try dequant(arena.allocator(), h.words, h.scales, h.biases, 8); + try std.testing.expectEqualSlices(f32, &.{ -1, 1, 3, 5, 7, 9, 11, 13 }, out); +} + +test "a projection splits its words and group tables on the same boundary" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var words: [2 * 4]u32 = undefined; + for (&words, 0..) |*w, i| w.* = @intCast(i); + var scales: [2 * 2]u16 = .{ 10, 11, 12, 13 }; + const p = hostOf(&words, &scales, &scales, 2, 4, 32); + const pair = try halves(arena.allocator(), p); + try std.testing.expectEqual(@as(usize, 2), pair[0].words.shape[1]); + try std.testing.expectEqual(@as(usize, 1), pair[1].scales.shape[1]); + try std.testing.expectEqualSlices(u32, &.{ 2, 3, 6, 7 }, @alignCast(std.mem.bytesAsSlice(u32, pair[1].words.bytes))); + try std.testing.expectEqualSlices(u16, &.{ 11, 13 }, @alignCast(std.mem.bytesAsSlice(u16, pair[1].scales.bytes))); +} + +test "a column split keeps whole groups and a row split its own rows" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var words: [4 * 4]u32 = undefined; + for (&words, 0..) |*w, i| w.* = @intCast(i); + var scales: [4 * 2]u16 = .{ 0, 1, 2, 3, 4, 5, 6, 7 }; + // eight bits: four words a row hold sixteen codes, two groups of eight + const p = hostOf(&words, &scales, &scales, 4, 8, 8); + const c = try sliceCols(a, p, .{ .rank = 1, .world = 2 }, "test"); + try std.testing.expectEqual(@as(usize, 2), c.words.shape[1]); + try std.testing.expectEqualSlices(u32, &.{ 2, 3, 6, 7, 10, 11, 14, 15 }, @alignCast(std.mem.bytesAsSlice(u32, c.words.bytes))); + try std.testing.expectEqualSlices(u16, &.{ 1, 3, 5, 7 }, @alignCast(std.mem.bytesAsSlice(u16, c.scales.bytes))); + const q = try sliceRows(a, p, &.{ .{ .from = 1, .to = 2 }, .{ .from = 3, .to = 4 } }); + try std.testing.expectEqualSlices(u32, &.{ 4, 5, 6, 7, 12, 13, 14, 15 }, @alignCast(std.mem.bytesAsSlice(u32, q.words.bytes))); +} + +test "the config's per-tensor widths override the global one" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const text = + \\{"group_size": 64, "bits": 4, "mode": "affine", + \\ "layers.0.mlp.gate": {"group_size": 32, "bits": 8}, + \\ "vision_tower.x": {"group_size": 64, "bits": 7}} + ; + const obj = (try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{})).object; + const q = (try detect(a, .{ .root = obj, .quantization = obj })).?; + try std.testing.expectEqual(Width{ .bits = 8, .group = 32 }, try q.width("layers.0.mlp.gate")); + try std.testing.expectEqual(Width{ .bits = 4, .group = 64 }, try q.width("layers.1.mlp.gate")); + try std.testing.expectError(error.UnsupportedQuantization, q.width("vision_tower.x")); + const gptq = (try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"group_size\": 64, \"bits\": 4, \"mode\": \"gptq\"}", .{})).object; + try std.testing.expect((try detect(a, .{ .root = gptq, .quantization = gptq })) == null); +} diff --git a/zig/src/core/quant/quant.zig b/zig/src/core/quant/quant.zig new file mode 100644 index 00000000000..fe9a1bf4186 --- /dev/null +++ b/zig/src/core/quant/quant.zig @@ -0,0 +1,200 @@ +//! The weight formats behind one interface: a format module provides what `conforms` lists; nothing above names one. + +const std = @import("std"); + +pub const types = @import("types.zig"); +pub const slice = @import("slice.zig"); +pub const convert = @import("convert.zig"); +pub const mlx = @import("mlx.zig"); +pub const dense = @import("dense.zig"); + +const Allocator = std.mem.Allocator; + +pub const Format = types.Format; +pub const Decoder = types.Decoder; +pub const Tables = types.Tables; +pub const Tensor = types.Tensor; +pub const DType = types.DType; +pub const Buf = types.Buf; +pub const Uploader = types.Uploader; +pub const Sources = types.Sources; +pub const Rank = slice.Rank; +pub const Span = slice.Span; +pub const join = types.join; + +/// The module of a format. +pub fn Module(comptime f: Format) type { + return switch (f) { + .mlx => mlx, + .dense => dense, + }; +} + +/// The order a tensor is offered to the formats: the first that recognizes it reads it. +const read_order = [_]Format{ .dense, .mlx }; + +/// What a format module provides, checked at compile time. +pub fn conforms(comptime M: type) void { + const required = .{ + "id", "decoder", // which format, and the device decoder its kernels use + "Config", "detect", // the checkpoint's own declaration of the format (null: not this format) + "Host", "matches", "read", "rows", "bytes", "halves", // a tensor's host side: recognized, read and split + "sliceRows", "sliceCols", "sliceStack", // tensor parallelism: output rows, input columns, experts + "Device", "upload", // load: onto the device, repacked there when the decoder reads a layout of its own + "Matrix", "View", "view", // what the kernels read of an uploaded tensor + "elements", "reference", // fp64 dequantization of every weight, for the tests + }; + inline for (required) |name| { + if (!@hasDecl(M, name)) @compileError("a format module needs `" ++ name ++ "`"); + } +} + +/// The checkpoint's declared quantization. +pub const Config = union(Format) { + mlx: mlx.Config, + dense: dense.Config, + + /// The tensor's MLX width (the table's own, else the global one). + pub fn width(c: Config, key: []const u8) error{UnsupportedQuantization}!mlx.Width { + return switch (c) { + .mlx => |q| q.width(key), + .dense => error.UnsupportedQuantization, + }; + } +}; + +/// The format the config declares, or `error.UnsupportedQuantization`. +pub fn detect(a: Allocator, src: Sources) (Allocator.Error || error{UnsupportedQuantization})!Config { + inline for (read_order) |f| { + if (try Module(f).detect(a, src)) |c| return @unionInit(Config, @tagName(f), c); + } + return error.UnsupportedQuantization; +} + +/// A projection read from the checkpoint, still on the host. +pub const Host = union(Format) { + mlx: mlx.Host, + dense: dense.Host, + + /// Output rows N. + pub fn rows(h: Host) usize { + return switch (h) { + inline else => |x, tag| Module(tag).rows(x), + }; + } + + /// The bytes of its tensors. + pub fn bytes(h: Host) usize { + return switch (h) { + inline else => |x, tag| Module(tag).bytes(x), + }; + } +}; + +fn wrap(comptime f: Format, v: Module(f).Host) Host { + return @unionInit(Host, @tagName(f), v); +} + +/// The projection `key` names: the first format that recognizes the tensors reads it. +pub fn read(a: Allocator, t: anytype, key: []const u8) !Host { + inline for (read_order) |f| { + if (Module(f).matches(t, key)) return wrap(f, try Module(f).read(a, t, key)); + } + return types.refuse(key, "no weight format reads this tensor"); +} + +/// A fused [embedding | hidden] projection as its two halves along K. +pub fn halves(a: Allocator, h: Host) ![2]Host { + switch (h) { + inline else => |x, tag| { + const pair = try Module(tag).halves(a, x); + return .{ wrap(tag, pair[0]), wrap(tag, pair[1]) }; + }, + } +} + +/// Output rows `spans`: a column-split projection's share on one rank. +pub fn sliceRows(a: Allocator, h: Host, spans: []const Span) slice.Error!Host { + switch (h) { + inline else => |x, tag| return wrap(tag, try Module(tag).sliceRows(a, x, spans)), + } +} + +/// One rank's input groups of a row-split projection. +pub fn sliceCols(a: Allocator, h: Host, r: Rank, what: []const u8) slice.Error!Host { + switch (h) { + inline else => |x, tag| return wrap(tag, try Module(tag).sliceCols(a, x, r, what)), + } +} + +/// A rank's `part` experts of a stack, and the shared one on rank 0. +pub fn sliceStack(a: Allocator, h: Host, r: Rank, part: usize) slice.Error!Host { + switch (h) { + inline else => |x, tag| return wrap(tag, try Module(tag).sliceStack(a, x, r, part)), + } +} + +/// A projection on the device, as its format uploaded it. +pub const Device = union(Format) { + mlx: mlx.Device, + dense: dense.Device, +}; + +pub fn upload(u: Uploader, h: Host) !Device { + switch (h) { + inline else => |x, tag| return @unionInit(Device, @tagName(tag), try Module(tag).upload(u, x)), + } +} + +/// What the kernels read of a projection, by format. +pub const Handle = union(Format) { + mlx: mlx.Matrix, + dense: dense.Matrix, +}; + +/// One product (N, K): the format's handle and its shape. A stack is one expert's shape at the stack's addresses. +pub const Projection = struct { + n: u32, + k: u32, + /// Split along K: the product stays fp32, one rank's share of a sum. + partial: bool = false, + handle: Handle, + + pub fn format(p: Projection) Format { + return std.meta.activeTag(p.handle); + } + + pub fn decoder(p: Projection) Decoder { + return switch (p.format()) { + inline else => |f| Module(f).decoder, + }; + } +}; + +/// The view of an uploaded projection, or of a stack of them (`stacked`). +pub fn view(d: Device, stacked: bool) error{UnsupportedTables}!Projection { + switch (d) { + inline else => |x, tag| { + const v = try Module(tag).view(x, stacked); + return .{ .n = v.n, .k = v.k, .handle = @unionInit(Handle, @tagName(tag), v.matrix) }; + }, + } +} + +test "every format module provides the interface" { + comptime conforms(mlx); + comptime conforms(dense); +} + +test "a projection knows its format and decoder" { + try std.testing.expectEqual(Decoder.mlx, (Projection{ .n = 1, .k = 32, .handle = .{ .mlx = undefined } }).decoder()); + try std.testing.expectEqual(Format.mlx, (Projection{ .n = 1, .k = 32, .handle = .{ .mlx = undefined } }).format()); +} + +test { + _ = @import("exact_test.zig"); + _ = slice; + _ = convert; + _ = mlx; + _ = dense; +} diff --git a/zig/src/core/quant/slice.zig b/zig/src/core/quant/slice.zig new file mode 100644 index 00000000000..6d652e02615 --- /dev/null +++ b/zig/src/core/quant/slice.zig @@ -0,0 +1,97 @@ +//! Tensor-parallel cuts of host tensors, the same for every format: rows, columns and experts, byte for byte. + +const std = @import("std"); +const st = @import("../safetensors.zig"); + +const Tensor = st.Tensor; +const Allocator = std.mem.Allocator; + +pub const Error = error{UnevenSplit} || Allocator.Error; + +/// A tensor-parallel rank of a group. +pub const Rank = struct { rank: usize, world: usize }; + +/// Rows [from, to) of a tensor's first dimension. +pub const Span = struct { from: usize, to: usize }; + +/// `size` over `world` equal parts, or `error.UnevenSplit` (logged under `what`). +pub fn even(size: usize, world: usize, what: []const u8) Error!usize { + if (size % world != 0) { + std.log.err("{s}: {d} does not split into {d} equal parts", .{ what, size, world }); + return error.UnevenSplit; + } + return size / world; +} + +fn rowBytes(t: Tensor) usize { + return t.numel() / t.shape[0] * t.dtype.size(); +} + +/// `spans` of `t`'s rows joined in order; one span shares the source's bytes. +pub fn takeRows(a: Allocator, t: Tensor, spans: []const Span) Error!Tensor { + const row = rowBytes(t); + var rows: usize = 0; + for (spans) |s| rows += s.to - s.from; + var out = t; + out.shape[0] = rows; + if (spans.len == 1) { + out.bytes = t.bytes[spans[0].from * row .. spans[0].to * row]; + return out; + } + const bytes = try a.alloc(u8, rows * row); + var at: usize = 0; + for (spans) |s| { + const n = (s.to - s.from) * row; + @memcpy(bytes[at..][0..n], t.bytes[s.from * row ..][0..n]); + at += n; + } + out.bytes = bytes; + return out; +} + +/// Columns [from, to) of a rank-2 tensor, copied. +pub fn takeCols(a: Allocator, t: Tensor, from: usize, to: usize) Error!Tensor { + const size = t.dtype.size(); + const width = (to - from) * size; + const bytes = try a.alloc(u8, t.shape[0] * width); + for (0..t.shape[0]) |r| @memcpy(bytes[r * width ..][0..width], t.bytes[(r * t.shape[1] + from) * size ..][0..width]); + var out = t; + out.shape[1] = to - from; + out.bytes = bytes; + return out; +} + +/// Experts [part * rank, ...) of a stacked tensor (E + 1 experts, the shared one last), and the shared one on rank 0. +pub fn takeExperts(a: Allocator, t: Tensor, r: Rank, part: usize) Error!Tensor { + const total = t.shape[0] - 1; + const row = rowBytes(t); + const mine = t.bytes[r.rank * part * row ..][0 .. part * row]; + if (r.rank != 0) { + var out = t; + out.shape[0] = part; + out.bytes = mine; + return out; + } + const bytes = try a.alloc(u8, (part + 1) * row); + @memcpy(bytes[0 .. part * row], mine); + @memcpy(bytes[part * row ..], t.bytes[total * row ..][0..row]); + var out = t; + out.shape[0] = part + 1; + out.bytes = bytes; + return out; +} + +test "rows join their spans and a column cut keeps its rows" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var data: [4 * 3]u16 = undefined; + for (&data, 0..) |*v, i| v.* = @intCast(i); + const t: Tensor = .{ .dtype = .u16, .rank = 2, .shape = .{ 4, 3, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&data) }; + const rows = try takeRows(a, t, &.{ .{ .from = 1, .to = 2 }, .{ .from = 3, .to = 4 } }); + try std.testing.expectEqualSlices(u16, &.{ 3, 4, 5, 9, 10, 11 }, @alignCast(std.mem.bytesAsSlice(u16, rows.bytes))); + const cols = try takeCols(a, t, 1, 3); + try std.testing.expectEqual(@as(usize, 2), cols.shape[1]); + try std.testing.expectEqualSlices(u16, &.{ 1, 2, 4, 5, 7, 8, 10, 11 }, @alignCast(std.mem.bytesAsSlice(u16, cols.bytes))); + try std.testing.expectEqual(@as(usize, 2), try even(4, 2, "test")); +} diff --git a/zig/src/core/quant/types.zig b/zig/src/core/quant/types.zig new file mode 100644 index 00000000000..36d0bcd20ea --- /dev/null +++ b/zig/src/core/quant/types.zig @@ -0,0 +1,58 @@ +//! What the format modules share: format tags, device decoder ids and the uploaded tensor; nothing here is a backend's. + +const std = @import("std"); +const st = @import("../safetensors.zig"); + +pub const Tensor = st.Tensor; +pub const DType = st.DType; + +/// The weight formats the backend reads. +pub const Format = enum { mlx, dense }; + +/// The decoder a format's kernels instantiate the shared tiles with: each backend names the kernels of its decoders. +pub const Decoder = enum(u8) { mlx = 0, dense = 1 }; + +/// The type of a group table, numbered as the kernels number it. +pub const Tables = enum(u8) { f32 = 0, bf16 = 1, f16 = 2 }; + +/// The config objects a format reads its quantization from: `quantization` of the text tower or the root, and the root. +pub const Sources = struct { root: std.json.ObjectMap, quantization: std.json.ObjectMap }; + +/// `parts` joined in `buf`: a tensor's key from its base and suffix. +pub fn join(buf: []u8, parts: []const []const u8) []const u8 { + var n: usize = 0; + for (parts) |p| { + @memcpy(buf[n..][0..p.len], p); + n += p.len; + } + return buf[0..n]; +} + +/// A tensor the loader refuses, logged under its key. +pub fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { + std.log.err("{s}: {s}", .{ key, what }); + return error.UnexpectedTensor; +} + +/// One uploaded tensor: its device address and the element type and shape of the bytes there. +pub const Buf = struct { + ptr: u64, + len: usize, + dtype: DType, + rank: u8, + shape: [st.max_rank]usize, + + pub fn dim(b: Buf, i: usize) usize { + return if (i < b.rank) b.shape[i] else 1; + } +}; + +/// How a backend puts a host tensor on its device: `put` copies it, returns where it landed, keeps what it must free. +pub const Uploader = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, t: Tensor) anyerror!Buf, + + pub fn tensor(u: Uploader, t: Tensor) !Buf { + return u.put(u.ctx, t); + } +}; diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 92f4eeb367d..4aca8ae1474 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -11,11 +11,13 @@ pub const tokenizer = @import("tokenizer"); // a module of its own, so the nativ pub const ids_json = @import("ids_json.zig"); pub const affine4_host = @import("affine4_host.zig"); pub const shard_edit = @import("shard_edit.zig"); +pub const quant = @import("quant/quant.zig"); test { _ = safetensors; _ = affine4_host; _ = shard_edit; + _ = quant; _ = exl3_format; _ = @import("exl3_rect_test.zig"); _ = checkpoint; From 48abd9908ed79c5e92457788d62ac4fd3f307616 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:05:33 +0200 Subject: [PATCH 03/52] feat(core): a kernel registry that picks a product's tile by tuned cost, one family of bits at every row count core/registry selects, for a format, op (product, group, routed plan, routed with activation) and path (decode or prompt), the cheapest entry the GPU, the run's switches and the shape allow, by a per-GPU tuning table read at build time (core/tuning), so every rank picks alike. Its family rule checks that one (op, path) keeps one family of entries at every row count from 1 to 256 for each width and group: a row's bits never depend on how many rows share its launch. The rule's test fails when a tuning table lets another family take some rows. --- zig/src/core/registry.zig | 309 ++++++++++++++++++++++++++++++++++++++ zig/src/core/root.zig | 4 + zig/src/core/tuning.zig | 46 ++++++ 3 files changed, 359 insertions(+) create mode 100644 zig/src/core/registry.zig create mode 100644 zig/src/core/tuning.zig diff --git a/zig/src/core/registry.zig b/zig/src/core/registry.zig new file mode 100644 index 00000000000..e355c09c319 --- /dev/null +++ b/zig/src/core/registry.zig @@ -0,0 +1,309 @@ +//! Kernel choice: `select` takes the cheapest entry by tuning table, so ranks agree; one family writes equal bits. + +const std = @import("std"); +const quant = @import("quant/quant.zig"); +const tuning = @import("tuning.zig"); + +/// What is launched: a product, up to four sharing x, a plan over stacked experts, or its gate and up with activation. +pub const Op = enum { project, group, routed, routed_act }; + +/// A prompt's span, or anything that decodes (a lane round, the logits head, a draft). +pub const Path = enum { decode, prefill }; + +/// Entries that write the same bytes for any row of a product. +pub const Family = enum { stream, row, lanes, wide, tiled, reference, split, gemm }; + +/// A product as the choice sees it. +pub const Shape = struct { + /// Rows of x; a plan's most rows in an item. + m: u32, + n: u32, + k: u32, + bits: u8, + group: u16, + /// x is fp16 (bf16 otherwise). + fp16: bool, + tables: quant.Tables = .bf16, + tables_alike: bool = true, + /// x on 16 bytes. + x_aligned: bool = true, + /// The words on the load size of their width. + words_aligned: bool = true, + /// A plan's items; 0 is a plain product. + items: u32 = 0, + /// Parts the groups are split into. + parts: u32 = 1, + /// Inside a lane round: the decode tile keeps every row count. + round: bool = false, + /// The activation of a stacked gate and up is the epilogue. + pairs: bool = false, +}; + +/// What the GPU has and the run switched on. +pub const Env = struct { + /// bf16 activations (fp16 otherwise). + bf16: bool, + /// Matrix cores a tile can use exist. + matrix: bool, + /// ...and the run lets them take the rows above the decode tiles'. + matrix_on: bool, + stream_on: bool, + /// The GEMM tile (else the reference one) takes the products. + gemm_on: bool, +}; + +/// Whether an entry writes the activation type itself instead of fp32. +pub const Rounds = enum { never, always, fp16 }; + +pub fn Entry(comptime Launch: type) type { + return struct { + id: []const u8, + format: quant.Format, + op: Op, + path: Path, + family: Family, + /// What the GPU must have. + caps: *const fn (Env) bool, + /// What the run must not have switched off. + policy: *const fn (Env) bool, + /// What the kernel can do: alignments, widths, row counts it has code for. + fits: *const fn (Shape) bool, + rounds: Rounds = .never, + /// A lane round takes it at any row count its shape fits. + round_any: bool = false, + launch: Launch, + + /// Whether the entry writes the activation type at this shape. + pub fn roundsAct(e: *const @This(), s: Shape) bool { + return switch (e.rounds) { + .never => false, + .always => true, + .fp16 => s.fp16, + }; + } + }; +} + +/// Room for the entries' tuned rows: a Registry sits in a backend's kernel table, so its size is fixed. +pub const max_entries = 64; + +/// The most rows the family rule is checked at. +pub const rule_rows = 256; + +pub fn Registry(comptime Launch: type) type { + return struct { + const Self = @This(); + pub const E = Entry(Launch); + + entries: []const E, + table: *const tuning.Table, + tuned: [max_entries]?tuning.Row, + + pub fn init(table: *const tuning.Table, entries: []const E) Self { + std.debug.assert(entries.len <= max_entries); + var r: Self = .{ .entries = entries, .table = table, .tuned = @splat(null) }; + for (entries, 0..) |e, i| r.tuned[i] = tuning.find(table, e.id); + return r; + } + + /// The cost of entry `i` at `shape`, or null where its row has no room for the shape. + fn cost(r: *const Self, i: usize, shape: Shape, env: Env) ?f32 { + const e = &r.entries[i]; + const t = r.tuned[i] orelse return null; + const plan = shape.items > 0; + if (plan and !t.routed) return null; + if (!plan and !t.plain) return null; + if (t.items != 0 and plan and shape.items > t.items) return null; + // a routed prompt's kernel is chosen by its items, whatever rows they hold + if (!plan or e.path == .decode) { + const limit = if (t.rows_matrix != 0 and env.matrix_on and env.matrix) t.rows_matrix else t.rows; + if (!(e.round_any and shape.round) and limit != 0 and shape.m > limit) return null; + if (shape.m < t.min_rows) return null; + } + return t.cost; + } + + /// The cheapest entry of (format, op, path) the GPU, run and shape allow; null when none takes the shape. + pub fn select(r: *const Self, env: Env, format: quant.Format, op: Op, path: Path, shape: Shape) ?*const E { + var best: ?*const E = null; + var best_cost: f32 = std.math.inf(f32); + for (r.entries, 0..) |*e, i| { + if (e.format != format or e.op != op or e.path != path or !e.caps(env) or !e.policy(env) or !e.fits(shape)) continue; + const c = r.cost(i, shape, env) orelse continue; + if (c < best_cost) { + best = e; + best_cost = c; + } + } + return best; + } + + /// The family rule for one (op, path) of a format: at every row count it selects the one family. + fn rule(r: *const Self, env: Env, format: quant.Format, op: Op, path: Path, base: Shape, quiet: bool) error{FamilyChanges}!void { + var shape = base; + var seen: ?Family = null; + for (1..rule_rows + 1) |m| { + shape.m = @intCast(m); + const e = r.select(env, format, op, path, shape) orelse continue; + if (seen) |f| { + if (f != e.family) { + if (!quiet) std.log.err("registry: {s} at {d} rows is {t}, not {t} ({d} bits, group {d})", .{ e.id, m, e.family, f, shape.bits, shape.group }); + return error.FamilyChanges; + } + } else seen = e.family; + } + } + + /// Checks the family rule for a round's decode, a prompt's products and routed plans, at every width and group. + pub fn verify(r: *const Self, env: Env, format: quant.Format) error{FamilyChanges}!void { + // the reference decode tiles and the reference GEMM tile are the Python engine's rules, by row count + if (!env.stream_on or !env.gemm_on) return; + for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| for ([_]u16{ 32, 64, 128 }) |group| { + var base: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = bits, .group = group, .fp16 = !env.bf16, .tables = if (env.bf16) .bf16 else .f16 }; + base.round = true; + try r.rule(env, format, .project, .decode, base, false); + base.round = false; + try r.rule(env, format, .project, .prefill, base, false); + base.items = 64; + try r.rule(env, format, .routed, .prefill, base, false); + }; + } + + /// What each (op, path) chose across row counts, one line a run of rows: for `--explain-kernels`. + pub fn explain(r: *const Self, env: Env, format: quant.Format, w: *std.Io.Writer, bits: u8, group: u16) std.Io.Writer.Error!void { + const base: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = bits, .group = group, .fp16 = !env.bf16, .tables = if (env.bf16) .bf16 else .f16 }; + try w.print("kernel choice for {t} on {s}: {d}-bit, group {d}, {s} activations\n", .{ format, r.table.gfx, bits, group, if (env.bf16) "bf16" else "fp16" }); + const rows = [_]struct { Op, Path, bool, u32 }{ + .{ .project, .decode, true, 0 }, + .{ .project, .decode, false, 0 }, + .{ .group, .decode, true, 0 }, + .{ .routed, .decode, false, 64 }, + .{ .routed_act, .decode, false, 64 }, + .{ .project, .prefill, false, 0 }, + .{ .routed, .prefill, false, 64 }, + }; + for (rows) |row| { + var shape = base; + shape.round = row[2]; + shape.items = row[3]; + shape.pairs = row[0] == .routed_act; + try w.print(" {t} {t}{s}{s}:", .{ row[0], row[1], if (row[2]) " in a lane round" else "", if (row[3] != 0) " over a plan" else "" }); + var from: u32 = 1; + var last: ?*const E = null; + var m: u32 = 1; + while (m <= rule_rows) : (m += 1) { + shape.m = m; + const e = r.select(env, format, row[0], row[1], shape); + if (m > 1 and e != last) { + try printRun(w, from, m - 1, last); + from = m; + } + last = e; + } + try printRun(w, from, rule_rows, last); + try w.writeAll("\n"); + } + } + + fn printRun(w: *std.Io.Writer, from: u32, to: u32, e: ?*const E) std.Io.Writer.Error!void { + const name = if (e) |x| x.id[std.mem.lastIndexOfScalar(u8, x.id, '.').? + 1 ..] else "none"; + if (from == to) try w.print(" {d} {s}", .{ from, name }) else try w.print(" {d}-{d} {s}", .{ from, to, name }); + } + }; +} + +// ---- the rules, on entries of no backend + +const Toy = Registry(*const fn () void); +const ToyEntry = Toy.E; + +fn nothing() void {} + +fn anyEnv(_: Env) bool { + return true; +} + +fn anyShape(_: Shape) bool { + return true; +} + +fn toy(id: []const u8, path: Path, family: Family, round_any: bool) ToyEntry { + return .{ .id = id, .format = .mlx, .op = .project, .path = path, .family = family, .caps = &anyEnv, .policy = &anyEnv, .fits = &anyShape, .round_any = round_any, .launch = ¬hing }; +} + +const toy_env: Env = .{ .bf16 = true, .matrix = true, .matrix_on = true, .stream_on = true, .gemm_on = true }; +const toy_shape: Shape = .{ .m = 1, .n = 64, .k = 64, .bits = 4, .group = 32, .fp16 = false }; + +test "the cheapest entry that has room for the rows runs" { + const entries = [_]ToyEntry{ + toy("a.decode.few", .decode, .stream, true), + toy("a.decode.cores", .decode, .gemm, false), + toy("a.decode.any", .decode, .lanes, false), + }; + const rows = [_]tuning.Row{ + .{ .id = "a.decode.few", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "a.decode.cores", .cost = 2, .min_rows = 16 }, + .{ .id = "a.decode.any", .cost = 3 }, + }; + const r = Toy.init(&.{ .gfx = "toy", .rows = &rows }, &entries); + var shape = toy_shape; + const want = [_]struct { u32, []const u8 }{ .{ 1, "few" }, .{ 15, "few" }, .{ 16, "cores" }, .{ 100, "cores" } }; + for (want) |w| { + shape.m = w[0]; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .decode, shape).?.id, w[1])); + } + // the matrix cores off: the 16th row is still the decode tile's + var off = toy_env; + off.matrix_on = false; + shape.m = 16; + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "few")); + // a lane round keeps its tile at any rows; another format has no entry + shape.round = true; + shape.m = 200; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .decode, shape).?.id, "few")); + try std.testing.expect(r.select(toy_env, .dense, .project, .decode, shape) == null); + // an entry the table does not list never runs + const partial = Toy.init(&.{ .gfx = "toy", .rows = rows[2..] }, &entries); + try std.testing.expect(std.mem.endsWith(u8, partial.select(toy_env, .mlx, .project, .decode, shape).?.id, "any")); +} + +test "a plan is chosen by its items, a plain product by its rows" { + const entries = [_]ToyEntry{ + toy("a.prefill.short", .prefill, .gemm, false), + toy("a.prefill.plan", .prefill, .gemm, false), + toy("a.prefill.big", .prefill, .gemm, false), + }; + const rows = [_]tuning.Row{ + .{ .id = "a.prefill.short", .cost = 1, .rows = 4, .routed = false }, + .{ .id = "a.prefill.plan", .cost = 2, .items = 300, .plain = false }, + .{ .id = "a.prefill.big", .cost = 3 }, + }; + const r = Toy.init(&.{ .gfx = "toy", .rows = &rows }, &entries); + var shape = toy_shape; + shape.m = 3; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .prefill, shape).?.id, "short")); + shape.m = 5; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .prefill, shape).?.id, "big")); + // the rows an item holds do not count for a plan + shape.items = 100; + shape.m = 40; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .prefill, shape).?.id, "plan")); + shape.items = 301; + try std.testing.expect(std.mem.endsWith(u8, r.select(toy_env, .mlx, .project, .prefill, shape).?.id, "big")); +} + +test "the family rule refuses a path whose family changes with the rows" { + const entries = [_]ToyEntry{ + toy("a.decode.small", .decode, .stream, false), + toy("a.decode.large", .decode, .gemm, false), + toy("a.prefill.all", .prefill, .gemm, false), + }; + const rows = [_]tuning.Row{ + .{ .id = "a.decode.small", .cost = 1, .rows = 8 }, + .{ .id = "a.decode.large", .cost = 2, .min_rows = 9 }, + .{ .id = "a.prefill.all", .cost = 1 }, + }; + const r = Toy.init(&.{ .gfx = "toy", .rows = &rows }, &entries); + try r.rule(toy_env, .mlx, .project, .prefill, toy_shape, true); + try std.testing.expectError(error.FamilyChanges, r.rule(toy_env, .mlx, .project, .decode, toy_shape, true)); +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 4aca8ae1474..3e9cfba6320 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -12,12 +12,16 @@ pub const ids_json = @import("ids_json.zig"); pub const affine4_host = @import("affine4_host.zig"); pub const shard_edit = @import("shard_edit.zig"); pub const quant = @import("quant/quant.zig"); +pub const registry = @import("registry.zig"); +pub const tuning = @import("tuning.zig"); test { _ = safetensors; _ = affine4_host; _ = shard_edit; _ = quant; + _ = registry; + _ = tuning; _ = exl3_format; _ = @import("exl3_rect_test.zig"); _ = checkpoint; diff --git a/zig/src/core/tuning.zig b/zig/src/core/tuning.zig new file mode 100644 index 00000000000..1925a8afe73 --- /dev/null +++ b/zig/src/core/tuning.zig @@ -0,0 +1,46 @@ +//! The registry's costs per GPU, read at build time from a backend's .zon files; no autotuning, so ranks agree. + +const std = @import("std"); + +/// One entry's cost and the products it takes (the file's header says what each field means). +pub const Row = struct { + id: []const u8, + cost: f32, + rows: u32 = 0, + rows_matrix: u32 = 0, + min_rows: u32 = 0, + items: u32 = 0, + plain: bool = true, + routed: bool = true, +}; + +pub const Table = struct { gfx: []const u8, rows: []const Row }; + +/// The table a .zon document of `gfx` and `entries` describes. +pub fn build(comptime zon: anytype) Table { + const rows = comptime blk: { + var out: [zon.entries.len]Row = undefined; + for (zon.entries, 0..) |e, i| { + var row: Row = .{ .id = e.id, .cost = e.cost }; + for (@typeInfo(Row).@"struct".field_names) |name| { + if (std.mem.eql(u8, name, "id") or std.mem.eql(u8, name, "cost")) continue; + if (@hasField(@TypeOf(e), name)) @field(row, name) = @field(e, name); + } + out[i] = row; + } + break :blk out; + }; + return .{ .gfx = zon.gfx, .rows = &rows }; +} + +pub fn find(t: *const Table, id: []const u8) ?Row { + for (t.rows) |r| if (std.mem.eql(u8, r.id, id)) return r; + return null; +} + +test "a table is found by an entry's id" { + const zon = .{ .gfx = "toy", .entries = .{ .{ .id = "a", .cost = 1 }, .{ .id = "b", .cost = 2, .rows = 8 } } }; + const t = comptime build(zon); + try std.testing.expectEqual(@as(u32, 8), find(&t, "b").?.rows); + try std.testing.expect(find(&t, "c") == null); +} From 625422815a1d2740a9939e410e1fe399613903d5 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:16:41 +0200 Subject: [PATCH 04/52] feat(hip): the MLX affine products: dot2 tiles, the gfx11 matrix-core GEMM tile, stream and K-parallel tiles The MLX affine 2- to 8-bit products a model's projections run, chosen per product by the kernel registry over a per-GPU tuning table (gfx1030's for RDNA2, gfx1100's for RDNA3 to RDNA4): the decode row, column, stream and split tiles, the RDNA2 wide tile, the prefill dot2 GEMM and K-parallel tiles, the gfx11 matrix-core GEMM tile (compiler WMMA builtins, no rocWMMA), routed plans and products sharing x, with the routed gate and up's activation as an epilogue. The tile sources hold device code only; each kernel the Zig launches resolve is instantiated explicitly. hip-kernel-test checks every entry on the served models' shapes and a ragged sweep of every width and group against float64, the entries the registry picks between by rows for equal bytes, and a row's bytes alone and in a round of 2 to 32 rows. --- zig/build/hip.zig | 23 +- zig/kernels/hip/common/arch.hpp | 53 ++ zig/kernels/hip/common/dot2.hpp | 71 +++ zig/kernels/hip/common/vec.hpp | 11 + zig/kernels/hip/common/wmma.hpp | 30 + zig/kernels/hip/quant/act.hpp | 26 + zig/kernels/hip/quant/mlx.hpp | 75 +++ zig/kernels/hip/quant/mlx_decoder.hpp | 215 +++++++ zig/kernels/hip/quant/mlx_pieces.hpp | 63 ++ zig/kernels/hip/quant/mlx_tiles.hpp | 68 +++ zig/kernels/hip/tiles/dot2.hip | 389 +++++++++++++ zig/kernels/hip/tiles/dot2.hpp | 22 + zig/kernels/hip/tiles/dot2_tiles.hip | 377 ++++++++++++ zig/kernels/hip/tiles/epilogue.hpp | 86 +++ zig/kernels/hip/tiles/gemm.hpp | 248 ++++++++ zig/kernels/hip/tiles/gemm_kp.hpp | 178 ++++++ zig/kernels/hip/tiles/matrix_gemm.hpp | 209 +++++++ zig/kernels/hip/tiles/plan.hpp | 27 + zig/kernels/hip/tiles/stream.hpp | 235 ++++++++ zig/src/hip/kernel_tests.zig | 2 + zig/src/hip/kernel_tests/affine/affine.zig | 186 ++++++ zig/src/hip/kernel_tests/affine/cases.zig | 120 ++++ zig/src/hip/kernel_tests/affine/data.zig | 89 +++ zig/src/hip/kernel_tests/affine/product.zig | 261 +++++++++ zig/src/hip/kernel_tests/affine/reference.zig | 76 +++ zig/src/hip/kernel_tests/affine/rows.zig | 420 ++++++++++++++ zig/src/hip/kernel_tests/decode.zig | 168 ++++++ zig/src/hip/kernel_tests/rig.zig | 39 ++ zig/src/hip/kernels.zig | 2 +- zig/src/hip/launches.zig | 18 +- zig/src/hip/launches/affine.zig | 547 ++++++++++++++++++ zig/src/hip/launches/mlx_entries.zig | 408 +++++++++++++ zig/src/hip/ops/ops.zig | 17 + zig/src/hip/ops/project.zig | 223 +++++++ zig/src/hip/ops/types.zig | 34 +- zig/src/hip/tuning/gfx1030.zon | 46 ++ zig/src/hip/tuning/gfx1100.zon | 46 ++ zig/src/hip/tuning/tuning.zig | 21 + zig/tests/hip_kernels.md | 8 + 39 files changed, 5131 insertions(+), 6 deletions(-) create mode 100644 zig/kernels/hip/common/arch.hpp create mode 100644 zig/kernels/hip/common/dot2.hpp create mode 100644 zig/kernels/hip/common/vec.hpp create mode 100644 zig/kernels/hip/common/wmma.hpp create mode 100644 zig/kernels/hip/quant/act.hpp create mode 100644 zig/kernels/hip/quant/mlx.hpp create mode 100644 zig/kernels/hip/quant/mlx_decoder.hpp create mode 100644 zig/kernels/hip/quant/mlx_pieces.hpp create mode 100644 zig/kernels/hip/quant/mlx_tiles.hpp create mode 100644 zig/kernels/hip/tiles/dot2.hip create mode 100644 zig/kernels/hip/tiles/dot2.hpp create mode 100644 zig/kernels/hip/tiles/dot2_tiles.hip create mode 100644 zig/kernels/hip/tiles/epilogue.hpp create mode 100644 zig/kernels/hip/tiles/gemm.hpp create mode 100644 zig/kernels/hip/tiles/gemm_kp.hpp create mode 100644 zig/kernels/hip/tiles/matrix_gemm.hpp create mode 100644 zig/kernels/hip/tiles/plan.hpp create mode 100644 zig/kernels/hip/tiles/stream.hpp create mode 100644 zig/src/hip/kernel_tests/affine/affine.zig create mode 100644 zig/src/hip/kernel_tests/affine/cases.zig create mode 100644 zig/src/hip/kernel_tests/affine/data.zig create mode 100644 zig/src/hip/kernel_tests/affine/product.zig create mode 100644 zig/src/hip/kernel_tests/affine/reference.zig create mode 100644 zig/src/hip/kernel_tests/affine/rows.zig create mode 100644 zig/src/hip/launches/affine.zig create mode 100644 zig/src/hip/launches/mlx_entries.zig create mode 100644 zig/src/hip/ops/project.zig create mode 100644 zig/src/hip/tuning/gfx1030.zon create mode 100644 zig/src/hip/tuning/gfx1100.zon create mode 100644 zig/src/hip/tuning/tuning.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index c20bddcaf22..c0d82db7318 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -22,6 +22,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu }); 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) })); + hip_test_module.addImport("core", coreModule(b, b.graph.host)); 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); @@ -70,21 +71,29 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu 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); + kernel_module.addImport("core", coreModule(b, target)); 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", "recurrence/gdn_prefill.hip", "decode/decode.hip", "decode/plan.hip" }; +const groups = [_][]const u8{ "ops/ops.hip", "ops/act.hip", "attention/attention.hip", "recurrence/gated_delta.hip", "attention/prefill.hip", "recurrence/gdn_prefill.hip", "decode/decode.hip", "decode/plan.hip", "tiles/dot2_tiles.hip", "tiles/dot2.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" }; +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", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", "common/wmma.hpp", + "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", + "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", "tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", + "tiles/plan.hpp", "tiles/stream.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: [8][]align(8) const u8 = @splat(&.{});\n"; +const stub = "pub const arch = \"\";\npub const images: [10][]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 { @@ -101,6 +110,7 @@ fn kernelObjects(b: *std.Build, hipcc: []const u8, hipcc_resolved: []const u8, d 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("-DTF_MATRIX={d}", .{@intFromBool(c.matrix != .none)})); 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})); @@ -115,3 +125,10 @@ fn kernelObjects(b: *std.Build, hipcc: []const u8, hipcc_resolved: []const u8, d } 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 })) }); } + +/// The backend-neutral core (checkpoint formats, the kernel registry), as the other backends import it. +fn coreModule(b: *std.Build, target: std.Build.ResolvedTarget) *std.Build.Module { + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .link_libc = true }); + core.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .link_libc = true })); + return core; +} diff --git a/zig/kernels/hip/common/arch.hpp b/zig/kernels/hip/common/arch.hpp new file mode 100644 index 00000000000..5aeb14f5f39 --- /dev/null +++ b/zig/kernels/hip/common/arch.hpp @@ -0,0 +1,53 @@ +#pragma once + +// RDNA2 (dot2), RDNA3 / 3.5 (gfx11 WMMA), RDNA4 (gfx12 WMMA) from the build's TF_* cap macros; RDNA1 is refused. + +#if !defined(TF_WAVE) || !defined(TF_MATRIX) +#error "the caps macros come from the build" +#endif + +namespace tf { +namespace rocm { + +enum class Gen { rdna2, rdna3, rdna4 }; + +// Device code only: host dispatch reads TF_MATRIX from the build. +#if defined(__gfx1200__) || defined(__gfx1201__) || defined(__gfx12_generic__) +inline constexpr Gen kGen = Gen::rdna4; +inline constexpr bool kWmma = true; +#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) \ + || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1153__) \ + || defined(__gfx11_generic__) +inline constexpr Gen kGen = Gen::rdna3; +inline constexpr bool kWmma = true; +#elif defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__) || defined(__gfx1033__) \ + || defined(__gfx1034__) || defined(__gfx1035__) || defined(__gfx1036__) +inline constexpr Gen kGen = Gen::rdna2; +inline constexpr bool kWmma = false; +#elif defined(__gfx1010__) || defined(__gfx1011__) || defined(__gfx1012__) +static_assert(false, "RDNA1 (gfx101x) is not a TensorFold target"); +#else +inline constexpr Gen kGen = Gen::rdna2; +inline constexpr bool kWmma = false; +#endif + +} // namespace rocm + +// v_dot2_f32_bf16 (gfx11 and gfx12 device code): the BF16 dot2 tiles of the RDNA3 experts. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) \ + || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1153__) \ + || defined(__gfx11_generic__) || defined(__gfx1200__) || defined(__gfx1201__) || defined(__gfx12_generic__) +#define TF_DEVICE_BF16_DOT2 1 +#else +#define TF_DEVICE_BF16_DOT2 0 +#endif + +// gfx11 device code: v_wmma_f32_16x16x16_bf16 with its wave32 layouts (gfx12's differs). +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) \ + || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1153__) \ + || defined(__gfx11_generic__) +#define TF_DEVICE_WMMA_GFX11 1 +#else +#define TF_DEVICE_WMMA_GFX11 0 +#endif +} // namespace tf diff --git a/zig/kernels/hip/common/dot2.hpp b/zig/kernels/hip/common/dot2.hpp new file mode 100644 index 00000000000..f84a80f8518 --- /dev/null +++ b/zig/kernels/hip/common/dot2.hpp @@ -0,0 +1,71 @@ +#pragma once + +// The Dot plug-ins of the tiles: the multiply-accumulate unit of an activation type and its operands. + +#include + +#include "common/arch.hpp" + +namespace tf { +namespace rocm { + +typedef __bf16 bf16x2 __attribute__((ext_vector_type(2))); + +// One dot2 whose x pair is lane I of the lane's quad (DPP quad_perm), as a pair of 32-bit words. +template +__device__ inline float dot_quad_shared(uint32_t x, uint32_t w, float acc) { + const uint32_t shared = __builtin_amdgcn_mov_dpp(static_cast(x), I * 0x55, 0xf, 0xf, false); + return T::dot(__builtin_bit_cast(typename T::pair, shared), __builtin_bit_cast(typename T::pair, w), acc); +} + +// FP16 v_dot2_f32_f16 (RDNA2 and gfx11 / gfx12). +struct DotF16 { + using elem = __half; + using pair = __half2; + // A pair of 1.0: dotted with x it gives the sum of x. + static constexpr uint32_t ones = 0x3c003c00u; + __device__ static elem zero() { return __float2half(0.f); } + __device__ static pair two(elem a, elem b) { return __halves2half2(a, b); } + __device__ static float lo(pair p) { return __low2float(p); } + __device__ static float hi(pair p) { return __high2float(p); } + __device__ static float dot(pair x, pair q, float acc) { return __builtin_amdgcn_fdot2(x, q, acc, false); } + // On RDNA2 the DPP form of v_dot2c_f32_f16 does it in one instruction at full rate (row_share would halve it). + template + __device__ static float quad(uint32_t x, uint32_t w, float acc) { +#if !TF_DOT2_BF16 + asm("v_dot2c_f32_f16_dpp %0, %1, %2 quad_perm:[%3,%3,%3,%3] row_mask:0xf bank_mask:0xf" + : "+v"(acc) + : "v"(x), "v"(w), "n"(I)); + return acc; +#else + return dot_quad_shared(x, w, acc); +#endif + } +}; + +// BF16 v_dot2_f32_bf16 (gfx11 / gfx12). +struct DotBF16 { + using elem = __bf16; + using pair = bf16x2; + static constexpr uint32_t ones = 0x3f803f80u; + __device__ static elem zero() { return static_cast<__bf16>(0.f); } + __device__ static pair two(elem a, elem b) { return pair{a, b}; } + __device__ static float lo(pair p) { return static_cast(p.x); } + __device__ static float hi(pair p) { return static_cast(p.y); } + __device__ static float dot(pair x, pair q, float acc) { +#if TF_DEVICE_BF16_DOT2 + return __builtin_amdgcn_fdot2_f32_bf16(x, q, acc, false); +#else + __builtin_trap(); + return acc; +#endif + } + // The BF16 dot2 has no DPP form: the x word is moved across the quad first. + template + __device__ static float quad(uint32_t x, uint32_t w, float acc) { + return dot_quad_shared(x, w, acc); + } +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/common/vec.hpp b/zig/kernels/hip/common/vec.hpp new file mode 100644 index 00000000000..6f24575cbdb --- /dev/null +++ b/zig/kernels/hip/common/vec.hpp @@ -0,0 +1,11 @@ +#pragma once + +// The 128-bit vector the tiles load code words and activation rows with. + +namespace tf { +namespace rocm { + +using u32x4 = unsigned __attribute__((ext_vector_type(4))); + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/common/wmma.hpp b/zig/kernels/hip/common/wmma.hpp new file mode 100644 index 00000000000..663cd59e2c9 --- /dev/null +++ b/zig/kernels/hip/common/wmma.hpp @@ -0,0 +1,30 @@ +#pragma once + +// The matrix-core Dot of gfx11: v_wmma_f32_16x16x16_bf16 with its wave32 layouts (gfx12's differs), over BF16 operands. + +#include "common/dot2.hpp" +#include "common/vec.hpp" + +namespace tf { +namespace rocm { + +typedef __bf16 bf16x16 __attribute__((ext_vector_type(16))); +typedef unsigned u32x8 __attribute__((ext_vector_type(8))); +typedef float f32x8 __attribute__((ext_vector_type(8))); + +// The 16 BF16 of a row's 16 k as one fragment: two 16-byte words of the staged tile. +__device__ inline bf16x16 frag16(const uint32_t* p) { + const u32x4 lo = *reinterpret_cast(p); + const u32x4 hi = *reinterpret_cast(p + 4); + return __builtin_bit_cast(bf16x16, __builtin_shufflevector(lo, hi, 0, 1, 2, 3, 4, 5, 6, 7)); +} + +// The BF16 elements and sums of DotBF16, and the 16 x 16 x 16 product of two fragments added to an accumulator. +struct WmmaBF16 : DotBF16 { +#if TF_DEVICE_WMMA_GFX11 + __device__ static f32x8 mma(bf16x16 a, bf16x16 b, f32x8 c) { return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); } +#endif +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/act.hpp b/zig/kernels/hip/quant/act.hpp new file mode 100644 index 00000000000..e26c1cfb4c5 --- /dev/null +++ b/zig/kernels/hip/quant/act.hpp @@ -0,0 +1,26 @@ +#pragma once + +// ActEncoders feed a tile the activation rows: as the Dot's element type, or quantized once a launch with scales kept. + +#include "common/dot2.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +template +struct IdentityAct { + using elem = typename T::elem; + + // Row r of the block's x (a plan's pair r reads its x row), `k` elements. + template + __device__ static const elem* row(const Args& a, int r) { + return static_cast(a.x) + x_row(a, r) * a.k; + } +}; + +using F16Act = IdentityAct; +using BF16Act = IdentityAct; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx.hpp b/zig/kernels/hip/quant/mlx.hpp new file mode 100644 index 00000000000..9d376a277dc --- /dev/null +++ b/zig/kernels/hip/quant/mlx.hpp @@ -0,0 +1,75 @@ +#pragma once + +// MLX affine words: y[m, n] = sum_g (scale[n, g] * sum_k x[m, k] * code[n, k] + bias[n, g] * sum_k x[m, k]). + +#include +#include +#include + +#include + +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +enum ScaleKind : int { kScaleF32 = 0, kScaleBF16 = 1, kScaleF16 = 2 }; + +// One (n, k / group) table of scales or biases, row major, in its stored type. +struct GroupTable { + const void* p; + int kind; // ScaleKind + __device__ float operator[](long long i) const { + if (kind == kScaleBF16) return static_cast(static_cast(p)[i]); + if (kind == kScaleF16) return __half2float(static_cast(p)[i]); + return static_cast(p)[i]; + } +}; + +struct Affine { + const void* x; // (m, k) row major, bf16 or fp16 + const uint32_t* words; // (n, k * bits / 32) row major + GroupTable scale; + GroupTable bias; + float* out; // (m, n) + int m, n, k, bits, group; + int fp16; // 0 is bf16, 1 is fp16 + Routing route = {}; + __half* out16 = nullptr; // set: the decode tile rounds each output to fp16 here instead of writing out +}; + +// A routed block takes item ``z``: its expert's weights and its rows. False when the item has no rows. +__device__ inline bool take_item(Affine& a, int z) { + if (!a.route.items) return true; + const int* item = a.route.items + 3 * z; + const int count = item[2]; + if (count <= 0) return false; + const long long expert = item[0]; + const long long groups = a.k / a.group; + const int table = a.scale.kind == kScaleF32 ? 4 : 2; + a.words += expert * a.n * (static_cast(a.k) * a.bits / 32); + a.scale.p = static_cast(a.scale.p) + expert * a.n * groups * table; + a.bias.p = static_cast(a.bias.p) + expert * a.n * groups * table; + a.route.first = item[1]; + a.m = count; + return true; +} + +__host__ __device__ inline uint32_t affine_code(const uint32_t* row, int k, int bits, int words) { + int bit = k * bits; + int word = bit >> 5; + int shift = bit & 31; + uint32_t low = row[word]; + uint32_t high = (shift + bits > 32 && word + 1 < words) ? row[word + 1] : 0u; + uint32_t value = (low >> shift); + if (shift + bits > 32) value |= high << ((32 - shift) & 31); + return value & ((1u << bits) - 1u); +} + +// Integer code as the BF16 value the product sees. 129 is not exact in BF16. +__host__ __device__ inline float code_bf16(uint32_t code) { + return static_cast(hip_bfloat16(static_cast(code))); +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx_decoder.hpp b/zig/kernels/hip/quant/mlx_decoder.hpp new file mode 100644 index 00000000000..eb9a567e2c5 --- /dev/null +++ b/zig/kernels/hip/quant/mlx_decoder.hpp @@ -0,0 +1,215 @@ +#pragma once + +// The MLX affine WeightDecoder: BITS-wide codes packed little-endian in 32-bit words, a scale and a bias a group of K. + +#include +#include + +#include "common/vec.hpp" +#include "quant/mlx.hpp" +#include "quant/mlx_pieces.hpp" + +namespace tf { +namespace rocm { + +// A table entry's bits as two 16-bit loads valid for every kind; a branch or conversion would stall loads in flight. +using TableBits = unsigned __attribute__((ext_vector_type(2))); + +template +struct MlxDecoder { + using Args = Affine; + static constexpr int kBits = BITS; + // Words of a 32-code chunk of a column. + static constexpr int kWords = BITS; + + // ---- the plan: a routed item's expert and rows ---- + + __device__ static bool take_item(Args& a, int z) { return tf::rocm::take_item(a, z); } + + // ---- a column's codes ---- + + __device__ static const uint32_t* words(const Args& a) { return a.words; } + + // Words of a column's row of K codes, in the integer type the tile does its address arithmetic in. + template + __device__ static Idx row_words(const Args& a) { + return static_cast(a.k) * BITS / 32; + } + + // A chunk is BITS words: 16-byte loads when BITS % 4 == 0 and WIDE, 8-byte when even, else by word. + template + __device__ static void load(const uint32_t* src, uint32_t (&w)[BITS]) { + if constexpr (WIDE && BITS % 4 == 0) { +#pragma unroll + for (int i = 0; i < BITS / 4; ++i) { + const u32x4 v = reinterpret_cast(src)[i]; + w[4 * i] = v.x; + w[4 * i + 1] = v.y; + w[4 * i + 2] = v.z; + w[4 * i + 3] = v.w; + } + } else if constexpr (WIDE && BITS % 2 == 0) { +#pragma unroll + for (int i = 0; i < BITS / 2; ++i) { + const uint2 v = reinterpret_cast(src)[i]; + w[2 * i] = v.x; + w[2 * i + 1] = v.y; + } + } else { +#pragma unroll + for (int i = 0; i < BITS; ++i) w[i] = src[i]; + } + } + + // Two codes (below 256, exact in both types) as the activation type's pair. + template + __device__ static typename T::pair pair_of(uint32_t c0, uint32_t c1) { + if constexpr (std::is_same_v) { + // 0x6400 | c is 1024 + c in FP16; the subtraction is exact. + const uint32_t bits = (c0 | (c1 << 16)) | 0x64006400u; + return __hsub2(__builtin_bit_cast(__half2, bits), __builtin_bit_cast(__half2, 0x64006400u)); + } else { + // The float of an integer below 256 has its low 16 bits clear, so its top half is the BF16. + const uint32_t bits = (__builtin_bit_cast(uint32_t, static_cast(c0)) >> 16) | + (__builtin_bit_cast(uint32_t, static_cast(c1)) & 0xffff0000u); + return __builtin_bit_cast(typename T::pair, bits); + } + } + + // Code t of a chunk as the Dot's element type (codes are below 256, exact in both). + template + __device__ static typename T::elem code(const uint32_t (&w)[BITS], int t) { + if constexpr (std::is_same_v) { + return piece_code(w, t); + } else { + return static_cast(static_cast(piece_bits(w, t))); + } + } + + // Codes t and t + 1 of a chunk, in order, as a pair. + template + __device__ static typename T::pair pair(const uint32_t (&w)[BITS], int t) { + return pair_of(piece_bits(w, t), piece_bits(w, t + 1)); + } + + // ---- the group terms: a scale and a bias a group of a column ---- + + struct Term { + TableBits scale; + TableBits bias; + }; + + __device__ static TableBits table_bits(const GroupTable& t, long long i) { + const uint16_t* p = static_cast(t.p); + const bool wide = t.kind == kScaleF32; + return TableBits{p[wide ? 2 * i : i], p[wide ? 2 * i + 1 : i]}; + } + + __device__ static float table_float(const GroupTable& t, TableBits b) { + if (t.kind == kScaleBF16) return __uint_as_float(b.x << 16); + if (t.kind == kScaleF16) return __half2float(__ushort_as_half(static_cast(b.x))); + return __uint_as_float(b.x | (b.y << 16)); + } + + // The stored scale and bias of group `i` of a table row set (the tile does the row arithmetic). + __device__ static Term term(const Args& a, long long i) { return {table_bits(a.scale, i), table_bits(a.bias, i)}; } + + __device__ static float scale_value(const Args& a, const Term& t) { return table_float(a.scale, t.scale); } + __device__ static float bias_value(const Args& a, const Term& t) { return table_float(a.bias, t.bias); } + + // A group's sum: its dot against the codes times the scale, and the sum of x times the bias. + __device__ static float fold_scale(float acc, float dot, float scale) { return fmaf(dot, scale, acc); } + __device__ static float fold_bias(float acc, float sum_x, float bias) { return fmaf(sum_x, bias, acc); } + + // ---- the decode stream tile: a lane owns a 32-code chunk, its pairs are made with a few bit operations ---- + + // Bytes the chunk's loads are aligned to when they are wide (16 for 4-word multiples, 8 for even, else by word). + static constexpr int kWideBytes = BITS % 4 == 0 ? 16 : BITS % 2 == 0 ? 8 : 4; + + // Whether every chunk of the words is wide-aligned: the words and the row stride are. + __device__ static bool wide_aligned(const Args& a) { + const long long words_row = static_cast(a.k) * BITS / 32; + return ((reinterpret_cast(a.words) | static_cast(words_row * 4)) & (kWideBytes - 1)) == 0; + } + + // The words and tables of side s of a group of products that share x. + template + __device__ static void bind(Args& a, const Sides& sides, int s) { + a.words = sides.words[s]; + a.scale.p = sides.scale[s]; + a.bias.p = sides.bias[s]; + } + + // Codes 16 bits apart in one word when the width divides 16 (the pair is two masked fields), else neighbours. + static constexpr bool kGapPairs = BITS == 2 || BITS == 4 || BITS == 8; + + // The two codes of pair I of a chunk: `lo` and `lo + gap`. + template + static constexpr int lo() { + if constexpr (BITS == 4) return (I >> 2) * 8 + (I & 3); + else if constexpr (BITS == 8) return (I >> 1) * 4 + (I & 1); + else if constexpr (BITS == 2) return (I >> 3) * 16 + (I & 7); + else return 2 * I; + } + + static constexpr int gap() { + if constexpr (BITS == 4) return 4; + else if constexpr (BITS == 8) return 2; + else if constexpr (BITS == 2) return 8; + else return 1; + } + + // Pair I of the chunk's codes as the activation type's pair (the codes are below 256, exact in both types). + template + __device__ static typename T::pair stream_pair(const uint32_t (&w)[BITS]) { + constexpr int low = lo(); + constexpr int high = low + gap(); + uint32_t bits; + if constexpr (kGapPairs) { + constexpr int per = 32 / BITS; + constexpr uint32_t mask = ((1u << BITS) - 1u) * 0x00010001u; + bits = (w[low / per] >> (BITS * (low % per))) & mask; + } else { + bits = piece_bits(w, low) | (piece_bits(w, high) << 16); + } + if constexpr (std::is_same_v) { + bits |= 0x64006400u; + return __hsub2(__builtin_bit_cast(__half2, bits), __builtin_bit_cast(__half2, 0x64006400u)); + } else { + // The float of an integer below 256 has its low 16 bits clear, so its top half is the BF16. + const uint32_t a = __builtin_bit_cast(uint32_t, static_cast(bits & 0xffffu)); + const uint32_t b = __builtin_bit_cast(uint32_t, static_cast(bits >> 16)); + return __builtin_bit_cast(typename T::pair, (a >> 16) | (b & 0xffff0000u)); + } + } + + // The stream tile's group terms: 16-bit BF16 or FP16 table entries, loaded as stored and widened where used. + struct StreamTerms { + const unsigned short* scale; + const unsigned short* bias; + bool half; + + struct Raw { + unsigned short scale; + unsigned short bias; + }; + + __device__ explicit StreamTerms(const Args& a) + : scale(static_cast(a.scale.p)), + bias(static_cast(a.bias.p)), + half(a.scale.kind == kScaleF16) {} + + __device__ unsigned short scale_raw(long long at) const { return scale[at]; } + __device__ unsigned short bias_raw(long long at) const { return bias[at]; } + + __device__ float widen(unsigned short v) const { + return half ? __half2float(__ushort_as_half(v)) : __uint_as_float(static_cast(v) << 16); + } + + __device__ float scale_value(Raw r) const { return widen(r.scale); } + __device__ float bias_value(Raw r) const { return widen(r.bias); } + }; +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx_pieces.hpp b/zig/kernels/hip/quant/mlx_pieces.hpp new file mode 100644 index 00000000000..07c1aa43d0c --- /dev/null +++ b/zig/kernels/hip/quant/mlx_pieces.hpp @@ -0,0 +1,63 @@ +#pragma once + +// MLX affine codes read out of a 32-code piece of a column's row. + +#include + +#include + +#include "quant/mlx.hpp" + +namespace tf { +namespace rocm { + +// 32 codes are exactly BITS words: 16-byte loads when aligned and BITS % 4 == 0, 8-byte for even BITS. +template +__device__ inline void load_piece(const uint32_t* src, uint32_t (&w)[BITS]) { + const uintptr_t at = reinterpret_cast(src); + if constexpr (BITS % 4 == 0) { + if ((at & 15u) == 0) { +#pragma unroll + for (int i = 0; i < BITS / 4; ++i) { + const uint4 v = reinterpret_cast(src)[i]; + w[4 * i] = v.x; + w[4 * i + 1] = v.y; + w[4 * i + 2] = v.z; + w[4 * i + 3] = v.w; + } + return; + } + } + if constexpr (BITS % 2 == 0) { + if ((at & 7u) == 0) { +#pragma unroll + for (int i = 0; i < BITS / 2; ++i) { + const uint2 v = reinterpret_cast(src)[i]; + w[2 * i] = v.x; + w[2 * i + 1] = v.y; + } + return; + } + } +#pragma unroll + for (int i = 0; i < BITS; ++i) w[i] = src[i]; +} + +// Code t of a 32-code piece as FP16. Codes are below 256, exact in BF16 and FP16, so this is code_f16(code). +template +__device__ inline uint32_t piece_bits(const uint32_t (&w)[BITS], int t) { + const int bit = t * BITS; + const int word = bit >> 5; + const int shift = bit & 31; + uint32_t value = w[word] >> shift; + if (shift + BITS > 32) value |= w[word + 1] << (32 - shift); + return value & ((1u << BITS) - 1u); +} + +template +__device__ inline __half piece_code(const uint32_t (&w)[BITS], int t) { + return __ushort2half_rn(static_cast(piece_bits(w, t))); +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/quant/mlx_tiles.hpp b/zig/kernels/hip/quant/mlx_tiles.hpp new file mode 100644 index 00000000000..7dacb30d3e7 --- /dev/null +++ b/zig/kernels/hip/quant/mlx_tiles.hpp @@ -0,0 +1,68 @@ +#pragma once + +// MLX affine kernels: each shared tile over the MLX decoder, identity encoder and Dot, named as the launchers look up. + +#include + +#include "quant/act.hpp" +#include "quant/mlx_decoder.hpp" +#include "tiles/dot2.hpp" +#include "tiles/epilogue.hpp" +#include "tiles/gemm.hpp" +#include "tiles/gemm_kp.hpp" +#include "tiles/matrix_gemm.hpp" +#include "tiles/stream.hpp" + +namespace tf { +namespace rocm { + +// ---- the prefill GEMM tile ---- + +template +__global__ void __launch_bounds__(256) affine_gemm_block(Affine a) { + gemm_tile, IdentityAct, T, F32Out, RT>(a); +} + +// ---- the K-parallel tiles of a short prompt ---- + +template +__global__ void __launch_bounds__(32 * WAVES) affine_gemm_kp(Affine a) { + gemm_kp_tile, IdentityAct, T, F32Out, CB, R, WAVES, RB, LOOP>(a); +} + +// ---- the prefill GEMM tile on the matrix cores of gfx11 ---- + +template +__global__ void __launch_bounds__(256) affine_wmma_gemm(Affine a) { + wmma_gemm_tile, BF16Act, WmmaBF16, F32Out>(a); +} + +// ---- the decode stream tile ---- + +// Up to four products sharing x, K, width and group in one launch; side s owns blocks [first[s], first[s + 1]). +constexpr int kStreamSides = 4; + +struct StreamSides { + const uint32_t* words[kStreamSides]; + const void* scale[kStreamSides]; + const void* bias[kStreamSides]; + void* out[kStreamSides]; + int n[kStreamSides]; + int first[kStreamSides + 1]; + int count; // 0 is the plain product of the Affine + int out_half; + int pair_cols; // > 0: the (gate | up) rows of a stacked product with this many columns each, out is its activation + float limit; // the activation's clamp when above 0 +}; + +// Item z of the plan (or the plain product, or a group's side) at CB columns a lane, R rows; PAIR fuses the activation. +template +__global__ void __launch_bounds__(32 * kStreamWaves) affine_dot2_stream(Affine a, StreamSides sides, int lpc_log2, + int gshift) { + using Epi = std::conditional_t, StreamRound>; + stream_tile, IdentityAct, T, Epi, R, CB>(a, sides, lpc_log2, gshift); +} + + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/dot2.hip b/zig/kernels/hip/tiles/dot2.hip new file mode 100644 index 00000000000..46624c2983d --- /dev/null +++ b/zig/kernels/hip/tiles/dot2.hip @@ -0,0 +1,389 @@ +// FP16 dot2 schedules: the one-thread reference and the column, tiled, split and wide prefill tiles. + +#include "tiles/dot2.hpp" + +#include + +namespace tf { +namespace rocm { + +__device__ __half code_f16(uint32_t code) { + return __float2half_rn(code_bf16(code)); +} + +__global__ void __launch_bounds__(32) affine_dot2_kernel(Affine a) { + int col = blockIdx.x * blockDim.x + threadIdx.x; + int row = blockIdx.y; + if (row >= a.m || col >= a.n) return; + + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + const uint32_t* wrow = a.words + static_cast(col) * words; + const __half* xrow = static_cast(a.x) + static_cast(row) * a.k; + float acc = 0.f; + for (int group = 0; group < groups; ++group) { + float dot = 0.f; + float sum = 0.f; + int base = group * a.group; + for (int t = 0; t < a.group; t += 2) { + __half x0 = xrow[base + t]; + __half x1 = xrow[base + t + 1]; + __half q0 = code_f16(affine_code(wrow, base + t, a.bits, words)); + __half q1 = code_f16(affine_code(wrow, base + t + 1, a.bits, words)); + dot = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), __halves2half2(q0, q1), dot, false); + sum += static_cast(x0); + sum += static_cast(x1); + } + acc = fmaf(dot, a.scale[static_cast(col) * groups + group], acc); + acc = fmaf(sum, a.bias[static_cast(col) * groups + group], acc); + } + a.out[static_cast(row) * a.n + col] = acc; +} + +// Column tile: a thread owns a column and walks a staged K chunk in pair order; scale only after the whole group. +constexpr int kFastM = 8; +constexpr int kFastN = 256; +constexpr int kFastK = 64; +constexpr int kFastLd = 68; + +// fp16(bf16(code)) for every byte. Filled by code_f16 so the product rounding does not change. +__constant__ __half kByteF16[256]; + +__global__ void fill_byte_lut(__half* lut) { + int i = threadIdx.x; + if (i < 256) lut[i] = code_f16(static_cast(i)); +} + +__device__ void store_codes(__half* dst, uint32_t packed) { + dst[0] = kByteF16[packed & 0xffu]; + dst[1] = kByteF16[(packed >> 8) & 0xffu]; + dst[2] = kByteF16[(packed >> 16) & 0xffu]; + dst[3] = kByteF16[packed >> 24]; +} + +// Four packed words per load. An 8-bit group starts on a 16-byte boundary. +__device__ void load_byte_tile(__half* tile, const uint32_t* words, int words_per_row, int n, int n_cols, int tid, + int chunk, int gbase, int k0) { + int vecs = chunk >> 4; + int nvecs = n_cols * vecs; + for (int e = tid; e < nvecs; e += blockDim.x) { + int c = e / vecs; + int v = e - c * vecs; + int gc = blockIdx.x * n_cols + c; + int word = ((gbase + k0) >> 2) + (v << 2); + uint4 packed = make_uint4(0u, 0u, 0u, 0u); + if (gc < n) { + const uint32_t* src = words + static_cast(gc) * words_per_row + word; + packed = *reinterpret_cast(src); + } + int base = c * kFastLd + (v << 4); + store_codes(tile + base, packed.x); + store_codes(tile + base + 4, packed.y); + store_codes(tile + base + 8, packed.z); + store_codes(tile + base + 12, packed.w); + } +} + +// One column's chunk of codes in LDS, a 32-code piece a load; 8-bit keeps the byte path. +template +__device__ void load_piece_tile(__half* tile, const uint32_t* words, int words_per_row, int n, int n_cols, int tid, + int chunk, int gbase, int k0) { + const int pieces = chunk / 32; + for (int e = tid; e < n_cols * pieces; e += blockDim.x) { + const int c = e / pieces; + const int p = e - c * pieces; + const int gc = blockIdx.x * n_cols + c; + __half* dst = tile + c * kFastLd + p * 32; + if (gc >= n) { +#pragma unroll + for (int t = 0; t < 32; ++t) dst[t] = __float2half(0.f); + continue; + } + uint32_t w[BITS]; + load_piece(words + static_cast(gc) * words_per_row + (gbase + k0 + p * 32) / 32 * BITS, w); +#pragma unroll + for (int t = 0; t < 32; ++t) dst[t] = piece_code(w, t); + } +} + +__device__ void load_code_tile(__half* tile, const Affine& a, int words_per_row, int n_cols, int tid, int chunk, + int gbase, int k0) { + switch (a.bits) { + case 2: load_piece_tile<2>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 3: load_piece_tile<3>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 4: load_piece_tile<4>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 5: load_piece_tile<5>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + case 6: load_piece_tile<6>(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + default: load_byte_tile(tile, a.words, words_per_row, a.n, n_cols, tid, chunk, gbase, k0); break; + } +} + +// Prefill tile: each output is still one thread's fdot2 chain in pair order. +constexpr int kDotBM = 16; +constexpr int kDotBN = 16; +constexpr int kDotGroup = 128; + +__global__ void affine_dot2_tiled(Affine a) { + __shared__ __half xs[kDotBM * kDotGroup]; + __shared__ __half ws[kDotBN * kDotGroup]; + int local_row = threadIdx.x / kDotBN; + int local_col = threadIdx.x % kDotBN; + int row = blockIdx.y * kDotBM + local_row; + int col = blockIdx.x * kDotBN + local_col; + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + bool live = row < a.m && col < a.n; + float acc = 0.f; + const __half* x = static_cast(a.x); + + for (int group = 0; group < groups; ++group) { + int base = group * a.group; + int span = kDotBM * a.group; + for (int e = threadIdx.x; e < span; e += blockDim.x) { + int r = e / a.group; + int c = e - r * a.group; + int gr = blockIdx.y * kDotBM + r; + int gk = base + c; + __half xv = __float2half(0.f); + if (gr < a.m && gk < a.k) xv = x[static_cast(gr) * a.k + gk]; + xs[r * a.group + c] = xv; + } + for (int e = threadIdx.x; e < span; e += blockDim.x) { + int r = e / a.group; + int c = e - r * a.group; + int gc = blockIdx.x * kDotBN + r; + int gk = base + c; + __half qv = __float2half(0.f); + if (gc < a.n && gk < a.k) { + const uint32_t* wrow = a.words + static_cast(gc) * words; + qv = code_f16(affine_code(wrow, gk, a.bits, words)); + } + ws[r * a.group + c] = qv; + } + __syncthreads(); + if (live) { + float dot = 0.f; + float sum = 0.f; + const __half* xrow = xs + local_row * a.group; + const __half* wrow = ws + local_col * a.group; + for (int t = 0; t < a.group; t += 2) { + __half x0 = xrow[t]; + __half x1 = xrow[t + 1]; + __half q0 = wrow[t]; + __half q1 = wrow[t + 1]; + dot = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), __halves2half2(q0, q1), dot, false); + sum += static_cast(x0); + sum += static_cast(x1); + } + int g = group; + acc = fmaf(dot, a.scale[static_cast(col) * groups + g], acc); + acc = fmaf(sum, a.bias[static_cast(col) * groups + g], acc); + } + __syncthreads(); + } + if (live) a.out[static_cast(row) * a.n + col] = acc; +} + +// affine_dot2_fast's walk over groups [z * per, (z + 1) * per); affine_dot2_fold applies them in group order. +template +__global__ void __launch_bounds__(kFastN, 1) affine_dot2_span(Affine a, float* partial, int per) { + __shared__ __half xs[Rows * kFastLd]; + __shared__ __half ws[kFastN * kFastLd]; + int tid = threadIdx.x; + int col = blockIdx.x * kFastN + tid; + int row0 = blockIdx.y * kFastM; + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + int chunk = a.group < kFastK ? a.group : kFastK; + int g0 = blockIdx.z * per; + int g1 = g0 + per; + const __half* x = static_cast(a.x); + + for (int group = g0; group < g1; ++group) { + int gbase = group * a.group; + float dot[Rows]; + float sumx[Rows]; +#pragma unroll + for (int m = 0; m < Rows; ++m) { + dot[m] = 0.f; + sumx[m] = 0.f; + } + for (int k0 = 0; k0 < a.group; k0 += chunk) { + if (a.bits == 8) { + load_byte_tile(ws, a.words, words, a.n, kFastN, tid, chunk, gbase, k0); + } else { + int span = kFastN * chunk; + for (int e = tid; e < span; e += kFastN) { + int c = e / chunk; + int kk = e - c * chunk; + int gc = blockIdx.x * kFastN + c; + int gk = gbase + k0 + kk; + __half qv = __float2half(0.f); + if (gc < a.n && gk < a.k) { + const uint32_t* wrow = a.words + static_cast(gc) * words; + qv = code_f16(affine_code(wrow, gk, a.bits, words)); + } + ws[c * kFastLd + kk] = qv; + } + } + int xspan = Rows * chunk; + for (int e = tid; e < xspan; e += kFastN) { + int r = e / chunk; + int kk = e - r * chunk; + int gr = row0 + r; + int gk = gbase + k0 + kk; + __half xv = __float2half(0.f); + if (gr < a.m && gk < a.k) xv = x[static_cast(gr) * a.k + gk]; + xs[r * kFastLd + kk] = xv; + } + __syncthreads(); + if (col < a.n) { + for (int t = 0; t < chunk; t += 2) { + __half2 q = __halves2half2(ws[tid * kFastLd + t], ws[tid * kFastLd + t + 1]); +#pragma unroll + for (int m = 0; m < Rows; ++m) { + __half x0 = xs[m * kFastLd + t]; + __half x1 = xs[m * kFastLd + t + 1]; + dot[m] = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), q, dot[m], false); + sumx[m] += static_cast(x0); + sumx[m] += static_cast(x1); + } + } + } + __syncthreads(); + } + if (col < a.n) { +#pragma unroll + for (int m = 0; m < Rows; ++m) { + int row = row0 + m; + if (row < a.m) { + float* slot = partial + ((static_cast(row) * a.n + col) * groups + group) * 2; + slot[0] = dot[m]; + slot[1] = sumx[m]; + } + } + } + } +} + +__global__ void __launch_bounds__(kFastN) affine_dot2_fold(const float* partial, GroupTable scale, GroupTable bias, + float* out, int m, int n, int groups) { + int col = blockIdx.x * kFastN + threadIdx.x; + int row = blockIdx.y; + if (row >= m || col >= n) return; + const float* base = partial + (static_cast(row) * n + col) * groups * 2; + float acc = 0.f; + for (int group = 0; group < groups; ++group) { + acc = fmaf(base[group * 2], scale[static_cast(col) * groups + group], acc); + acc = fmaf(base[group * 2 + 1], bias[static_cast(col) * groups + group], acc); + } + out[static_cast(row) * n + col] = acc; +} + +// Prefill tile: 128 rows share one load of 32 columns; a thread owns a column and eight rows. +constexpr int kWideM = 128; +constexpr int kWideN = 32; +constexpr int kWideRows = 8; + +__device__ void load_wide_chunk(__half* xs, __half* ws, const Affine& a, int tid, int row_base, int words, + int chunk, int gbase, int k0) { + int vecs = chunk >> 2; + int nvecs = kWideM * vecs; + for (int e = tid; e < nvecs; e += blockDim.x) { + int r = e / vecs; + int v = e - r * vecs; + int kk = v << 2; + int gr = row_base + r; + int gk = gbase + k0 + kk; + uint2 packed = make_uint2(0u, 0u); + if (gr < a.m && gk + 3 < a.k) { + const __half* src = static_cast(a.x) + static_cast(gr) * a.k + gk; + packed = *reinterpret_cast(src); + } + *reinterpret_cast(xs + r * kFastLd + kk) = packed; + } + load_code_tile(ws, a, words, kWideN, tid, chunk, gbase, k0); +} + +__device__ void dot_wide_chunk(float dot[kWideRows], float sumx[kWideRows], const __half* xs, const __half* ws, + int col_local, int row_group, int chunk) { + for (int t = 0; t < chunk; t += 2) { + __half2 q = __halves2half2(ws[col_local * kFastLd + t], ws[col_local * kFastLd + t + 1]); +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + int r = row_group * kWideRows + m; + __half x0 = xs[r * kFastLd + t]; + __half x1 = xs[r * kFastLd + t + 1]; + dot[m] = __builtin_amdgcn_fdot2(__halves2half2(x0, x1), q, dot[m], false); + sumx[m] += static_cast(x0); + sumx[m] += static_cast(x1); + } + } +} + +__global__ void __launch_bounds__(512, 1) affine_dot2_wide(Affine a) { + __shared__ __half xs[2][kWideM * kFastLd]; + __shared__ __half ws[2][kWideN * kFastLd]; + int tid = threadIdx.x; + int col_local = tid % kWideN; + int row_group = tid / kWideN; + int col = blockIdx.x * kWideN + col_local; + int row_base = blockIdx.y * kWideM; + int my_row = row_base + row_group * kWideRows; + int words = a.k * a.bits / 32; + int groups = a.k / a.group; + int chunk = a.group < kFastK ? a.group : kFastK; + int per = a.group / chunk; + int nchunks = groups * per; + float acc[kWideRows]; + float dot[kWideRows]; + float sumx[kWideRows]; +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + acc[m] = 0.f; + dot[m] = 0.f; + sumx[m] = 0.f; + } + if (nchunks > 0) load_wide_chunk(xs[0], ws[0], a, tid, row_base, words, chunk, 0, 0); + __syncthreads(); + + int phase = 0; + for (int ci = 0; ci < nchunks; ++ci) { + int next = phase ^ 1; + if (ci + 1 < nchunks) { + int nci = ci + 1; + int ng = nci / per; + int nk0 = (nci - ng * per) * chunk; + load_wide_chunk(xs[next], ws[next], a, tid, row_base, words, chunk, ng * a.group, nk0); + } + if (col < a.n) dot_wide_chunk(dot, sumx, xs[phase], ws[phase], col_local, row_group, chunk); + if ((ci % per) == per - 1 && col < a.n) { + int group = ci / per; + float scale = a.scale[static_cast(col) * groups + group]; + float biasv = a.bias[static_cast(col) * groups + group]; +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + acc[m] = fmaf(dot[m], scale, acc[m]); + acc[m] = fmaf(sumx[m], biasv, acc[m]); + dot[m] = 0.f; + sumx[m] = 0.f; + } + } + __syncthreads(); + phase = next; + } + if (col < a.n) { +#pragma unroll + for (int m = 0; m < kWideRows; ++m) { + int row = my_row + m; + if (row < a.m) a.out[static_cast(row) * a.n + col] = acc[m]; + } + } +} + +// The split tile's two row counts launches/affine.zig resolves. +template __global__ void affine_dot2_span<1>(Affine, float*, int); +template __global__ void affine_dot2_span(Affine, float*, int); + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/dot2.hpp b/zig/kernels/hip/tiles/dot2.hpp new file mode 100644 index 00000000000..26d3bd4eb42 --- /dev/null +++ b/zig/kernels/hip/tiles/dot2.hpp @@ -0,0 +1,22 @@ +#pragma once + +// The tile constants shared by the dot2 files. + +#include + +#include "common/arch.hpp" +#include "common/dot2.hpp" +#include "quant/mlx.hpp" +#include "quant/mlx_pieces.hpp" + +namespace tf { +namespace rocm { + +constexpr int kLaneCols = 32; +constexpr int kLaneWaves = 8; +constexpr int kLaneRows = 8; +constexpr int kLaneGroupMax = 128; +constexpr int kBlockRows = 64; // from here the GEMM tile beats the 128-row column tile + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/dot2_tiles.hip b/zig/kernels/hip/tiles/dot2_tiles.hip new file mode 100644 index 00000000000..bff70f5f72d --- /dev/null +++ b/zig/kernels/hip/tiles/dot2_tiles.hip @@ -0,0 +1,377 @@ +// Dot2 tiles for every width and both activation types: one row, 2-8 rows, the GEMM tile, and routed plans. + +#include "tiles/dot2.hpp" +#include "tiles/gemm.hpp" +#include "tiles/gemm_kp.hpp" +#include "tiles/stream.hpp" +#include "tiles/matrix_gemm.hpp" +#include "quant/mlx_tiles.hpp" + +namespace tf { +namespace rocm { + +// Groups a wave owns each round. Fewer rows leave room for more loads in flight; at most 16 code words a lane. +constexpr int lane_groups(int bits, int rows, int pieces) { + int per = rows <= 2 ? 4 : rows <= 4 ? 2 : 1; + while (per > 1 && per * pieces * bits > 8) per /= 2; + return per; +} + +template +__global__ void __launch_bounds__(kLaneCols * kLaneWaves) affine_dot2_lanes(Affine a) { + if (!take_item(a, blockIdx.z)) return; + constexpr int kGroup = 32 * PIECES; + constexpr int kPer = lane_groups(BITS, ROWS, PIECES); + constexpr int kRound = kLaneWaves * kPer; + __shared__ typename T::elem xs[ROWS][kRound * kGroup]; + __shared__ float part[kRound][ROWS][2][kLaneCols]; + const int lane = threadIdx.x % kLaneCols; + const int wave = threadIdx.x / kLaneCols; + const int col = blockIdx.x * kLaneCols + lane; + const int groups = a.k / kGroup; + const int words_row = a.k * BITS / 32; + // A lane past N reads the last column and stores nothing, so every lane reaches every barrier. + const uint32_t* wrow = a.words + static_cast(col < a.n ? col : a.n - 1) * words_row; + const typename T::elem* x = static_cast(a.x); + float acc[ROWS]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) acc[r] = 0.f; + + for (int g0 = 0; g0 < groups; g0 += kRound) { + constexpr int kSpan = kRound * kGroup; + for (int e = threadIdx.x; e < ROWS * kSpan; e += blockDim.x) { + const int r = e / kSpan; + const int kk = e - r * kSpan; + const int gk = g0 * kGroup + kk; + xs[r][kk] = (r < a.m && gk < a.k) ? x[x_row(a, r) * a.k + gk] : T::zero(); + } + // 6- and 8-bit lanes load every code word of their groups up front; narrower widths load a piece at a time. + constexpr bool kAhead = BITS >= 6; + uint32_t w[kPer][PIECES][BITS]; + if constexpr (kAhead) { +#pragma unroll + for (int j = 0; j < kPer; ++j) { + const int g = g0 + wave * kPer + j; + if (g < groups) { +#pragma unroll + for (int p = 0; p < PIECES; ++p) load_piece(wrow + (g * PIECES + p) * BITS, w[j][p]); + } + } + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < kPer; ++j) { + const int local = wave * kPer + j; + if (g0 + local >= groups) continue; + float dot[ROWS]; + float sum[ROWS]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + dot[r] = 0.f; + sum[r] = 0.f; + } +#pragma unroll + for (int p = 0; p < PIECES; ++p) { + if constexpr (!kAhead) load_piece(wrow + ((g0 + local) * PIECES + p) * BITS, w[j][p]); + const int xk = local * kGroup + 32 * p; +#pragma unroll + for (int t = 0; t < 32; t += 2) { + const typename T::pair q = T::two(MlxDecoder::template code(w[j][p], t), + MlxDecoder::template code(w[j][p], t + 1)); +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + const typename T::pair xp = T::two(xs[r][xk + t], xs[r][xk + t + 1]); + dot[r] = T::dot(xp, q, dot[r]); + sum[r] += T::lo(xp); + sum[r] += T::hi(xp); + } + } + } +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + part[local][r][0][lane] = dot[r]; + part[local][r][1][lane] = sum[r]; + } + } + __syncthreads(); + if (wave == 0 && col < a.n) { + const int round = groups - g0 < kRound ? groups - g0 : kRound; + for (int j = 0; j < round; ++j) { + const long long at = static_cast(col) * groups + g0 + j; + const float scale = a.scale[at]; + const float bias = a.bias[at]; +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + acc[r] = fmaf(part[j][r][0][lane], scale, acc[r]); + acc[r] = fmaf(part[j][r][1][lane], bias, acc[r]); + } + } + } + // The next round restages xs: wave 0's fold above only reads part. + } + if (wave == 0 && col < a.n) { +#pragma unroll + for (int r = 0; r < ROWS; ++r) { + if (r >= a.m) continue; + if (a.out16 != nullptr) { + a.out16[out_row(a, r) * a.n + col] = __float2half_rn(acc[r]); + } else { + a.out[out_row(a, r) * a.n + col] = acc[r]; + } + } + } +} + +// One-row tile: a lane owns a group, so a wave reads a weight row contiguously; lane c folds column c in order. +constexpr int kRowWaves = 4; +constexpr int kRowCols = 32; + +template +__global__ void __launch_bounds__(32 * kRowWaves) affine_dot2_row(Affine a, int lpc) { + if (!take_item(a, blockIdx.z)) return; + constexpr int kGroup = 32 * PIECES; + __shared__ float dots[kRowWaves][kRowCols][33]; + __shared__ float sums[kRowWaves][32]; + const int lane = threadIdx.x & 31; + const int wave = threadIdx.x >> 5; + const int slots = 32 / lpc; // columns a pass + const int slot = lane / lpc; + const int j = lane % lpc; + const int col0 = (blockIdx.x * kRowWaves + wave) * kRowCols; + const int mine = col0 + lane; // the column this lane folds + const int groups = a.k / kGroup; + const long long words_row = static_cast(a.k) * BITS / 32; + const typename T::pair* x = reinterpret_cast( + static_cast(a.x) + x_row(a, 0) * a.k); + float acc = 0.f; + for (int g0 = 0; g0 < groups; g0 += lpc) { + const int g = g0 + j; + const bool live = g < groups; + typename T::pair xv[PIECES * 16]; + float sum = 0.f; +#pragma unroll + for (int i = 0; i < PIECES * 16; ++i) { + xv[i] = live ? x[g * (kGroup / 2) + i] : T::two(T::zero(), T::zero()); + sum += T::lo(xv[i]); + sum += T::hi(xv[i]); + } + if (slot == 0) sums[wave][j] = sum; +#pragma unroll 2 + for (int pass = 0; pass < kRowCols / slots; ++pass) { + const int c = pass * slots + slot; + const int col = col0 + c; + float dot = 0.f; + if (live && col < a.n) { + const uint32_t* wrow = a.words + static_cast(col) * words_row + + static_cast(g) * PIECES * BITS; +#pragma unroll + for (int p = 0; p < PIECES; ++p) { + uint32_t w[BITS]; + load_piece(wrow + p * BITS, w); +#pragma unroll + for (int t = 0; t < 32; t += 2) { + const typename T::pair q = + T::two(MlxDecoder::template code(w, t), MlxDecoder::template code(w, t + 1)); + dot = T::dot(xv[p * 16 + t / 2], q, dot); + } + } + } + dots[wave][c][j] = dot; + } + __syncthreads(); + if (mine < a.n) { + const int round = groups - g0 < lpc ? groups - g0 : lpc; + for (int i = 0; i < round; ++i) { + const long long at = static_cast(mine) * groups + g0 + i; + acc = fmaf(dots[wave][lane][i], a.scale[at], acc); + acc = fmaf(sums[wave][i], a.bias[at], acc); + } + } + __syncthreads(); + } + if (mine < a.n) { + if (a.out16 != nullptr) { + a.out16[out_row(a, 0) * a.n + mine] = __float2half_rn(acc); + } else { + a.out[out_row(a, 0) * a.n + mine] = acc; + } + } +} + +// GEMM tile: 128 x 128, a thread 8 rows x 8 columns strided by 16, K through double-buffered LDS 32 codes a stage. +constexpr int kBlockM = 128; +constexpr int kBlockN = 128; +constexpr int kBlockK = 32; +constexpr int kBlockLd = kBlockK + 2; // 17 words a row: the 16 column threads of a wave read 16 banks + +template +__device__ inline void stage_block(typename T::elem* xs, typename T::elem* ws, const Affine& a, int m0, int n0, int k0, + int words_row) { + const typename T::elem* x = static_cast(a.x); + // x: 128 rows x 32 halves, 16 halves (two 16-byte loads) a thread. + { + const int r = threadIdx.x >> 1; + const int half = (threadIdx.x & 1) * 16; + const int gr = m0 + r; + uint4 lo = make_uint4(0u, 0u, 0u, 0u); + uint4 hi = lo; + if (gr < a.m) { + const uint4* src = reinterpret_cast(x + x_row(a, gr) * a.k + k0 + half); + lo = src[0]; + hi = src[1]; + } + uint32_t* dst = reinterpret_cast(xs + r * kBlockLd + half); + dst[0] = lo.x; dst[1] = lo.y; dst[2] = lo.z; dst[3] = lo.w; + dst[4] = hi.x; dst[5] = hi.y; dst[6] = hi.z; dst[7] = hi.w; + } + // Codes: one 32-code piece a column, threads 0..127. + if (threadIdx.x < kBlockN) { + const int c = threadIdx.x; + const int gc = n0 + c; + typename T::elem* dst = ws + c * kBlockLd; + if (gc < a.n) { + uint32_t w[BITS]; + load_piece(a.words + static_cast(gc) * words_row + k0 / 32 * BITS, w); +#pragma unroll + for (int t = 0; t < 32; t += 2) { + *reinterpret_cast(dst + t) = + T::two(MlxDecoder::template code(w, t), MlxDecoder::template code(w, t + 1)); + } + } else { +#pragma unroll + for (int t = 0; t < 32; t += 2) { + *reinterpret_cast(dst + t) = T::two(T::zero(), T::zero()); + } + } + } +} + +template +__global__ void __launch_bounds__(256, 1) affine_dot2_block(Affine a) { + if (!take_item(a, blockIdx.z)) return; + if (static_cast(blockIdx.y) * kBlockM >= a.m) return; + __shared__ typename T::elem xs[2][kBlockM * kBlockLd]; + __shared__ typename T::elem ws[2][kBlockN * kBlockLd]; + const int tx = threadIdx.x & 15; + const int ty = threadIdx.x >> 4; + const int m0 = blockIdx.y * kBlockM; + const int n0 = blockIdx.x * kBlockN; + const int words_row = a.k * BITS / 32; + const int groups = a.k / a.group; + const int stages = a.k / kBlockK; + const int per = a.group / kBlockK; + float acc[8][8]; + float dot[8][8]; + float sumx[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + sumx[i] = 0.f; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc[i][j] = 0.f; + dot[i][j] = 0.f; + } + } + stage_block(xs[0], ws[0], a, m0, n0, 0, words_row); + __syncthreads(); + for (int s = 0; s < stages; ++s) { + const int cur = s & 1; + if (s + 1 < stages) stage_block(xs[cur ^ 1], ws[cur ^ 1], a, m0, n0, (s + 1) * kBlockK, words_row); + const typename T::elem* xb = xs[cur]; + const typename T::elem* wb = ws[cur]; +#pragma unroll 4 + for (int t = 0; t < kBlockK; t += 2) { + typename T::pair xv[8]; + typename T::pair wv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + xv[i] = *reinterpret_cast(xb + (ty + 16 * i) * kBlockLd + t); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + wv[j] = *reinterpret_cast(wb + (tx + 16 * j) * kBlockLd + t); + } +#pragma unroll + for (int i = 0; i < 8; ++i) { +#pragma unroll + for (int j = 0; j < 8; ++j) dot[i][j] = T::dot(xv[i], wv[j], dot[i][j]); + sumx[i] += T::lo(xv[i]); + sumx[i] += T::hi(xv[i]); + } + } + if (s % per == per - 1) { + const int g = s / per; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int col = n0 + tx + 16 * j; + const long long at = static_cast(col < a.n ? col : 0) * groups + g; + const float scale = a.scale[at]; + const float bias = a.bias[at]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + acc[i][j] = fmaf(dot[i][j], scale, acc[i][j]); + acc[i][j] = fmaf(sumx[i], bias, acc[i][j]); + dot[i][j] = 0.f; + } + } +#pragma unroll + for (int i = 0; i < 8; ++i) sumx[i] = 0.f; + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = m0 + ty + 16 * i; + if (row >= a.m) continue; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int col = n0 + tx + 16 * j; + if (col < a.n) a.out[out_row(a, row) * a.n + col] = acc[i][j]; + } + } +} + +// The kernels launches/affine.zig resolves, for the build's activation type: bf16 where the GPU has its dot2. +#if TF_DOT2_BF16 +using Dot = DotBF16; +#else +using Dot = DotF16; +#endif + +#define TF_LANES(BITS, ROWS) \ + template __global__ void affine_dot2_lanes(Affine); \ + template __global__ void affine_dot2_lanes(Affine); \ + template __global__ void affine_dot2_lanes(Affine); +#define TF_STREAM(BITS, R, CB) \ + template __global__ void affine_dot2_stream(Affine, StreamSides, int, int); \ + template __global__ void affine_dot2_stream(Affine, StreamSides, int, int); +#if TF_MATRIX +#define TF_WMMA(BITS) template __global__ void affine_wmma_gemm(Affine); +#else +#define TF_WMMA(BITS) +#endif +#define TF_TILES(BITS) \ + template __global__ void affine_dot2_block(Affine); \ + template __global__ void affine_gemm_block::rt>(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_gemm_kp(Affine); \ + template __global__ void affine_dot2_row(Affine, int); \ + template __global__ void affine_dot2_row(Affine, int); \ + template __global__ void affine_dot2_row(Affine, int); \ + TF_LANES(BITS, 1) TF_LANES(BITS, 2) TF_LANES(BITS, 4) TF_LANES(BITS, kLaneRows) \ + TF_STREAM(BITS, 1, 2) TF_STREAM(BITS, 1, 4) TF_STREAM(BITS, 1, 8) \ + TF_STREAM(BITS, 2, 2) TF_STREAM(BITS, 2, 4) TF_STREAM(BITS, 2, 8) \ + TF_STREAM(BITS, 4, 2) TF_STREAM(BITS, 4, 4) \ + TF_WMMA(BITS) + +TF_TILES(2) +TF_TILES(3) +TF_TILES(4) +TF_TILES(5) +TF_TILES(6) +TF_TILES(8) + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/epilogue.hpp b/zig/kernels/hip/tiles/epilogue.hpp new file mode 100644 index 00000000000..6b818c008cc --- /dev/null +++ b/zig/kernels/hip/tiles/epilogue.hpp @@ -0,0 +1,86 @@ +#pragma once + +// Epilogues: what a tile does with finished sums; GEMM tiles hand one fp32 value, the stream tile a lane's columns. + +#include + +#include + +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +// The product in fp32 at its (row, col) of out, the plan's pair row for a routed item. +struct F32Out { + template + __device__ static void store(const Args& a, int row, int col, float v) { + a.out[out_row(a, row) * a.n + col] = v; + } +}; + +// A float as the activation type, rounded to nearest even. +template +__device__ inline typename T::elem narrow(float v) { + if constexpr (std::is_same_v) { + return __float2half_rn(v); + } else { + const uint32_t u = __float_as_uint(v); + const uint32_t bits = v != v ? 0x7fc0u : (u + (((u >> 16) & 1u) + 0x7fffu)) >> 16; + return __builtin_bit_cast(typename T::elem, static_cast(bits)); + } +} + +// A float product rounded to T: FP16 is one rounding of the exact product (fma, zero addend), never fp32 then FP16. +template +__device__ inline typename T::elem narrow_product(float a, float b) { + if constexpr (std::is_same_v) { + uint32_t bits; + asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(bits) : "v"(a), "v"(b)); + return __builtin_bit_cast(typename T::elem, static_cast(bits)); + } else { + return narrow(a * b); + } +} + +// silu(gate) * up in the activation type, both clamped by limit first when it is above 0 (moe_act_kernel's arithmetic). +template +__device__ inline typename T::elem swiglu(float g, float u, float limit) { + if (limit > 0.f) { + g = fminf(g, limit); + u = fminf(fmaxf(u, -limit), limit); + } + return narrow_product(g / (1.f + expf(-g)), u); +} + +// Stream tile epilogues take a lane's CB column sums for one row (`v`), their column `c` and the paired output width. + +// The sum rounded to the activation type where `out16` is set (the decode tails' own rounding), else stored in fp32. +template +struct StreamRound { + static constexpr bool kPair = false; + + template + __device__ static void put(const Args& a, long long row, int col, const float (&v)[CB], int c, int, float) { + if (a.out16 != nullptr) { + static_cast(static_cast(a.out16))[row * a.n + col] = narrow(v[c]); + } else { + a.out[row * a.n + col] = v[c]; + } + } +}; + +// A lane's columns are CB / 2 gate columns and the same up columns; out is silu(gate) * up in T, `pair_cols` wide. +template +struct StreamSwiglu { + static constexpr bool kPair = true; + + template + __device__ static void put(const Args& a, long long row, int col, const float (&v)[CB], int c, int pair_cols, float limit) { + constexpr int CH = CB / 2; + static_cast(static_cast(a.out16))[row * pair_cols + col] = swiglu(v[c], v[c + CH], limit); + } +}; + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/gemm.hpp b/zig/kernels/hip/tiles/gemm.hpp new file mode 100644 index 00000000000..de673cf5266 --- /dev/null +++ b/zig/kernels/hip/tiles/gemm.hpp @@ -0,0 +1,248 @@ +#pragma once + +// Dot2 prefill GEMM (m >= 64), 128 x 128 a block: bit for bit affine_dot2_block's per-group dot2 chain and fma fold. + +#include +#include + +#include "common/dot2.hpp" +#include "common/vec.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +constexpr int kGemmM = 128; +constexpr int kGemmN = 128; +constexpr int kGemmK = 32; +constexpr int kGemmLd = kGemmK + 8; // 20 words a row: 16-byte aligned, eight 16-byte readers hit eight bank groups + +// Rows of x a lane keeps: 16 where dot2 takes x from a quad lane by DPP (RDNA2 FP16), 8 where it has none (gfx11 BF16). +template +struct GemmShape { + static constexpr int rt = 16; +}; + +template <> +struct GemmShape { + static constexpr int rt = 8; +}; + +// One 128 x 128 block of y = x . W^T: Dec reads weights and group terms, Act the rows of x, T multiplies, Epi stores. +template +__device__ __forceinline__ void gemm_tile(typename Dec::Args& a) { + if (!Dec::take_item(a, blockIdx.z)) return; + const int bx = blockIdx.x, by = blockIdx.y; + if (by * kGemmM >= a.m) return; + using pair = typename T::pair; + constexpr int kLdw = kGemmLd / 2; + __shared__ __attribute__((aligned(16))) uint32_t xs[2][kGemmM * kLdw]; + __shared__ __attribute__((aligned(16))) uint32_t ws[2][kGemmN * kLdw]; + __shared__ float sx[2][kGemmM]; + // The last three groups' scales and biases: bias lags scale a stage, so a slow wave reads an older group. + __shared__ float sc[3][kGemmN]; + __shared__ float bi[3][kGemmN]; + + const int tid = threadIdx.x; + const int m0 = by * kGemmM; + const int n0 = bx * kGemmN; + const int words_row = Dec::template row_words(a); + const int groups = a.k / a.group; + const int stages = a.k / kGemmK; + const int per = a.group / kGemmK; + const int line = tid & (kGemmN - 1); + const int side = __builtin_amdgcn_readfirstlane(tid >> 7); // codes 16 * side ..; side 1 also stages x + + // This thread's column of codes and half a row of x; past the edge it reads the last column or first row, unused. + const int col_s = n0 + line < a.n ? n0 + line : a.n - 1; + const uint32_t* wsrc = Dec::words(a) + static_cast(col_s) * words_row; + const int xrow = tid >> 1; + const int xhalf = tid & 1; + // Rows past the end are not loaded, stored or summed: a stager wave has 16 rows, a summer 32: whole waves skip. + const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const bool xlive = wave * 16 < a.m - m0; + const bool sxlive = (line & ~31) < a.m - m0; + const int row_s = m0 + xrow < a.m ? m0 + xrow : 0; + const typename Act::elem* xrow_ptr = Act::row(a, row_s); + const u32x4* xsrc = reinterpret_cast(xrow_ptr); + + // Two stages a fetch: a row's 64 bytes of x in each (two lanes: one 128-byte request), a column's two code pieces. + uint32_t wreg[2][Dec::kWords]; + u32x4 xreg[4]; + typename Dec::Term term[2]; + float run = 0.f; + + // Every thread issues the same loads, so none waits on a branch. A stage past the last repeats it. + auto fetch = [&](int st0) { + const int st1 = st0 + 1 < stages ? st0 + 1 : stages - 1; + const int st = st0 < stages ? st0 : stages - 1; + Dec::template load(wsrc + st * Dec::kWords, wreg[0]); + Dec::template load(wsrc + st1 * Dec::kWords, wreg[1]); + const int sx_ = xhalf ? st1 : st; + if (xlive) { +#pragma unroll + for (int v = 0; v < 4; ++v) xreg[v] = xsrc[sx_ * 4 + v]; + } + const long long base = static_cast(col_s) * groups; + term[0] = Dec::term(a, base + st / per); + term[1] = Dec::term(a, base + st1 / per); + }; + // Stage st (parity J) from `buf`: this thread's 16 codes, its row of x if any, and scale and bias at a group's end. + auto stash = [&](std::integral_constant, int st, int buf) { + u32x4* dst = reinterpret_cast(ws[buf] + line * kLdw + side * 8); + auto decode = [&](std::integral_constant) { +#pragma unroll + for (int v = 0; v < 2; ++v) { + uint32_t d[4]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const int t = S * 16 + v * 8 + h * 2; + d[h] = __builtin_bit_cast(uint32_t, Dec::template pair(wreg[J], t)); + } + dst[v] = u32x4{d[0], d[1], d[2], d[3]}; + } + }; + if (side == 0) decode(std::integral_constant{}); else decode(std::integral_constant{}); + if (xhalf == J && xlive) { + u32x4* xdst = reinterpret_cast(xs[buf] + xrow * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) xdst[v] = xreg[v]; + } + if (side == 0 && st % per == per - 1) { + sc[(st / per) % 3][line] = Dec::scale_value(a, term[J]); + bi[(st / per) % 3][line] = Dec::bias_value(a, term[J]); + } + }; + // Side 1 sums a row's x of the stage in LDS, lo then hi of each pair in order, on through the group. + auto sumx = [&](int st, int buf) { + if (st % per == 0) run = 0.f; + const u32x4* src = reinterpret_cast(xs[buf] + line * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 u = src[v]; + const uint32_t q[4] = {u.x, u.y, u.z, u.w}; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const pair p = __builtin_bit_cast(pair, q[h]); + run += T::lo(p); + run += T::hi(p); + } + } + if (st % per == per - 1) sx[(st / per) & 1][line] = run; + }; + + // A wave owns 16 rows, 128 columns; at RT = 8 lanes 0-15 take rows 0-7, 16-31 rows 8-15; x rows come by quad DPP. + constexpr int CT = 64 / RT; + const int lane = tid & 31; + // With 3 groups or fewer live, odd blocks rotate groups by 2 waves so a WGP's two blocks keep all four SIMDs busy. + const int rg = (wave + ((a.m - m0 <= 48 && (bx & 1)) ? 6 : 0)) & 7; + const bool live = rg * 16 < a.m - m0; + const int hrow = RT == 8 ? (lane >> 4) * 8 : 0; + constexpr int kCStride = RT == 8 ? 16 : 32; + const int cbase = RT == 8 ? lane & 15 : lane; + float acc[RT][CT]; + float dot[RT][CT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { +#pragma unroll + for (int j = 0; j < CT; ++j) { + acc[r][j] = 0.f; + dot[r][j] = 0.f; + } + } + // A group's bias terms lag its scale terms a stage; acc is untouched until the next scale term, keeping fma order. + auto apply_bias = [&](int slot, int g) { + float s_x[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) s_x[r] = sx[g][rg * 16 + hrow + r]; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const float bias = bi[slot][cbase + kCStride * j]; +#pragma unroll + for (int r = 0; r < RT; ++r) acc[r][j] = Dec::fold_bias(acc[r][j], s_x[r], bias); + } + }; + fetch(0); + stash(std::integral_constant{}, 0, 0); + __syncthreads(); + // Two stages a trip so a stage's buffer and parity are known when the code is built. + auto step = [&](std::integral_constant, int s) { + constexpr int cur = P; + if (live && s > 0 && (s - 1) % per == per - 1) apply_bias(((s - 1) / per) % 3, ((s - 1) / per) & 1); + if constexpr (P == 1) fetch(s + 1); + if (live) { + constexpr int kXRegs = RT / 4; // x words (4 pairs each) a lane loads a chunk + const uint32_t* xb = xs[cur] + (rg * 16 + hrow + (lane & 3)) * kLdw; + const uint32_t* wb = ws[cur] + cbase * kLdw; + u32x4 xr[2][kXRegs]; + u32x4 wr[2][CT]; + auto load = [&](int c, u32x4 (&xo)[kXRegs], u32x4 (&wo)[CT]) { +#pragma unroll + for (int k = 0; k < kXRegs; ++k) xo[k] = *reinterpret_cast(xb + 4 * k * kLdw + c * 4); +#pragma unroll + for (int j = 0; j < CT; ++j) wo[j] = *reinterpret_cast(wb + kCStride * j * kLdw + c * 4); + }; + load(0, xr[0], wr[0]); +#pragma unroll + for (int c = 0; c < kGemmK / 8; ++c) { + if (c + 1 < kGemmK / 8) load(c + 1, xr[(c + 1) & 1], wr[(c + 1) & 1]); +#pragma unroll + for (int q = 0; q < 4; ++q) { + uint32_t wq[CT]; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const u32x4 u = wr[c & 1][j]; + wq[j] = q == 0 ? u.x : q == 1 ? u.y : q == 2 ? u.z : u.w; + } +#pragma unroll + for (int k = 0; k < kXRegs; ++k) { + const u32x4 u = xr[c & 1][k]; + const uint32_t xq = q == 0 ? u.x : q == 1 ? u.y : q == 2 ? u.z : u.w; + [&](std::integer_sequence) { + (([&] { +#pragma unroll + for (int j = 0; j < CT; ++j) { + dot[4 * k + I][j] = T::template quad(xq, wq[j], dot[4 * k + I][j]); + } + }()), + ...); + }(std::make_integer_sequence{}); + } + } + } + if (s % per == per - 1) { + const int g = (s / per) % 3; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const float scale = sc[g][cbase + kCStride * j]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + acc[r][j] = Dec::fold_scale(acc[r][j], dot[r][j], scale); + dot[r][j] = 0.f; + } + } + } + } + if (side == 1 && sxlive) sumx(s, cur); + stash(std::integral_constant{}, s + 1, cur ^ 1); + __syncthreads(); + }; + for (int s = 0; s < stages; s += 2) { + step(std::integral_constant{}, s); + if (s + 1 < stages) step(std::integral_constant{}, s + 1); + } + if (live && (stages - 1) % per == per - 1) apply_bias(((stages - 1) / per) % 3, ((stages - 1) / per) & 1); +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int row = m0 + rg * 16 + hrow + r; + if (row >= a.m) continue; +#pragma unroll + for (int j = 0; j < CT; ++j) { + const int col = n0 + cbase + kCStride * j; + if (col < a.n) Epi::store(a, row, col, acc[r][j]); + } + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/gemm_kp.hpp b/zig/kernels/hip/tiles/gemm_kp.hpp new file mode 100644 index 00000000000..d759c7da59f --- /dev/null +++ b/zig/kernels/hip/tiles/gemm_kp.hpp @@ -0,0 +1,178 @@ +#pragma once + +// Few-row prefill GEMM, a lane a column's group: outputs match affine_gemm_block bit for bit (same chains, fold order). + +#include "common/dot2.hpp" +#include "tiles/gemm.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +// The lanes a column takes, a group each: 32, or 16 or 8 when it has few groups (a wave then takes more columns). +__host__ __device__ inline int kp_lanes(int groups) { return groups > 16 ? 32 : groups > 8 ? 16 : 8; } + +// CB columns a lane, R rows a pass, WAVES waves a block; passes span <= RB adjacent row blocks to share weights. +template +__device__ __forceinline__ void gemm_kp_tile(typename Dec::Args& a) { + const int blocks = (a.m + R - 1) / R < RB ? (a.m + R - 1) / R : RB; // of the launch: a routed item has its own rows + if (!Dec::take_item(a, blockIdx.z)) return; + constexpr int NO = R * CB; // outputs of a lane set + constexpr int PS = NO + 1; + constexpr int OPL = (4 * NO + 31) / 32; // outputs a lane folds, at most + const int groups = a.k / a.group; + const int gp = kp_lanes(groups); // the lanes of a set; a wave has 32 / gp sets + const int sets = 32 / gp; + const int colw = ((blockIdx.x / blocks) * WAVES + (threadIdx.x >> 5)) * CB * sets; + if (colw >= a.n) return; + __shared__ float part[WAVES][32][PS]; + __shared__ float spart[WAVES][32][R + 1]; + __shared__ float scl[WAVES][32][CB + 1]; + __shared__ float bil[WAVES][32][CB + 1]; + + const int lane = threadIdx.x & 31; + const int wave = threadIdx.x >> 5; + const int per = a.group / 32; + const int rounds = (groups + gp - 1) / gp; + const int gi = lane & (gp - 1); + const int col0 = colw + (lane / gp) * CB; // this lane's columns + const long long words_row = Dec::template row_words(a); + const uint32_t* wsrc[CB]; + long long tb[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + const int col = col0 + c < a.n ? col0 + c : a.n - 1; + wsrc[c] = Dec::words(a) + col * words_row; + tb[c] = static_cast(col) * groups; + } + auto pass = [&](int row0) { + const typename Act::elem* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = Act::row(a, row0 + r < a.m ? row0 + r : 0); + float acc[OPL]; +#pragma unroll + for (int t = 0; t < OPL; ++t) acc[t] = 0.f; + + // Stage s of group g's code words for every column, plus its scale and bias (groups past the last repeat it). + uint32_t w[CB][Dec::kWords]; + uint32_t wn[CB][Dec::kWords]; + typename Dec::Term term[CB]; + auto fetch = [&](uint32_t (&dst)[CB][Dec::kWords], int g, int s) { + const int gl = g < groups ? g : groups - 1; +#pragma unroll + for (int c = 0; c < CB; ++c) Dec::template load(wsrc[c] + (static_cast(gl) * per + s) * Dec::kWords, dst[c]); + }; + auto tables = [&](int g) { + const int gl = g < groups ? g : groups - 1; +#pragma unroll + for (int c = 0; c < CB; ++c) term[c] = Dec::term(a, tb[c] + gl); + }; + fetch(w, gi, 0); + tables(gi); + for (int round = 0; round < rounds; ++round) { + const int g = round * gp + gi; + const int gl = g < groups ? g : groups - 1; + float d[R][CB]; + float sx[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + sx[r] = 0.f; +#pragma unroll + for (int c = 0; c < CB; ++c) d[r][c] = 0.f; + } + for (int s = 0; s < per; ++s) { + // the next stage's loads (the next round's first) go out before this stage's dots + if (s + 1 < per) fetch(wn, g, s + 1); + else if (round + 1 < rounds) fetch(wn, g + gp, 0); + typename T::pair wd[CB][16]; +#pragma unroll + for (int c = 0; c < CB; ++c) { +#pragma unroll + for (int i = 0; i < 16; ++i) { + wd[c][i] = Dec::template pair(w[c], 2 * i); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) { + const u32x4* src = reinterpret_cast(xr[r] + static_cast(gl) * a.group + s * 32); + uint32_t xn[16]; +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 u = src[v]; + xn[4 * v] = u.x; + xn[4 * v + 1] = u.y; + xn[4 * v + 2] = u.z; + xn[4 * v + 3] = u.w; + } + float run = sx[r]; +#pragma unroll + for (int i = 0; i < 16; ++i) { + const typename T::pair xp = __builtin_bit_cast(typename T::pair, xn[i]); + run += T::lo(xp); + run += T::hi(xp); + } + sx[r] = run; +#pragma unroll + for (int i = 0; i < 16; ++i) { + const typename T::pair xp = __builtin_bit_cast(typename T::pair, xn[i]); +#pragma unroll + for (int c = 0; c < CB; ++c) d[r][c] = T::dot(xp, wd[c][i], d[r][c]); + } + } +#pragma unroll + for (int c = 0; c < CB; ++c) { +#pragma unroll + for (int i = 0; i < Dec::kWords; ++i) w[c][i] = wn[c][i]; + } + } + // this group's results to LDS, then the round's groups in order +#pragma unroll + for (int r = 0; r < R; ++r) { + spart[wave][lane][r] = sx[r]; +#pragma unroll + for (int c = 0; c < CB; ++c) part[wave][lane][r * CB + c] = d[r][c]; + } +#pragma unroll + for (int c = 0; c < CB; ++c) { + scl[wave][lane][c] = Dec::scale_value(a, term[c]); + bil[wave][lane][c] = Dec::bias_value(a, term[c]); + } + if (round + 1 < rounds) tables(g + gp); + __syncwarp(); + const int count = groups - round * gp < gp ? groups - round * gp : gp; +#pragma unroll + for (int t = 0; t < OPL; ++t) { + const int os = lane + 32 * t; + if (os >= NO * sets) continue; + const int base = (os / NO) * gp; // the first lane of the output's set + const int o = os % NO; + const int r = o / CB; + const int c = o % CB; + float v = acc[t]; + for (int gg = 0; gg < count; ++gg) { + v = Dec::fold_scale(v, part[wave][base + gg][o], scl[wave][base + gg][c]); + v = Dec::fold_bias(v, spart[wave][base + gg][r], bil[wave][base + gg][c]); + } + acc[t] = v; + } + __syncwarp(); + } +#pragma unroll + for (int t = 0; t < OPL; ++t) { + const int os = lane + 32 * t; + if (os >= NO * sets) continue; + const int o = os % NO; + const int row = row0 + o / CB; + const int col = colw + (os / NO) * CB + o % CB; + if (row < a.m && col < a.n) Epi::store(a, row, col, acc[t]); + } + }; + if constexpr (LOOP) { + for (int row0 = (blockIdx.x % blocks) * R; row0 < a.m; row0 += blocks * R) pass(row0); + } else { + pass((blockIdx.x % blocks) * R); + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/matrix_gemm.hpp b/zig/kernels/hip/tiles/matrix_gemm.hpp new file mode 100644 index 00000000000..80ec172c839 --- /dev/null +++ b/zig/kernels/hip/tiles/matrix_gemm.hpp @@ -0,0 +1,209 @@ +#pragma once + +// gfx11 WMMA prefill GEMM (BF16, m >= 16): codes are exact in BF16, so WMMA sums match the dot2 chain bit for bit. + +#include "common/wmma.hpp" +#include "tiles/gemm.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +// Dec reads the words and group terms, Act the rows of x, T (a matrix-core Dot) multiplies and Epi stores. +template +__device__ __forceinline__ void wmma_gemm_tile(typename Dec::Args& a) { +#if TF_DEVICE_WMMA_GFX11 + if (!Dec::take_item(a, blockIdx.z)) return; + const int bx = blockIdx.x; + const int m0 = blockIdx.y * kGemmM; + if (m0 >= a.m) return; + constexpr int kLdw = kGemmLd / 2; + __shared__ __attribute__((aligned(16))) uint32_t xs[2][kGemmM * kLdw]; + __shared__ __attribute__((aligned(16))) uint32_t ws[2][kGemmN * kLdw]; + __shared__ float sx[2][kGemmM]; + __shared__ float sc[3][kGemmN]; + __shared__ float bi[3][kGemmN]; + + const int tid = threadIdx.x; + const int n0 = bx * kGemmN; + const int words_row = Dec::template row_words(a); + const int groups = a.k / a.group; + const int stages = a.k / kGemmK; + const int per = a.group / kGemmK; + const int rows_left = a.m - m0; + const int line = tid & (kGemmN - 1); + const int side = __builtin_amdgcn_readfirstlane(tid >> 7); + const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const int lane = tid & 31; + + // Staging as in gemm_tile: half a column's codes and half a row of x a thread, two stages a fetch. + const int col_s = n0 + line < a.n ? n0 + line : a.n - 1; + const uint32_t* wsrc = Dec::words(a) + static_cast(col_s) * words_row; + const int xrow = tid >> 1; + const int xhalf = tid & 1; + const bool xlive = wave * 16 < rows_left; + const bool sums = side == 1 && (line & ~31) < rows_left; + const int row_s = m0 + xrow < a.m ? m0 + xrow : 0; + const typename Act::elem* xrow_ptr = Act::row(a, row_s); + const u32x4* xsrc = reinterpret_cast(xrow_ptr); + uint32_t wreg[2][Dec::kWords]; + u32x4 xreg[4]; + typename Dec::Term term[2]; + float run = 0.f; + auto fetch = [&](int st0) { + const int st1 = st0 + 1 < stages ? st0 + 1 : stages - 1; + const int st = st0 < stages ? st0 : stages - 1; + Dec::template load(wsrc + st * Dec::kWords, wreg[0]); + Dec::template load(wsrc + st1 * Dec::kWords, wreg[1]); + const int sx_ = xhalf ? st1 : st; + if (xlive) { +#pragma unroll + for (int v = 0; v < 4; ++v) xreg[v] = xsrc[sx_ * 4 + v]; + } + const long long base = static_cast(col_s) * groups; + term[0] = Dec::term(a, base + st / per); + term[1] = Dec::term(a, base + st1 / per); + }; + auto stash = [&](std::integral_constant, int st, int buf) { + u32x4* dst = reinterpret_cast(ws[buf] + line * kLdw + side * 8); + auto decode = [&](std::integral_constant) { +#pragma unroll + for (int v = 0; v < 2; ++v) { + uint32_t d[4]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const int t = S * 16 + v * 8 + h * 2; + d[h] = __builtin_bit_cast(uint32_t, Dec::template pair(wreg[J], t)); + } + dst[v] = u32x4{d[0], d[1], d[2], d[3]}; + } + }; + if (side == 0) decode(std::integral_constant{}); else decode(std::integral_constant{}); + if (xhalf == J && xlive) { + u32x4* xdst = reinterpret_cast(xs[buf] + xrow * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) xdst[v] = xreg[v]; + } + if (side == 0 && st % per == per - 1) { + sc[(st / per) % 3][line] = Dec::scale_value(a, term[J]); + bi[(st / per) % 3][line] = Dec::bias_value(a, term[J]); + } + }; + auto sumx = [&](int st, int buf) { + if (st % per == 0) run = 0.f; + const u32x4* src = reinterpret_cast(xs[buf] + line * kLdw); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 u = src[v]; + const uint32_t q[4] = {u.x, u.y, u.z, u.w}; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const typename T::pair p = __builtin_bit_cast(typename T::pair, q[h]); + run += T::lo(p); + run += T::hi(p); + } + } + if (st % per == per - 1) sx[(st / per) & 1][line] = run; + }; + + // Wave (wm, wn) owns rows 32 wm.., columns 64 wn.. (2 x 4 tiles); a lane: column lane % 16, rows 2 i + lane / 16. + const int wm = wave & 3; + const int wn = wave >> 2; + const int rl = lane & 15; + const int rh = lane >> 4; + const bool live0 = wm * 32 < rows_left; + const bool live1 = wm * 32 + 16 < rows_left; + f32x8 acc[2][4]; + f32x8 d[2][4]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + acc[mt][nt] = f32x8{0, 0, 0, 0, 0, 0, 0, 0}; + d[mt][nt] = acc[mt][nt]; + } + } + const f32x8 zero = {0, 0, 0, 0, 0, 0, 0, 0}; + auto apply_bias = [&](int slot, int g) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt == 1 && !live1) continue; + float s_x[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) s_x[i] = sx[g][wm * 32 + mt * 16 + 2 * i + rh]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float bias = bi[slot][wn * 64 + nt * 16 + rl]; +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = Dec::fold_bias(acc[mt][nt][i], s_x[i], bias); + } + } + }; + fetch(0); + stash(std::integral_constant{}, 0, 0); + __syncthreads(); + auto step = [&](std::integral_constant, int s) { + constexpr int cur = P; + if (live0 && s > 0 && (s - 1) % per == per - 1) apply_bias(((s - 1) / per) % 3, ((s - 1) / per) & 1); + if constexpr (P == 1) fetch(s + 1); + if (live0) { +#pragma unroll + for (int t = 0; t < 2; ++t) { + bf16x16 bf[4]; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) bf[nt] = frag16(ws[cur] + (wn * 64 + nt * 16 + rl) * kLdw + t * 8); + const bool first = t == 0 && s % per == 0; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt == 1 && !live1) continue; + const bf16x16 af = frag16(xs[cur] + (wm * 32 + mt * 16 + rl) * kLdw + t * 8); +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + d[mt][nt] = T::mma(af, bf[nt], first ? zero : d[mt][nt]); + } + } + } + if (s % per == per - 1) { + const int g = (s / per) % 3; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (mt == 1 && !live1) continue; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const float scale = sc[g][wn * 64 + nt * 16 + rl]; +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = Dec::fold_scale(acc[mt][nt][i], d[mt][nt][i], scale); + } + } + } + } + if (sums) sumx(s, cur); + stash(std::integral_constant{}, s + 1, cur ^ 1); + __syncthreads(); + }; + for (int s = 0; s < stages; s += 2) { + step(std::integral_constant{}, s); + if (s + 1 < stages) step(std::integral_constant{}, s + 1); + } + if (live0 && (stages - 1) % per == per - 1) apply_bias(((stages - 1) / per) % 3, ((stages - 1) / per) & 1); +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = m0 + wm * 32 + mt * 16 + 2 * i + rh; + if (row >= a.m) continue; +#pragma unroll + for (int nt = 0; nt < 4; ++nt) { + const int col = n0 + wn * 64 + nt * 16 + rl; + if (col < a.n) Epi::store(a, row, col, acc[mt][nt][i]); + } + } + } +#else + (void)a; + __builtin_trap(); +#endif +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/plan.hpp b/zig/kernels/hip/tiles/plan.hpp new file mode 100644 index 00000000000..6cd355ba754 --- /dev/null +++ b/zig/kernels/hip/tiles/plan.hpp @@ -0,0 +1,27 @@ +#pragma once + +// Routed plan, any weight format: item z = (expert, first, count) takes pairs members[first..first + count). + +namespace tf { +namespace rocm { + +struct Routing { + const int* items = nullptr; // (count, 3) int32; nullptr is one plain (m, n) product + const int* members = nullptr; + int x_div = 1; + int first = 0; // set by the kernel from its item +}; + +// Row r of this block's x and out: the plain matrix's r, or the routed item's r-th pair. +template +__device__ inline long long x_row(const Args& a, int r) { + return a.route.items ? a.route.members[a.route.first + r] / a.route.x_div : r; +} + +template +__device__ inline long long out_row(const Args& a, int r) { + return a.route.items ? a.route.members[a.route.first + r] : r; +} + +} // namespace rocm +} // namespace tf diff --git a/zig/kernels/hip/tiles/stream.hpp b/zig/kernels/hip/tiles/stream.hpp new file mode 100644 index 00000000000..d8544456771 --- /dev/null +++ b/zig/kernels/hip/tiles/stream.hpp @@ -0,0 +1,235 @@ +#pragma once + +// Streaming decode tile for 1 to 8 rows: a lane owns a 32-code chunk of a column; no LDS, lanes fold by shuffle. + +#include +#include + +#include "common/dot2.hpp" +#include "common/vec.hpp" +#include "tiles/plan.hpp" + +namespace tf { +namespace rocm { + +constexpr int kStreamWaves = 4; + +// Tile shapes that exist: CB columns a lane times R rows at most 16 accumulators. +constexpr bool stream_shape(int rows, int cb) { return cb * rows <= 16; } +constexpr int kStreamRows = 16; // the most rows a launch takes + +// The pair (half `parity` of a, half `parity` of b). +__device__ inline uint32_t stream_pick(uint32_t a, uint32_t b, int parity) { + return __builtin_amdgcn_perm(b, a, parity ? 0x07060302u : 0x05040100u); +} + +// x of one row in the order of the code pairs: pair I takes the halves of the codes it is multiplied with. +template +__device__ inline void stream_x_pairs(const uint32_t (&xn)[16], typename T::pair (&xp)[16], + std::integer_sequence) { + (([&] { + constexpr int lo = Dec::template lo(); + constexpr int hi = lo + Dec::gap(); + if constexpr (Dec::kGapPairs) { + xp[I] = __builtin_bit_cast(typename T::pair, stream_pick(xn[lo >> 1], xn[hi >> 1], lo & 1)); + } else { + xp[I] = __builtin_bit_cast(typename T::pair, xn[I]); + } + }()), + ...); +} + +// One column's chunk against RG rows: each code pair is made once and dotted with every row's x. +template +__device__ inline void stream_dots(const typename T::pair (&xp)[RG][16], const uint32_t (&w)[Dec::kWords], float (&d)[RG], + std::integer_sequence) { + (([&] { + const typename T::pair q = Dec::template stream_pair(w); +#pragma unroll + for (int r = 0; r < RG; ++r) d[r] = T::dot(xp[r][I], q, d[r]); + }()), + ...); +} + +// Epi::kPair: a lane's CB columns are CB / 2 gate columns and the same up columns; out is silu(gate) * up. +template +__device__ inline void stream_body(const typename Dec::Args& a, int lpc_log2, int gshift, int bx, int pair_cols, float limit) { + using pair = typename T::pair; + constexpr bool PAIR = Epi::kPair; + constexpr int RG = R < 4 ? R : 4; // rows a pass keeps in registers + constexpr int NG = R / RG; + constexpr uint32_t kOne = T::ones; + const int row0 = blockIdx.y * R; // a block's rows: more than 8 rows are 8-row blocks on the grid's y + const int lpc = 1 << lpc_log2; + const int lane = threadIdx.x & 31; + const int j = lane & (lpc - 1); + const int slot = lane >> lpc_log2; + constexpr int CH = PAIR ? CB / 2 : CB; // output columns a lane + const int cols = PAIR ? pair_cols : a.n; + const int per_wave = (32 >> lpc_log2) * CH; + const int col0 = (bx * kStreamWaves + (threadIdx.x >> 5)) * per_wave + slot * CH; + const int nch = a.k >> 5; + const long long words_row = Dec::template row_words(a); + const long long groups = a.k / a.group; + const uint32_t* wp[CB]; + long long sb[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + const int cj = PAIR ? c % CH : c; + const long long col = (col0 + cj < cols ? col0 + cj : cols - 1) + (PAIR && c >= CH ? pair_cols : 0); + wp[c] = Dec::words(a) + col * words_row; + sb[c] = col * groups; + } + const typename Act::elem* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = Act::row(a, row0 + r < a.m ? row0 + r : 0); + float acc[R][CB]; +#pragma unroll + for (int r = 0; r < R; ++r) { +#pragma unroll + for (int c = 0; c < CB; ++c) acc[r][c] = 0.f; + } + + const typename Dec::StreamTerms terms(a); + + // The loads of one round: every column's chunk and its scale and bias, none waited for before the dots. + auto fetch = [&](int base, uint32_t (&w)[CB][Dec::kWords], unsigned short (&sr)[CB], unsigned short (&br)[CB]) { + const int q = base + j < nch ? base + j : nch - 1; +#pragma unroll + for (int c = 0; c < CB; ++c) { + Dec::template load(wp[c] + static_cast(q) * Dec::kWords, w[c]); + const long long at = sb[c] + (q >> gshift); + sr[c] = terms.scale_raw(at); + br[c] = terms.bias_raw(at); + } + }; + // The dots of one round. A lane past the row's last chunk read the last one: its scale and bias are zero. + auto work = [&](int base, const uint32_t (&w)[CB][Dec::kWords], const unsigned short (&sr)[CB], + const unsigned short (&br)[CB]) { + const bool live = base + j < nch; + const int q = live ? base + j : nch - 1; + float sc[CB]; + float bi[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + sc[c] = live ? terms.widen(sr[c]) : 0.f; + bi[c] = live ? terms.widen(br[c]) : 0.f; + } +#pragma unroll + for (int g = 0; g < NG; ++g) { + if (row0 + g * RG >= a.m) break; + pair xp[RG][16]; + float sx[RG]; +#pragma unroll + for (int r = 0; r < RG; ++r) { + uint32_t xn[16]; + const u32x4* src = + reinterpret_cast(xr[g * RG + r] + static_cast(q) * 32); +#pragma unroll + for (int v = 0; v < 4; ++v) { + const u32x4 t = src[v]; + xn[4 * v] = t.x; + xn[4 * v + 1] = t.y; + xn[4 * v + 2] = t.z; + xn[4 * v + 3] = t.w; + } + float s = 0.f; +#pragma unroll + for (int i = 0; i < 16; ++i) { + s = T::dot(__builtin_bit_cast(pair, xn[i]), __builtin_bit_cast(pair, kOne), s); + } + sx[r] = s; + stream_x_pairs(xn, xp[r], std::make_integer_sequence{}); + } +#pragma unroll + for (int c = 0; c < CB; ++c) { + float d[RG]; +#pragma unroll + for (int r = 0; r < RG; ++r) d[r] = 0.f; + stream_dots(xp, w[c], d, std::make_integer_sequence{}); +#pragma unroll + for (int r = 0; r < RG; ++r) { + acc[g * RG + r][c] = Dec::fold_scale(acc[g * RG + r][c], d[r], sc[c]); + acc[g * RG + r][c] = Dec::fold_bias(acc[g * RG + r][c], sx[r], bi[c]); + } + } + } + }; + + // Columns stagger their start round by group of 8 to spread memory channels; a column's sum order ignores shape. + const int rounds = (nch + lpc - 1) >> lpc_log2; + const int rot = rounds > 1 ? (col0 >> 3) % rounds : 0; + auto at = [&](int r) { + const int ri = r + rot >= rounds ? r + rot - rounds : r + rot; + return ri << lpc_log2; + }; + uint32_t wa[CB][Dec::kWords]; + unsigned short sa[CB], ba[CB]; + if constexpr (R == 1) { + uint32_t wb[CB][Dec::kWords]; + unsigned short sbb[CB], bbb[CB]; + fetch(at(0), wa, sa, ba); + for (int r = 0; r < rounds; r += 2) { + if (r + 1 < rounds) fetch(at(r + 1), wb, sbb, bbb); + work(at(r), wa, sa, ba); + if (r + 1 >= rounds) break; + if (r + 2 < rounds) fetch(at(r + 2), wa, sa, ba); + work(at(r + 1), wb, sbb, bbb); + } + } else { + // several rows: the dots cover the loads' latency, and registers go to the rows' x + for (int r = 0; r < rounds; ++r) { + fetch(at(r), wa, sa, ba); + work(at(r), wa, sa, ba); + } + } + +#pragma unroll + for (int r = 0; r < R; ++r) { + float v[CB]; +#pragma unroll + for (int c = 0; c < CB; ++c) { + v[c] = acc[r][c]; + for (int d = lpc >> 1; d > 0; d >>= 1) v[c] += __shfl_xor(v[c], d, 32); + } + if (j != 0 || row0 + r >= a.m) continue; +#pragma unroll + for (int c = 0; c < CH; ++c) { + const int col = col0 + c; + if (col >= cols) continue; + Epi::put(a, out_row(a, row0 + r), col, v, c, pair_cols, limit); + } + } +} + +// Item z of the plan (or plain product, or a group's side) at CB columns a lane, R rows; chunk group is q >> gshift. +template +__device__ inline void stream_tile(typename Dec::Args& a, const Sides& sides, int lpc_log2, int gshift) { + int bx = blockIdx.x; + if (sides.count > 0) { + int s = 0; + while (s + 1 < sides.count && bx >= sides.first[s + 1]) ++s; + bx -= sides.first[s]; + Dec::bind(a, sides, s); + a.n = sides.n[s]; + if (sides.out_half) { + a.out16 = static_cast<__half*>(sides.out[s]); + } else { + a.out = static_cast(sides.out[s]); + } + } + if (!Dec::take_item(a, blockIdx.z) || static_cast(blockIdx.y) * R >= a.m) return; + if constexpr (Dec::kWideBytes == 4) { + stream_body(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); + } else { + // every chunk is wide-aligned when the words and the row stride are + if (Dec::wide_aligned(a)) { + stream_body(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); + } else { + stream_body(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); + } + } +} + +} // namespace rocm +} // namespace tf diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index e2009e27f7e..27a95da9362 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -23,4 +23,6 @@ test { _ = @import("kernel_tests/chain.zig"); _ = @import("kernel_tests/attention.zig"); _ = @import("kernel_tests/ops.zig"); + _ = @import("kernel_tests/affine/affine.zig"); + _ = @import("kernel_tests/affine/rows.zig"); } diff --git a/zig/src/hip/kernel_tests/affine/affine.zig b/zig/src/hip/kernel_tests/affine/affine.zig new file mode 100644 index 00000000000..605ba017e5a --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/affine.zig @@ -0,0 +1,186 @@ +//! Every registered affine entry the GPU has and the shape fits, against float64; rival entries must write equal bytes. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; +const data = @import("data.zig"); +const cases = @import("cases.zig"); +const prod = @import("product.zig"); +const Product = prod.Product; +const Rig = prod.Rig; +const Entry = affine.Entry; +const Case = cases.Case; + +/// The largest |y - ref| over the sum of the terms' magnitudes an fp32 sum may have: a few units of rounding a term. +fn bound(k: usize) f64 { + return 0x1p-24 * (8 + 2 * @sqrt(@as(f64, @floatFromInt(k)))); +} + +/// What rounding the output to the activation type may add, relative to the value. +fn roundBound(fp16: bool) f64 { + return if (fp16) 0x1p-10 else 0x1p-8; +} + +const pick = 16; + +/// Evenly spaced indices below `n`, ending on the last one: the edges are sampled too. +fn at(i: usize, count: usize, n: usize) usize { + return if (count <= 1 or n <= count) @min(i, n - 1) else i * (n - 1) / (count - 1); +} + +pub const Totals = struct { products: usize = 0, launches: usize = 0, worst: f64 = 0 }; + +const Ref = struct { row: usize, col: usize, v: @import("reference.zig").Value }; + +/// Largest error of the sampled outputs of `out`, over the bound that holds it. +fn worstOf(p: *const Product, out: Buffer, rounded: bool, refs: []const Ref) !f64 { + var worst: f64 = 0; + const lim = bound(p.c.k); + for (refs) |r| { + var y: f64 = undefined; + const at_ = (r.row * p.c.n + r.col); + if (rounded) { + var b: u16 = 0; + try out.download(at_ * 2, std.mem.asBytes(&b)); + if (p.rig.fp16) { + const h: f16 = @bitCast(b); + y = h; + } else { + y = @as(f32, @bitCast(@as(u32, b) << 16)); + } + // the activation type's own rounding, and the fp32 sum below it + const allowed = roundBound(p.rig.fp16) * @abs(r.v.y) + lim * r.v.norm + 1e-7; + worst = @max(worst, @abs(y - r.v.y) / allowed); + } else { + var f: f32 = 0; + try out.download(at_ * 4, std.mem.asBytes(&f)); + worst = @max(worst, @abs(@as(f64, f) - r.v.y) / (lim * @max(r.v.norm, 1e-30))); + } + } + return worst; +} + +const Seen = struct { e: *const Entry, digest: u64 }; + +fn name(buf: []u8, c: Case, rows: usize) []const u8 { + return std.fmt.bufPrint(buf, "{s} m{d} n{d} k{d} b{d} g{d}", .{ c.name, rows, c.n, c.k, c.bits, c.group }) catch "?"; +} + +/// One product: every entry that takes it, against the reference, and the pickable ones against each other. +pub fn product(rig: *Rig, c: Case, tot: *Totals) !void { + var p = try Product.init(rig, c); + defer p.deinit(); + var label_buf: [160]u8 = undefined; + const label = name(&label_buf, c, p.out_rows); + + var refs: [pick * pick]Ref = undefined; + var n_refs: usize = 0; + for (0..@min(pick, p.out_rows)) |i| for (0..@min(pick, c.n)) |j| { + const row = at(i, pick, p.out_rows); + const col = at(j, pick, c.n); + refs[n_refs] = .{ .row = row, .col = col, .v = p.reference(row, col) }; + n_refs += 1; + }; + + const env = rig.kernels.env(); + var pickable_set: std.ArrayList(*const Entry) = .empty; + defer pickable_set.deinit(gpa); + try prod.pickable(rig.kernels, p.arg(0, 0), p.items, c.path, env, &pickable_set, gpa); + + var out = try Buffer.alloc(rig.base, p.outBytes(false)); + defer out.free(); + // a split entry keeps a dot and a sum of x per group + var partial = try Buffer.alloc(rig.base, if (c.path == .decode and !c.routed()) (c.k / c.group) * p.out_rows * c.n * 8 else 8); + defer partial.free(); + var seen: [2][registry.max_entries]Seen = undefined; + var n_seen: [2]usize = .{ 0, 0 }; + var ran: usize = 0; + for (rig.kernels.reg.entries) |*e| { + if (!prod.takes(&p, e)) continue; + const shape = prod.shapeOf(&p, e); + for ([_]bool{ false, true }) |rounded| { + if (rounded and (!e.roundsAct(shape) or e.family == .split or c.routed())) continue; + try out.fill8(0xA5, null); + try prod.launchEntry(&p, e, out, rounded, partial.ptr, 0); + try rig.base.stream.synchronize(); + const worst = try worstOf(&p, out, rounded, refs[0..n_refs]); + tot.worst = @max(tot.worst, worst); + try base.expect(worst <= 1, "affine {s}: {s}{s} is {d:.1} times the error an fp32 sum may have against float64", .{ label, e.id, if (rounded) " (rounded)" else "", worst }); + const digest = try prod.digestOf(out, p.outBytes(rounded)); + rig.digest = std.hash.Wyhash.hash(rig.digest, std.mem.asBytes(&digest)); + const r: usize = @intFromBool(rounded); + if (std.mem.indexOfScalar(*const Entry, pickable_set.items, e) != null) { + seen[r][n_seen[r]] = .{ .e = e, .digest = digest }; + n_seen[r] += 1; + } + ran += 1; + } + } + try base.expect(ran > 0, "affine {s}: no registered entry takes the product", .{label}); + // entries the registry picks between by rows write one set of bytes; the rows group checks routed decode plans + if (env.stream_on and env.gemm_on and !(c.routed() and c.path == .decode)) for (seen, n_seen) |picked, n| { + if (n < 2) continue; + for (picked[1..n]) |s| try base.expect(s.digest == picked[0].digest, "affine {s}: {s} writes other bytes than {s}, which the registry picks between by rows", .{ label, s.e.id, picked[0].e.id }); + }; + tot.products += 1; + tot.launches += ran; +} + +/// A table of products: the decode or prefill shapes. +pub fn list(rig: *Rig, table: []const Case) !void { + var tot: Totals = .{}; + for (table) |c| try product(rig, c, &tot); +} + +fn ragged(comptime path: registry.Path) [6 * 3 * 4 * 3 + 6]Case { + var out: [6 * 3 * 4 * 3 + 6]Case = undefined; + var i: usize = 0; + const rows = if (path == .prefill) [_]usize{ 64, 100, 129, 300 } else [_]usize{ 1, 3, 8, 16 }; + const cols = [_]usize{ 1, 33, 130, 257 }; + for (cases.widths) |bits| for (cases.groups) |group| for (rows, 0..) |m, r| { + // k in groups: one, an odd stage count of 32-code stages (group 32 only) and a few + const ks = [_]usize{ group, group * 3, if (group == 32) 2080 else 4 * @as(usize, group) }; + for (ks, 0..) |k, j| { + out[i] = .{ .name = "ragged", .path = path, .rows = m, .n = cols[(r + j) % cols.len], .k = k, .bits = bits, .group = group }; + i += 1; + } + }; + // routed: short items over a few experts + for (cases.widths) |bits| { + out[i] = .{ .name = "ragged routed", .path = path, .rows = 300, .n = 200, .k = 256, .bits = bits, .experts = 40, .slots = 2, .item_rows = if (path == .prefill) 128 else 8 }; + i += 1; + } + return out; +} + +/// Every width and group on ragged sizes, odd stage counts and short routed items, on both paths. +pub fn sweep(rig: *Rig) !void { + var tot: Totals = .{}; + for (ragged(.prefill)) |c| try product(rig, c, &tot); + for (ragged(.decode)) |c| try product(rig, c, &tot); +} + +test "every affine entry on the served decode shapes sits within an fp32 sum of float64; picked entries write equal bytes" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try list(&rig, &cases.decode); +} + +test "every affine entry on the served prompt shapes sits within an fp32 sum of float64; picked entries write equal bytes" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try list(&rig, &cases.prefill); +} + +test "every width and group on ragged sizes, odd stage counts and short routed items, on both paths" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try sweep(&rig); +} diff --git a/zig/src/hip/kernel_tests/affine/cases.zig b/zig/src/hip/kernel_tests/affine/cases.zig new file mode 100644 index 00000000000..7d4a42222fa --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/cases.zig @@ -0,0 +1,120 @@ +//! The products the affine groups run every registered kernel on: the served models' projections and ragged sizes. + +const registry = @import("core").registry; + +/// A dense product of `rows` rows of x, or a routed one: `rows` tokens of `slots` experts each over stacked tables. +pub const Case = struct { + name: []const u8, + path: registry.Path = .decode, + rows: usize = 1, + n: usize, + k: usize, + bits: u8 = 4, + group: u16 = 64, + experts: usize = 0, + slots: usize = 9, + /// The routed down product: x has a row a pair, else a row a token. + down: bool = false, + /// The most rows an item of the plan holds. + item_rows: usize = 8, + /// Every expert takes the same number of pairs. + even: bool = false, + + pub fn routed(c: Case) bool { + return c.experts > 0; + } +}; + +/// Decode: a lane round's few rows, dense and routed, on the engine's shapes, reaching every decode tile. +pub const decode = [_]Case{ + .{ .name = "35b lm_head", .n = 248320, .k = 2048 }, + .{ .name = "35b qkv", .n = 8192, .k = 2048 }, + .{ .name = "35b o", .n = 2048, .k = 4096 }, + .{ .name = "35b shared gate_up", .n = 1024, .k = 2048 }, + .{ .name = "35b shared down", .n = 2048, .k = 512 }, + .{ .name = "35b kv", .n = 512, .k = 2048 }, + .{ .name = "35b routed gate_up", .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed down", .n = 2048, .k = 512, .experts = 256, .down = true }, + .{ .name = "9b qkv", .n = 8192, .k = 4096 }, + .{ .name = "9b gate_up", .n = 24576, .k = 4096 }, + .{ .name = "9b down", .n = 4096, .k = 12288 }, + .{ .name = "9b lm_head", .n = 248320, .k = 4096 }, + .{ .name = "9b down 6-bit", .n = 4096, .k = 12288, .bits = 6 }, + .{ .name = "9b down 8-bit", .n = 4096, .k = 12288, .bits = 8 }, + .{ .name = "9b gate_up 6-bit", .n = 24576, .k = 4096, .bits = 6 }, + .{ .name = "9b gate_up 8-bit", .n = 24576, .k = 4096, .bits = 8 }, + .{ .name = "9b8 qkv", .n = 12352, .k = 4096, .bits = 8 }, + .{ .name = "9b8 o", .n = 4096, .k = 4096, .bits = 8 }, + .{ .name = "9b8 lm_head", .n = 248320, .k = 4096, .bits = 8 }, + .{ .name = "9b8 kv", .n = 1024, .k = 4096, .bits = 8 }, + .{ .name = "2-bit", .n = 8192, .k = 2048, .bits = 2 }, + .{ .name = "3-bit", .n = 8192, .k = 2048, .bits = 3 }, + .{ .name = "5-bit", .n = 8192, .k = 2048, .bits = 5 }, + .{ .name = "group 32", .n = 8192, .k = 2048, .group = 32 }, + .{ .name = "group 128", .n = 8192, .k = 2048, .group = 128 }, + .{ .name = "ragged", .n = 1001, .k = 2112 }, + .{ .name = "stride k4032", .n = 24576, .k = 4032 }, + .{ .name = "stride k4160", .n = 24576, .k = 4160 }, + .{ .name = "stride k2048", .n = 49152, .k = 2048 }, + .{ .name = "stride k8192", .n = 12288, .k = 8192 }, + .{ .name = "35b qkv x2", .rows = 2, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv x4", .rows = 4, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv x8", .rows = 8, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv x16", .rows = 16, .n = 8192, .k = 2048 }, + .{ .name = "9b gate_up x4", .rows = 4, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up x8", .rows = 8, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up x12", .rows = 12, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up x16", .rows = 16, .n = 24576, .k = 4096 }, + .{ .name = "35b routed gate_up x2", .rows = 2, .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed gate_up x4", .rows = 4, .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed gate_up x8", .rows = 8, .n = 1024, .k = 2048, .experts = 256 }, + .{ .name = "35b routed down x4", .rows = 4, .n = 2048, .k = 512, .experts = 256, .down = true }, +}; + +// Prefill: a prompt's rows. The routed rows are tokens, 8 experts each over 256, in items of at most 128 rows. +pub const prefill = [_]Case{ + .{ .name = "35b qkv", .path = .prefill, .rows = 2048, .n = 8192, .k = 2048 }, + .{ .name = "35b qkv", .path = .prefill, .rows = 8192, .n = 8192, .k = 2048 }, + .{ .name = "35b o", .path = .prefill, .rows = 2048, .n = 2048, .k = 4096 }, + .{ .name = "35b o", .path = .prefill, .rows = 8192, .n = 2048, .k = 4096 }, + .{ .name = "35b shared gate_up", .path = .prefill, .rows = 8192, .n = 1024, .k = 2048 }, + .{ .name = "35b expert gate_up", .path = .prefill, .rows = 64, .n = 1024, .k = 2048 }, + .{ .name = "35b expert gate_up", .path = .prefill, .rows = 256, .n = 1024, .k = 2048 }, + .{ .name = "35b expert down", .path = .prefill, .rows = 256, .n = 2048, .k = 512 }, + .{ .name = "35b routed gate_up", .path = .prefill, .rows = 2048, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128 }, + .{ .name = "35b routed gate_up", .path = .prefill, .rows = 8192, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128 }, + .{ .name = "35b routed even 32", .path = .prefill, .rows = 1024, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128, .even = true }, + .{ .name = "35b routed even 64", .path = .prefill, .rows = 2048, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128, .even = true }, + .{ .name = "35b routed down", .path = .prefill, .rows = 2048, .n = 2048, .k = 512, .experts = 256, .slots = 8, .item_rows = 128, .down = true }, + .{ .name = "35b routed down", .path = .prefill, .rows = 8192, .n = 2048, .k = 512, .experts = 256, .slots = 8, .item_rows = 128, .down = true }, + .{ .name = "9b qkv", .path = .prefill, .rows = 2048, .n = 8192, .k = 4096 }, + .{ .name = "9b gate_up", .path = .prefill, .rows = 2048, .n = 24576, .k = 4096 }, + .{ .name = "9b gate_up", .path = .prefill, .rows = 8192, .n = 12288, .k = 4096 }, + .{ .name = "9b down", .path = .prefill, .rows = 2048, .n = 4096, .k = 12288 }, + .{ .name = "9b down", .path = .prefill, .rows = 8192, .n = 4096, .k = 12288 }, + .{ .name = "27b gate_up", .path = .prefill, .rows = 2048, .n = 17408, .k = 5120 }, + .{ .name = "27b down", .path = .prefill, .rows = 2048, .n = 5120, .k = 17408 }, + .{ .name = "27b q", .path = .prefill, .rows = 8192, .n = 12288, .k = 5120 }, + .{ .name = "vocab", .path = .prefill, .rows = 128, .n = 248320, .k = 2048 }, + .{ .name = "3-bit", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .bits = 3 }, + .{ .name = "6-bit", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .bits = 6 }, + .{ .name = "8-bit", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .bits = 8 }, + .{ .name = "group 32", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .group = 32 }, + .{ .name = "group 128", .path = .prefill, .rows = 2048, .n = 4096, .k = 2048, .group = 128 }, + .{ .name = "edges", .path = .prefill, .rows = 1000, .n = 1001, .k = 2112 }, +}; + +pub const widths = [_]u8{ 2, 3, 4, 5, 6, 8 }; +pub const groups = [_]u16{ 32, 64, 128 }; + +/// A short prompt's few rows, for the timings of each tile on dense and routed products. +pub const short_rows = [_]usize{ 1, 2, 4, 8, 13, 24, 32, 64 }; +pub const short_tokens = [_]usize{ 1, 13, 32, 64, 128, 256 }; +pub const short = [_]Case{ + .{ .name = "9b qkv", .path = .prefill, .n = 8192, .k = 4096 }, + .{ .name = "9b gate_up", .path = .prefill, .n = 24576, .k = 4096 }, + .{ .name = "9b down", .path = .prefill, .n = 4096, .k = 12288 }, + .{ .name = "35b o", .path = .prefill, .n = 2048, .k = 4096 }, + .{ .name = "35b routed gate_up", .path = .prefill, .n = 1024, .k = 2048, .experts = 256, .slots = 8, .item_rows = 128 }, + .{ .name = "35b routed down", .path = .prefill, .n = 2048, .k = 512, .experts = 256, .slots = 8, .item_rows = 128, .down = true }, +}; diff --git a/zig/src/hip/kernel_tests/affine/data.zig b/zig/src/hip/kernel_tests/affine/data.zig new file mode 100644 index 00000000000..3336885c94e --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/data.zig @@ -0,0 +1,89 @@ +//! Random packed products and the device compare the affine tests share. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; + +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; + } + + /// A value in [-1, 1) with a few mantissa bits, so activation sums stay far from overflow. + pub fn unit(r: *Rng) f32 { + const v: i32 = @intCast(r.next() >> 40 & 0x7ff); + return @as(f32, @floatFromInt(v - 1024)) / 1024.0; + } +}; + +pub fn bf16Bits(v: f32) u16 { + return @intCast(@as(u32, @bitCast(v)) >> 16); +} + +pub fn f16Bits(v: f32) u16 { + const h: f16 = @floatCast(v); + return @bitCast(h); +} + +pub fn fill(_: std.mem.Allocator, comptime T: type, n: usize, rng: *Rng, make: *const fn (*Rng) T) ![]T { + const host = try gpa.alloc(T, n); + for (host) |*v| v.* = make(rng); + return host; +} + +pub fn makeWord(r: *Rng) u32 { + return @truncate(r.next() >> 16); +} + +pub fn makeScale(r: *Rng) u16 { + return bf16Bits((r.unit() + 1.0) / 16.0); +} + +pub fn makeBias(r: *Rng) u16 { + return bf16Bits(r.unit() / 2.0); +} + +/// A full-mantissa activation in [-1, 1) at one of six scales: sums of products then round, in any order. +pub fn fine(r: *Rng) f32 { + const v = r.next(); + const m: i32 = @intCast(v >> 41 & 0x3fffff); + return @as(f32, @floatFromInt(m - 0x200000)) / 2097152.0 * std.math.ldexp(@as(f32, 1), -@as(i32, @intCast(v % 6))); +} + +pub fn makeX16(r: *Rng) u16 { + return f16Bits(fine(r)); +} + +pub fn makeXB(r: *Rng) u16 { + return bf16Bits(fine(r)); +} + +/// Words of two device buffers that differ, compared through 32 MiB windows. +pub fn sameOnDevice(a: Buffer, b: Buffer, len: usize) !usize { + const win = 32 << 20; + const ha = try gpa.alloc(u8, win); + defer gpa.free(ha); + const hb = try gpa.alloc(u8, win); + defer gpa.free(hb); + var diff: usize = 0; + var at: usize = 0; + while (at < len) : (at += win) { + const n = @min(win, len - at); + try a.download(at, ha[0..n]); + try b.download(at, hb[0..n]); + var i: usize = 0; + while (i + 4 <= n) : (i += 4) { + if (!std.mem.eql(u8, ha[i..][0..4], hb[i..][0..4])) diff += 1; + } + } + return diff; +} diff --git a/zig/src/hip/kernel_tests/affine/product.zig b/zig/src/hip/kernel_tests/affine/product.zig new file mode 100644 index 00000000000..20385757477 --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/product.zig @@ -0,0 +1,261 @@ +//! One random packed affine product on the host and the device, launched by any registry entry, with its reference. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; +const data = @import("data.zig"); +const ref = @import("reference.zig"); +const cases = @import("cases.zig"); +const Kernels = affine.Kernels; +const Entry = affine.Entry; + +/// The device a group runs on: the shared rig, the registry's kernels and the seeded generator. +pub const Rig = struct { + base: *base.Rig, + kernels: *const Kernels, + fp16: bool, + rng: data.Rng = .{ .state = 0x9E3779B97F4A7C15 }, + /// A running hash of the bytes every launch wrote: the same before and after a change that keeps its bits. + digest: u64 = 0, + + pub fn open(b: *base.Rig) Rig { + return .{ .base = b, .kernels = &b.on.affine, .fp16 = !b.bf16 }; + } +}; + +pub const Product = struct { + rig: *Rig, + c: cases.Case, + hx: []u16, + hw: []u32, + hs: []u16, + hb: []u16, + expert_of: []u32 = &.{}, + x: Buffer, + words: Buffer, + scale: Buffer, + bias: Buffer, + plan: ?Buffer = null, + members: ?Buffer = null, + /// A plan's items and the most rows in one; the output rows a launch writes. + items: usize = 1, + max_rows: usize, + out_rows: usize, + /// Copies of the tables back to back, so timed launches read weights from DRAM. + copies: usize, + copy_words: usize, + copy_tab: usize, + + pub fn init(rig: *Rig, c: cases.Case) !Product { + const experts = @max(c.experts, 1); + const words_row = c.k * c.bits / 32; + const groups = c.k / c.group; + const pairs = c.rows * c.slots; + var p: Product = undefined; + p.rig = rig; + p.c = c; + p.items = 1; + p.max_rows = c.rows; + p.out_rows = if (c.routed()) pairs else c.rows; + p.plan = null; + p.members = null; + p.expert_of = &.{}; + p.copy_words = std.mem.alignForward(usize, experts * c.n * words_row, 64); + p.copy_tab = std.mem.alignForward(usize, experts * c.n * groups, 128); + const copy_bytes = p.copy_words * 4 + p.copy_tab * 4; + p.copies = 1; + _ = copy_bytes; + const x_rows: usize = if (!c.routed()) c.rows else if (c.down) pairs else c.rows; + p.hx = try data.fill(gpa, u16, x_rows * c.k, &rig.rng, if (rig.fp16) data.makeX16 else data.makeXB); + errdefer gpa.free(p.hx); + p.hw = try data.fill(gpa, u32, p.copy_words, &rig.rng, data.makeWord); + errdefer gpa.free(p.hw); + p.hs = try data.fill(gpa, u16, p.copy_tab, &rig.rng, data.makeScale); + errdefer gpa.free(p.hs); + p.hb = try data.fill(gpa, u16, p.copy_tab, &rig.rng, data.makeBias); + errdefer gpa.free(p.hb); + p.x = try Buffer.fromHost(rig.base, p.hx); + errdefer p.x.free(); + p.words = try Buffer.alloc(rig.base, p.copies * p.copy_words * 4); + errdefer p.words.free(); + p.scale = try Buffer.alloc(rig.base, p.copies * p.copy_tab * 2); + errdefer p.scale.free(); + p.bias = try Buffer.alloc(rig.base, p.copies * p.copy_tab * 2); + errdefer p.bias.free(); + for (0..p.copies) |i| { + try p.words.upload(i * p.copy_words * 4, std.mem.sliceAsBytes(p.hw)); + try p.scale.upload(i * p.copy_tab * 2, std.mem.sliceAsBytes(p.hs)); + try p.bias.upload(i * p.copy_tab * 2, std.mem.sliceAsBytes(p.hb)); + } + if (c.routed()) try p.makePlan(pairs); + return p; + } + + /// Each pair draws an expert; the pairs sorted by expert are cut into items of at most `item_rows`. + fn makePlan(p: *Product, pairs: usize) !void { + const c = p.c; + p.expert_of = try gpa.alloc(u32, pairs); + for (p.expert_of, 0..) |*e, i| e.* = if (c.even) @intCast(i % c.experts) else @intCast(p.rig.rng.next() % c.experts); + const order = try gpa.alloc(i32, pairs); + defer gpa.free(order); + for (order, 0..) |*o, i| o.* = @intCast(i); + std.mem.sort(i32, order, p.expert_of, struct { + fn less(of: []u32, a: i32, b: i32) bool { + const ea = of[@intCast(a)]; + const eb = of[@intCast(b)]; + return if (ea != eb) ea < eb else a < b; + } + }.less); + const items = try gpa.alloc(i32, pairs * 3); + defer gpa.free(items); + var count: usize = 0; + var i: usize = 0; + p.max_rows = 1; + while (i < pairs) { + const e = p.expert_of[@intCast(order[i])]; + var j = i; + while (j < pairs and j - i < c.item_rows and p.expert_of[@intCast(order[j])] == e) j += 1; + items[count * 3 ..][0..3].* = .{ @intCast(e), @intCast(i), @intCast(j - i) }; + p.max_rows = @max(p.max_rows, j - i); + count += 1; + i = j; + } + p.items = count; + p.plan = try Buffer.fromHost(p.rig.base, items[0 .. count * 3]); + p.members = try Buffer.fromHost(p.rig.base, order); + } + + pub fn deinit(p: *Product) void { + gpa.free(p.hx); + gpa.free(p.hw); + gpa.free(p.hs); + gpa.free(p.hb); + gpa.free(p.expert_of); + p.x.free(); + p.words.free(); + p.scale.free(); + p.bias.free(); + if (p.plan) |*b| b.free(); + if (p.members) |*b| b.free(); + } + + pub fn flops(p: Product) f64 { + return 2.0 * @as(f64, @floatFromInt(p.out_rows)) * @as(f64, @floatFromInt(p.c.n)) * @as(f64, @floatFromInt(p.c.k)); + } + + /// The bytes of weights and tables a launch reads (every expert an item names, once). + pub fn bytes(p: Product) f64 { + const per = @as(f64, @floatFromInt(p.c.n)) * @as(f64, @floatFromInt(p.c.k * p.c.bits / 8 + 4 * (p.c.k / p.c.group))); + if (!p.c.routed()) return per; + var seen = std.bit_set.DynamicBitSetUnmanaged.initEmpty(gpa, p.c.experts) catch return per; + defer seen.deinit(gpa); + for (p.expert_of) |e| seen.set(e); + return per * @as(f64, @floatFromInt(seen.count())); + } + + pub fn arg(p: Product, out: u64, copy: usize) affine.Arg { + const c = p.c; + return .{ + .x = p.x.ptr, + .words = p.words.ptr + copy * p.copy_words * 4, + .scale = .{ .p = p.scale.ptr + copy * p.copy_tab * 2, .kind = 1 }, + .bias = .{ .p = p.bias.ptr + copy * p.copy_tab * 2, .kind = 1 }, + .out = out, + .m = @intCast(if (c.routed()) p.max_rows else c.rows), + .n = @intCast(c.n), + .k = @intCast(c.k), + .bits = c.bits, + .group = c.group, + .fp16 = @intFromBool(p.rig.fp16), + .route = if (c.routed()) .{ .items = p.plan.?.ptr, .members = p.members.?.ptr, .x_div = @intCast(if (c.down) 1 else c.slots) } else .{}, + }; + } + + pub fn outBytes(p: Product, rounded: bool) usize { + return p.out_rows * p.c.n * @as(usize, if (rounded) 2 else 4); + } + + pub fn problem(p: *const Product) ref.Problem { + return .{ .fp16 = p.rig.fp16, .n = p.c.n, .k = p.c.k, .bits = p.c.bits, .group = p.c.group, .x = p.hx, .words = p.hw, .scale = p.hs, .bias = p.hb }; + } + + /// The float64 value of output (`row`, `col`). + pub fn reference(p: *const Product, row: usize, col: usize) ref.Value { + if (!p.c.routed()) return ref.reference(p.problem(), row, 0, col); + return ref.reference(p.problem(), if (p.c.down) row else row / p.c.slots, p.expert_of[row], col); + } +}; + +/// The shape a registry entry is asked about: a split entry is asked for two parts. +pub fn shapeFor(a: affine.Arg, items: usize, e: *const Entry) registry.Shape { + var s = Kernels.shapeOf(a, @intCast(items)); + if (e.family == .split) s.parts = 2; + return s; +} + +pub fn shapeOf(p: *const Product, e: *const Entry) registry.Shape { + return shapeFor(p.arg(0, 0), p.items, e); +} + +/// Whether `e` is an entry of the launch's (op, path) that the GPU has and whose shape takes it. +pub fn takesArg(k: *const Kernels, e: *const Entry, a: affine.Arg, items: usize, path: registry.Path) bool { + const op: registry.Op = if (a.route.items != 0) .routed else .project; + if (e.format != .mlx or e.op != op or e.path != path) return false; + var env = k.env(); + env.matrix_on = env.matrix; + return e.caps(env) and e.fits(shapeFor(a, items, e)); +} + +/// Entries of the product's (op, path) that the GPU has and whose shapes take it. +pub fn takes(p: *const Product, e: *const Entry) bool { + return takesArg(p.rig.kernels, e, p.arg(0, 0), p.items, p.c.path); +} + +/// The entries the registry picks between at some row count under `env`, for the shape of `a`. +pub fn pickable(k: *const Kernels, a: affine.Arg, items: usize, path: registry.Path, env: registry.Env, out: *std.ArrayList(*const Entry), alloc: std.mem.Allocator) !void { + const op: registry.Op = if (a.route.items != 0) .routed else .project; + var shape = Kernels.shapeOf(a, @intCast(items)); + // a lane round keeps one family at every row count; outside one the decode tiles change with the rows + shape.round = path == .decode; + for (1..registry.rule_rows + 1) |m| { + shape.m = @intCast(m); + const e = k.reg.select(env, .mlx, op, path, shape) orelse continue; + if (std.mem.indexOfScalar(*const Entry, out.items, e) == null) try out.append(alloc, e); + } +} + +/// Launches `e` on the product into `out`, rounded to the activation type when `rounded`. +pub fn launchEntry(p: *const Product, e: *const Entry, out: Buffer, rounded: bool, partial: u64, copy: usize) runtime.Error!void { + var a = p.arg(out.ptr, copy); + if (rounded) { + a.out16 = a.out; + a.out = 0; + } + try e.launch(p.rig.kernels, .{ + .r = &p.rig.base.r, + .s = p.rig.base.stream.handle, + .arg = a, + .items = @intCast(p.items), + .partial = partial, + .parts = if (e.family == .split) 2 else 1, + }); +} + +/// A hash of a device buffer's first `len` bytes, read through windows. +pub fn digestOf(buf: Buffer, len: usize) !u64 { + const win = 32 << 20; + const host = try gpa.alloc(u8, @min(win, len)); + defer gpa.free(host); + var h: u64 = 0; + var at: usize = 0; + while (at < len) : (at += win) { + const n = @min(win, len - at); + try buf.download(at, host[0..n]); + h = std.hash.Wyhash.hash(h, host[0..n]); + } + return h; +} diff --git a/zig/src/hip/kernel_tests/affine/reference.zig b/zig/src/hip/kernel_tests/affine/reference.zig new file mode 100644 index 00000000000..2b707a3959e --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/reference.zig @@ -0,0 +1,76 @@ +//! A float64 reference for the packed affine product, dequant(W) . x, on sampled outputs, and error statistics. + +const std = @import("std"); + +/// One product on the host: fp16 or bf16 activations, and `experts` back to back of words with bf16 scales and biases. +pub const Problem = struct { + fp16: bool, + n: usize, + k: usize, + bits: usize, + group: usize, + x: []const u16, + words: []const u32, + scale: []const u16, + bias: []const u16, +}; + +fn bf16(b: u16) f64 { + return @as(f32, @bitCast(@as(u32, b) << 16)); +} + +fn activation(p: Problem, b: u16) f64 { + if (!p.fp16) return bf16(b); + const h: f16 = @bitCast(b); + return h; +} + +/// Code `k` of a column's packed row. +fn code(row: []const u32, k: usize, bits: usize) u32 { + const at = k * bits; + const shift: u5 = @intCast(at & 31); + var v: u32 = row[at >> 5] >> shift; + if (@as(usize, shift) + bits > 32) v |= row[(at >> 5) + 1] << @intCast(32 - @as(usize, shift)); + return v & ((@as(u32, 1) << @intCast(bits)) - 1); +} + +pub const Value = struct { y: f64, norm: f64 }; + +/// The product of x row `row` with column `col` of expert `expert`, and the sum of the magnitudes of its terms. +pub fn reference(p: Problem, row: usize, expert: usize, col: usize) Value { + const groups = p.k / p.group; + const words_row = p.k * p.bits / 32; + const col_at = expert * p.n + col; + const w = p.words[col_at * words_row ..][0..words_row]; + var y: f64 = 0; + var norm: f64 = 0; + for (0..p.k) |k| { + const g = k / p.group; + const s = bf16(p.scale[col_at * groups + g]); + const b = bf16(p.bias[col_at * groups + g]); + const term = activation(p, p.x[row * p.k + k]) * (@as(f64, @floatFromInt(code(w, k, p.bits))) * s + b); + y += term; + norm += @abs(term); + } + return .{ .y = y, .norm = norm }; +} + +/// Errors of one kernel's outputs: largest |y - ref| / norm (norm: what the terms could sum to), largest and rms. +pub const Stat = struct { + max_rel: f64 = 0, + max_abs: f64 = 0, + sum_sq: f64 = 0, + count: usize = 0, + + pub fn add(s: *Stat, y: f32, v: Value) void { + const e = @abs(@as(f64, y) - v.y); + s.max_abs = @max(s.max_abs, e); + if (v.norm > 0) s.max_rel = @max(s.max_rel, e / v.norm); + s.sum_sq += e * e; + s.count += 1; + } + + pub fn rms(s: Stat) f64 { + return if (s.count == 0) 0 else @sqrt(s.sum_sq / @as(f64, @floatFromInt(s.count))); + } +}; diff --git a/zig/src/hip/kernel_tests/affine/rows.zig b/zig/src/hip/kernel_tests/affine/rows.zig new file mode 100644 index 00000000000..bd67c6a91bb --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/rows.zig @@ -0,0 +1,420 @@ +//! Rows are the same bytes however a product is cut: decode's lane rounds, prefill's tiles and the router's kernels. + +const std = @import("std"); +const base = @import("../rig.zig"); +const affine = @import("../../launches/affine.zig"); +const registry = @import("core").registry; +const runtime = @import("../../runtime.zig"); +const Buffer = base.Buffer; +const gpa = base.gpa; +const data = @import("data.zig"); +const prod = @import("product.zig"); +const shapes = @import("cases.zig"); +const Rig = prod.Rig; +const Entry = affine.Entry; + +const Case = struct { name: []const u8, n: usize, k: usize, bits: c_int = 4, group: c_int = 64 }; + +const cases = [_]Case{ + .{ .name = "vocab", .n = 248320, .k = 2048 }, + .{ .name = "qkv", .n = 8192, .k = 2048 }, + .{ .name = "down", .n = 2048, .k = 512 }, + .{ .name = "9b gate_up", .n = 24576, .k = 4096 }, + .{ .name = "ragged", .n = 1001, .k = 2112 }, + .{ .name = "2-bit", .n = 4096, .k = 2048, .bits = 2 }, + .{ .name = "3-bit", .n = 4096, .k = 2048, .bits = 3 }, + .{ .name = "5-bit", .n = 4096, .k = 2048, .bits = 5 }, + .{ .name = "6-bit group 32", .n = 4096, .k = 2048, .bits = 6, .group = 32 }, + .{ .name = "8-bit group 128", .n = 4096, .k = 2048, .bits = 8, .group = 128 }, +}; + +/// Row counts launched together: every count of a lane round up to 16, then wider rounds. +const together = [_]usize{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32 }; +const most_rows = 32; + +/// One product at every row count: the number of rows whose bytes differ from the same row alone. +fn product(t: *Rig, rng: *data.Rng, c: Case, half: bool) !usize { + const words_row = c.k * @as(usize, @intCast(c.bits)) / 32; + const groups = c.k / @as(usize, @intCast(c.group)); + const hx = try data.fill(gpa, u16, most_rows * c.k, rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try data.fill(gpa, u32, c.n * words_row, rng, data.makeWord); + defer gpa.free(hw); + const hs = try data.fill(gpa, u16, c.n * groups, rng, data.makeScale); + defer gpa.free(hs); + const hb = try data.fill(gpa, u16, c.n * groups, rng, data.makeBias); + defer gpa.free(hb); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var words = try Buffer.fromHost(t.base, hw); + defer words.free(); + var scale = try Buffer.fromHost(t.base, hs); + defer scale.free(); + var bias = try Buffer.fromHost(t.base, hb); + defer bias.free(); + const size: usize = if (half) 2 else 4; + var out = try Buffer.alloc(t.base, most_rows * c.n * size); + defer out.free(); + const alone = try gpa.alloc(u8, most_rows * c.n * size); + defer gpa.free(alone); + const got = try gpa.alloc(u8, most_rows * c.n * size); + defer gpa.free(got); + + var arg: affine.Arg = .{ + .x = x.ptr, + .words = words.ptr, + .scale = .{ .p = scale.ptr, .kind = 1 }, + .bias = .{ .p = bias.ptr, .kind = 1 }, + .out = out.ptr, + .m = 1, + .n = @intCast(c.n), + .k = @intCast(c.k), + .bits = c.bits, + .group = c.group, + .fp16 = @intFromBool(t.fp16), + }; + // each row alone + for (0..most_rows) |i| { + arg.x = x.ptr + i * c.k * 2; + arg.m = 1; + try out.fill8(0xA5, null); + try t.kernels.run(&t.base.r, arg, 4, t.base.stream.handle, 0, 1, half); + try t.base.stream.synchronize(); + try out.download(0, alone[i * c.n * size ..][0 .. c.n * size]); + } + // the rows together + var bad: usize = 0; + arg.x = x.ptr; + for (together) |m| { + arg.m = @intCast(m); + try out.fill8(0xA5, null); + try t.kernels.run(&t.base.r, arg, 4, t.base.stream.handle, 0, 1, half); + try t.base.stream.synchronize(); + try out.download(0, got[0 .. m * c.n * size]); + for (0..m) |i| { + const row = i * c.n * size; + if (!std.mem.eql(u8, got[row..][0 .. c.n * size], alone[row..][0 .. c.n * size])) { + if (bad < 6) std.debug.print(" {s} {s}: row {d} of {d} differs from the row alone\n", .{ c.name, if (half) "rounded" else "fp32", i, m }); + bad += 1; + } + } + } + return bad; +} + +const Plan = struct { counts: [4]c_int }; +const plans = [_]Plan{ .{ .counts = .{ 5, 3, 6, 2 } }, .{ .counts = .{ 15, 9, 1, 4 } }, .{ .counts = .{ 2, 2, 2, 2 } }, .{ .counts = .{ 1, 4, 1, 3 } } }; +const routed_cases = [_]Case{ + .{ .name = "moe gate_up", .n = 1024, .k = 2048 }, + .{ .name = "moe down", .n = 2048, .k = 512 }, + .{ .name = "ragged", .n = 1002, .k = 2112 }, + .{ .name = "3-bit", .n = 1024, .k = 2048, .bits = 3 }, + .{ .name = "8-bit", .n = 1024, .k = 2048, .bits = 8, .group = 128 }, +}; + +fn launchRouted(t: *Rig, arg: affine.Arg, items: c_int, pair: bool) !void { + if (pair) { + if (!try t.kernels.pairRun(&t.base.r, arg, 0, items, t.base.stream.handle)) return error.NoTile; + } else { + try t.kernels.routed(&t.base.r, arg, items, t.base.stream.handle); + } + try t.base.stream.synchronize(); +} + +/// A routed plan's pairs together, against every pair as an item of its own: the number of output rows that differ. +fn routedProduct(t: *Rig, rng: *data.Rng, c: Case, pair: bool) !usize { + const experts = 4; + const words_row = c.k * @as(usize, @intCast(c.bits)) / 32; + const groups = c.k / @as(usize, @intCast(c.group)); + const hx = try data.fill(gpa, u16, 32 * c.k, rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try data.fill(gpa, u32, experts * c.n * words_row, rng, data.makeWord); + defer gpa.free(hw); + const hs = try data.fill(gpa, u16, experts * c.n * groups, rng, data.makeScale); + defer gpa.free(hs); + const hb = try data.fill(gpa, u16, experts * c.n * groups, rng, data.makeBias); + defer gpa.free(hb); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var words = try Buffer.fromHost(t.base, hw); + defer words.free(); + var scale = try Buffer.fromHost(t.base, hs); + defer scale.free(); + var bias = try Buffer.fromHost(t.base, hb); + defer bias.free(); + const cols = if (pair) c.n / 2 else c.n; + const size: usize = if (pair) 2 else 4; + var out = try Buffer.alloc(t.base, 32 * cols * size); + defer out.free(); + const alone = try gpa.alloc(u8, 32 * cols * size); + defer gpa.free(alone); + const got = try gpa.alloc(u8, 32 * cols * size); + defer gpa.free(got); + var members: [32]c_int = undefined; + for (&members, 0..) |*mb, i| mb.* = @intCast(i); + var mem = try Buffer.fromHost(t.base, @as([]const c_int, &members)); + defer mem.free(); + + var bad: usize = 0; + for (plans) |plan| { + var rows: usize = 0; + var item_alone: [96]c_int = undefined; + var item_all: [12]c_int = undefined; + var most: c_int = 0; + for (plan.counts, 0..) |n, e| { + item_all[3 * e] = @intCast(e); + item_all[3 * e + 1] = @intCast(rows); + item_all[3 * e + 2] = n; + most = @max(most, n); + for (0..@as(usize, @intCast(n))) |_| { + item_alone[3 * rows] = @intCast(e); + item_alone[3 * rows + 1] = @intCast(rows); + item_alone[3 * rows + 2] = 1; + rows += 1; + } + } + var plan_alone = try Buffer.fromHost(t.base, @as([]const c_int, item_alone[0 .. 3 * rows])); + defer plan_alone.free(); + var plan_all = try Buffer.fromHost(t.base, @as([]const c_int, &item_all)); + defer plan_all.free(); + var arg: affine.Arg = .{ + .x = x.ptr, + .words = words.ptr, + .scale = .{ .p = scale.ptr, .kind = 1 }, + .bias = .{ .p = bias.ptr, .kind = 1 }, + .out = if (pair) 0 else out.ptr, + .out16 = if (pair) out.ptr else 0, + .m = 1, + .n = @intCast(c.n), + .k = @intCast(c.k), + .bits = c.bits, + .group = c.group, + .fp16 = @intFromBool(t.fp16), + .route = .{ .items = plan_alone.ptr, .members = mem.ptr, .x_div = 1 }, + }; + try out.fill8(0xA5, null); + try launchRouted(t, arg, @intCast(rows), pair); + try out.download(0, alone[0 .. rows * cols * size]); + arg.m = most; + arg.route.items = plan_all.ptr; + try out.fill8(0xA5, null); + try launchRouted(t, arg, 4, pair); + try out.download(0, got[0 .. rows * cols * size]); + for (0..rows) |i| { + const row = i * cols * size; + if (!std.mem.eql(u8, got[row..][0 .. cols * size], alone[row..][0 .. cols * size])) { + if (bad < 6) std.debug.print(" routed {s} {s}: pair {d} of {d} (most {d} rows) differs from the pair alone\n", .{ c.name, if (pair) "act" else "fp32", i, rows, most }); + bad += 1; + } + } + } + return bad; +} + +/// Row counts the block shapes are compared at: every short one's edges, ragged ones and a few blocks. +const tier_rows = [_]usize{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 31, 33, 63, 64, 65, 100, 128, 200 }; + +/// One product (dense, or routed with ragged and empty items) through every block shape: words unlike the 128-row's. +fn tierProduct(t: *Rig, m: usize, n: usize, k: usize, bits: c_int, group: c_int, routed: bool) !usize { + const experts: usize = if (routed) 5 else 1; + const words_row = k * @as(usize, @intCast(bits)) / 32; + const groups = k / @as(usize, @intCast(group)); + var items: [3 * 256]i32 = undefined; + var item_count: usize = 1; + var max_rows = m; + if (routed) { + item_count = 0; + max_rows = 1; + var first: usize = 0; + while (first < m) { + const take = @min(m - first, 1 + t.rng.next() % 40); + items[item_count * 3 ..][0..3].* = .{ @intCast(item_count % experts), @intCast(first), @intCast(take) }; + item_count += 1; + first += take; + max_rows = @max(max_rows, take); + } + items[item_count * 3 ..][0..3].* = .{ 0, @intCast(m), 0 }; + item_count += 1; + } + const pairs = try gpa.alloc(i32, m); + defer gpa.free(pairs); + for (pairs, 0..) |*p, i| p.* = @intCast(i); + const x_div: usize = if (routed) 2 else 1; + const hx = try data.fill(gpa, u16, (m / x_div + 1) * k, &t.rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try data.fill(gpa, u32, experts * n * words_row, &t.rng, data.makeWord); + defer gpa.free(hw); + const hs = try data.fill(gpa, u16, experts * n * groups, &t.rng, data.makeScale); + defer gpa.free(hs); + const hb = try data.fill(gpa, u16, experts * n * groups, &t.rng, data.makeBias); + defer gpa.free(hb); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var words = try Buffer.fromHost(t.base, hw); + defer words.free(); + var scale = try Buffer.fromHost(t.base, hs); + defer scale.free(); + var bias = try Buffer.fromHost(t.base, hb); + defer bias.free(); + var plan = try Buffer.fromHost(t.base, items[0 .. item_count * 3]); + defer plan.free(); + var members = try Buffer.fromHost(t.base, pairs); + defer members.free(); + const bytes = m * n * 4; + var arg: affine.Arg = .{ + .x = x.ptr, + .words = words.ptr, + .scale = .{ .p = scale.ptr, .kind = 1 }, + .bias = .{ .p = bias.ptr, .kind = 1 }, + .out = 0, + .m = @intCast(max_rows), + .n = @intCast(n), + .k = @intCast(k), + .bits = bits, + .group = group, + .fp16 = @intFromBool(t.fp16), + .route = if (routed) .{ .items = plan.ptr, .members = members.ptr, .x_div = @intCast(x_div) } else .{}, + }; + // every tile the registry picks between by rows at this shape, twice, and the engine's own pick + const k_ptr = t.kernels; + var set: std.ArrayList(*const Entry) = .empty; + defer set.deinit(gpa); + try prod.pickable(k_ptr, arg, item_count, .prefill, k_ptr.env(), &set, gpa); + var ids: [registry.max_entries]*const Entry = undefined; + var n_ids: usize = 0; + for (set.items) |e| if (prod.takesArg(k_ptr, e, arg, item_count, .prefill)) { + ids[n_ids] = e; + n_ids += 1; + }; + if (n_ids == 0) return error.NoTile; + const big = n_ids - 1; + var outs: [2 * registry.max_entries + 1]Buffer = undefined; + const n_outs = 2 * n_ids + 1; + for (outs[0..n_outs], 0..) |*o, i| { + o.* = try Buffer.alloc(t.base, bytes); + errdefer for (outs[0..i]) |*f| f.free(); + try o.fill8(0xA5, null); + } + defer for (outs[0..n_outs]) |*o| o.free(); + for (0..2 * n_ids) |i| { + arg.out = outs[i].ptr; + try ids[i % n_ids].launch(k_ptr, .{ .r = &t.base.r, .s = t.base.stream.handle, .arg = arg, .items = @intCast(item_count) }); + } + arg.out = outs[2 * n_ids].ptr; + try k_ptr.prefillLaunch(&t.base.r, arg, t.base.stream.handle, @intCast(item_count)); + try t.base.stream.synchronize(); + const written = try gpa.alloc(u8, bytes); + defer gpa.free(written); + try outs[big].download(0, written); + t.digest = std.hash.Wyhash.hash(t.digest, written); + var diff: usize = 0; + for (0..n_outs) |i| { + if (i == big) continue; + const d = try data.sameOnDevice(outs[big], outs[i], bytes); + if (d != 0) { + const what: []const u8 = if (i < 2 * n_ids) ids[i % n_ids].id else "the engine's pick"; + std.debug.print("{s} differs from {s} in {d} words\n", .{ what, ids[big].id, d }); + const ha = try gpa.alloc(f32, m * n); + defer gpa.free(ha); + const hb2 = try gpa.alloc(f32, m * n); + defer gpa.free(hb2); + try outs[big].download(0, std.mem.sliceAsBytes(ha)); + try outs[i].download(0, std.mem.sliceAsBytes(hb2)); + var shown: usize = 0; + for (ha, hb2, 0..) |u, v, at| { + if (@as(u32, @bitCast(u)) != @as(u32, @bitCast(v)) and shown < 12) { + std.debug.print(" row {d} col {d}: {e} vs {e}\n", .{ at / n, at % n, u, v }); + shown += 1; + } + } + } + diff += d; + } + return diff; +} + +/// The router's logits through the wave-an-expert kernel and the 64 x 64 tiles at `r` rows: the words that differ. +fn routerProduct(t: *Rig, r: usize, d: usize, e: usize) !usize { + const hx = try data.fill(gpa, u16, r * d, &t.rng, if (t.fp16) data.makeX16 else data.makeXB); + defer gpa.free(hx); + const hw = try gpa.alloc(f32, e * d); + defer gpa.free(hw); + for (hw) |*v| v.* = data.fine(&t.rng); + var x = try Buffer.fromHost(t.base, hx); + defer x.free(); + var w = try Buffer.fromHost(t.base, hw); + defer w.free(); + var outs: [2]Buffer = undefined; + for (&outs, 0..) |*o, i| { + o.* = try Buffer.alloc(t.base, r * e * 4); + errdefer for (outs[0..i]) |*f| f.free(); + try o.fill8(0xA5, null); + } + defer for (&outs) |*o| o.free(); + for (outs, [_]bool{ true, false }) |o, small| { + try t.base.on.routerWith(@ptrFromInt(x.ptr), if (t.fp16) 1 else 2, @ptrFromInt(w.ptr), @ptrFromInt(o.ptr), @intCast(r), @intCast(d), @intCast(e), t.base.stream.handle, small); + } + try t.base.stream.synchronize(); + const written = try gpa.alloc(u8, r * e * 4); + defer gpa.free(written); + try outs[0].download(0, written); + t.digest = std.hash.Wyhash.hash(t.digest, written); + return data.sameOnDevice(outs[0], outs[1], r * e * 4); +} + +/// Prefill's short blocks against the 128-row one at every `tier_rows`, dense and routed: any differing word fails. +fn tiers(t: *Rig) !usize { + var ran: usize = 0; + for (shapes.widths) |bits_u| for (shapes.groups) |group_u| for (tier_rows) |m| for ([_]bool{ false, true }) |routed| { + // n off every block width, k a few stages or a long odd run + const bits: c_int = bits_u; + const group: c_int = group_u; + const ks = [_]usize{ 3 * @as(usize, @intCast(group)), if (group == 32) 2080 else 1024 }; + for (ks, 0..) |k, j| { + const n: usize = if (j == 0) 97 else 288; + const diff = try tierProduct(t, m, n, k, bits, group, routed); + try base.expect(diff == 0, "gemm tiers m{d} n{d} k{d} b{d} g{d} routed {}: {d} words differ from the 128-row block", .{ m, n, k, bits, group, routed, diff }); + ran += 1; + } + }; + for (tier_rows) |r| { + for ([_]usize{ 96, 2048 }) |d| { + const diff = try routerProduct(t, r, d, 259); + try base.expect(diff == 0, "router logits r{d} d{d}: {d} words differ between the wave-an-expert kernel and the tiles", .{ r, d, diff }); + ran += 1; + } + } + return ran; +} + +/// Decode: the rows of a lane round's launch against each row alone, plain products and routed plans. +pub fn decode(t: *Rig) !void { + var rng: data.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + var bad: usize = 0; + for (cases) |c| for ([_]bool{ false, true }) |half| { + bad += try product(t, &rng, c, half); + }; + for (routed_cases) |c| for ([_]bool{ false, true }) |pair| { + bad += try routedProduct(t, &rng, c, pair); + }; + try base.expect(bad == 0, "rows decode: {d} rows differ from the same row alone", .{bad}); +} + +/// Prefill: every tile the registry picks between by rows, at every row count, width and group. +pub fn prefill(t: *Rig) !void { + try base.expect(try tiers(t) > 0, "rows prefill: no product ran", .{}); +} + +test "a decode row writes the same bytes alone and in a round of 2 to 32, dense and routed, fp32 and rounded" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try decode(&rig); +} + +test "a prompt row writes the same bytes in every tile, dense and routed, every width and group, and the router's logits" { + const b = try base.Rig.open(1 << 20); + defer b.close(); + var rig = Rig.open(b); + try prefill(&rig); +} diff --git a/zig/src/hip/kernel_tests/decode.zig b/zig/src/hip/kernel_tests/decode.zig index f7693e989e8..5c85b799cab 100644 --- a/zig/src/hip/kernel_tests/decode.zig +++ b/zig/src/hip/kernel_tests/decode.zig @@ -133,3 +133,171 @@ test "the merged residual-and-norm tails are no further from float64 than twice } try tails(t, &rng, 1, 4096, 0); } + +const affine = @import("../launches/affine.zig"); +const ref = @import("affine/reference.zig"); + +/// A random packed product on the host and the device: (n, k) at `bits` and `group`, bf16 tables, `experts` stacked. +const Matrix = struct { + n: usize, + k: usize, + bits: usize, + group: usize, + words: []u32, + scale: []u16, + bias: []u16, + dev: [3]@import("../memory.zig").DeviceBuffer, + + fn init(t: *Rig, rng: *rig.Rng, n: usize, k: usize, bits: usize, group_size: usize, experts: usize) !Matrix { + var m: Matrix = .{ .n = n, .k = k, .bits = bits, .group = group_size, .words = undefined, .scale = undefined, .bias = undefined, .dev = undefined }; + m.words = try gpa.alloc(u32, experts * n * k * bits / 32); + m.scale = try gpa.alloc(u16, experts * n * k / group_size); + m.bias = try gpa.alloc(u16, m.scale.len); + for (m.words) |*w| w.* = @truncate(rng.next() >> 16); + for (m.scale) |*v| v.* = rig.bf16Bits((rng.unit() + 1.0) / 16.0); + for (m.bias) |*v| v.* = rig.bf16Bits(rng.unit() / 2.0); + m.dev = .{ try t.upload(m.words), try t.upload(m.scale), try t.upload(m.bias) }; + return m; + } + + fn deinit(m: *Matrix) void { + gpa.free(m.words); + gpa.free(m.scale); + gpa.free(m.bias); + for (&m.dev) |*b| b.free(); + } + + fn problem(m: Matrix, t: *const Rig, x: []const u16) ref.Problem { + return .{ .fp16 = !t.bf16, .n = m.n, .k = m.k, .bits = m.bits, .group = m.group, .x = x, .words = m.words, .scale = m.scale, .bias = m.bias }; + } + + fn arg(m: Matrix, t: *const Rig, x: u64, rows: usize, out: u64) affine.Arg { + return .{ + .x = x, + .words = at(m.dev[0]), + .scale = .{ .p = at(m.dev[1]), .kind = 1 }, + .bias = .{ .p = at(m.dev[2]), .kind = 1 }, + .out = out, + .m = @intCast(rows), + .n = @intCast(m.n), + .k = @intCast(m.k), + .bits = @intCast(m.bits), + .group = @intCast(m.group), + .fp16 = @intFromBool(!t.bf16), + }; + } +}; + +/// Up to four products sharing x in one launch against one launch each: no further from float64 than twice that. +fn group(t: *Rig, rng: *rig.Rng, rows: usize, ns: []const usize, k: usize, bits: usize, group_size: usize) !void { + const hx = try gpa.alloc(u16, rows * k); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + var x = try t.upload(hx); + defer x.free(); + var ms: [4]Matrix = undefined; + var outs: [2][4]@import("../memory.zig").DeviceBuffer = undefined; + for (ns, 0..) |n, i| { + ms[i] = try Matrix.init(t, rng, n, k, bits, group_size, 1); + for (&outs) |*o| o[i] = try t.alloc(rows * n * 2); + } + defer for (ns, 0..) |_, i| { + ms[i].deinit(); + for (&outs) |*o| o[i].free(); + }; + const kernels = &t.on.affine; + for (ms[0..ns.len], 0..) |m, i| try kernels.run(&t.r, m.arg(t, at(x), rows, at(outs[0][i])), 4, t.stream.handle, 0, 1, true); + var sides: [4]affine.Side = undefined; + for (ms[0..ns.len], 0..) |m, i| sides[i] = .{ .words = at(m.dev[0]), .scale = at(m.dev[1]), .bias = at(m.dev[2]), .n = @intCast(m.n), .out = at(outs[1][i]) }; + try kernels.groupRun(&t.r, ms[0].arg(t, at(x), rows, 0), sides[0..ns.len], true, t.stream.handle); + try t.stream.synchronize(); + var errs: [2]f64 = .{ 0, 0 }; + for (0..2) |v| for (ns, 0..) |n, i| { + const got = try rig.download(u16, outs[v][i]); + defer gpa.free(got); + const prob = ms[i].problem(t, hx); + for (0..rows) |r| for (0..@min(n, 12)) |ci| { + const col = ci * (n - 1) / @max(@min(n, 12) - 1, 1); + const want = ref.reference(prob, r, 0, col); + errs[v] = @max(errs[v], @abs(t.value(got[r * n + col]) - want.y) / want.norm); + }; + }; + try std.testing.expect(errs[1] <= 2 * errs[0] + 1e-9); +} + +/// A token's routed gate and up, then the activation, against one launch with the activation as epilogue. +fn pair(t: *Rig, rng: *rig.Rng, rows: usize, width: usize, k: usize, bits: usize, group_size: usize) !void { + const experts = 64; + const slots = 9; + const pairs = rows * slots; + var m = try Matrix.init(t, rng, 2 * width, k, bits, group_size, experts); + defer m.deinit(); + const hx = try gpa.alloc(u16, rows * k); + defer gpa.free(hx); + for (hx) |*v| v.* = t.bits(rng.unit()); + var x = try t.upload(hx); + defer x.free(); + // a token's pairs are its slots; one pair an item + const pick = try gpa.alloc(u32, pairs); + defer gpa.free(pick); + for (pick) |*e| e.* = @intCast(rng.next() % experts); + const items = try gpa.alloc(i32, pairs * 3); + defer gpa.free(items); + const members = try gpa.alloc(i32, pairs); + defer gpa.free(members); + for (0..pairs) |i| { + items[3 * i ..][0..3].* = .{ @intCast(pick[i]), @intCast(i), 1 }; + members[i] = @intCast(i); + } + var dev_items = try t.upload(items); + defer dev_items.free(); + var dev_members = try t.upload(members); + defer dev_members.free(); + var both = try t.alloc(pairs * 2 * width * 4); + defer both.free(); + var acts: [2]@import("../memory.zig").DeviceBuffer = .{ try t.alloc(pairs * width * 2), try t.alloc(pairs * width * 2) }; + defer for (&acts) |*a| a.free(); + const kernels = &t.on.affine; + var a = m.arg(t, at(x), rows, at(both)); + a.route = .{ .items = at(dev_items), .members = at(dev_members), .x_div = slots }; + try kernels.routedWith(&t.r, a, @intCast(pairs), t.stream.handle, .gemm); + try t.off.tf_moe_act(@ptrFromInt(at(both)), @ptrFromInt(at(acts[0])), t.kind(), @intCast(pairs), @intCast(width), 0, t.stream.handle); + a.out = 0; + a.out16 = at(acts[1]); + try std.testing.expect(try kernels.pairRun(&t.r, a, 0, @intCast(pairs), t.stream.handle)); + try t.stream.synchronize(); + var errs: [2]f64 = .{ 0, 0 }; + const prob = m.problem(t, hx); + for (0..2) |v| { + const got = try rig.download(u16, acts[v]); + defer gpa.free(got); + for (0..pairs) |pi| for (0..12) |ci| { + const col = ci * (width - 1) / 11; + const g = ref.reference(prob, pi / slots, pick[pi], col); + const u = ref.reference(prob, pi / slots, pick[pi], col + width); + const want = g.y / (1.0 + @exp(-g.y)) * u.y; + errs[v] = @max(errs[v], @abs(t.value(got[pi * width + col]) - want) / @max(@abs(want), 0.01)); + }; + } + try std.testing.expect(errs[1] <= 2 * errs[0] + 1e-9); +} + +test "products sharing x in one launch are no further from float64 than twice one launch each" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4, 8, 16 }) |rows| try group(t, &rng, rows, &.{ 8192, 4096, 32, 32 }, 2048, 4, 64); + try group(t, &rng, 1, &.{ 8192, 512, 512 }, 2048, 4, 64); + try group(t, &rng, 1, &.{ 12288, 12288 }, 4096, 6, 64); + try group(t, &rng, 4, &.{ 4096, 4096 }, 4096, 8, 128); + try group(t, &rng, 2, &.{ 1024, 96, 96 }, 2048, 3, 32); +} + +test "the routed gate and up with its activation in one launch is no further from float64 than twice the two launches" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9E3779B97F4A7C15 }; + for ([_]usize{ 1, 2, 4 }) |rows| try pair(t, &rng, rows, 512, 2048, 4, 64); + try pair(t, &rng, 1, 768, 2048, 6, 64); + try pair(t, &rng, 1, 512, 2048, 4, 128); +} diff --git a/zig/src/hip/kernel_tests/rig.zig b/zig/src/hip/kernel_tests/rig.zig index 6afc5c6afd3..a1e142fa81b 100644 --- a/zig/src/hip/kernel_tests/rig.zig +++ b/zig/src/hip/kernel_tests/rig.zig @@ -135,3 +135,42 @@ pub fn bf16Bits(v: f32) u16 { pub fn bf16Value(b: u16) f64 { return @as(f32, @bitCast(@as(u32, b) << 16)); } + +/// A device buffer with its address, as the product tests hand it to launches. +pub const Buffer = struct { + buf: DeviceBuffer, + ptr: u64, + + pub fn alloc(t: *Rig, bytes: usize) !Buffer { + const b = try DeviceBuffer.alloc(&t.r, bytes); + return .{ .buf = b, .ptr = at(b) }; + } + + pub fn fromHost(t: *Rig, host: anytype) !Buffer { + const b = try t.upload(host); + return .{ .buf = b, .ptr = at(b) }; + } + + pub fn free(b: *Buffer) void { + b.buf.free(); + } + + pub fn fill8(b: Buffer, value: u8, _: @TypeOf(null)) !void { + try b.buf.fill8(value); + } + + pub fn upload(b: Buffer, offset: usize, bytes: []const u8) !void { + try b.buf.upload(offset, bytes); + } + + pub fn download(b: Buffer, offset: usize, out: []u8) !void { + try b.buf.download(offset, out); + } +}; + +/// A failed check with its message. +pub fn expect(ok: bool, comptime fmt: []const u8, args: anytype) !void { + if (ok) return; + std.debug.print(fmt ++ "\n", args); + return error.TestUnexpectedResult; +} diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig index 513a88c1f5f..d28850a1c4c 100644 --- a/zig/src/hip/kernels.zig +++ b/zig/src/hip/kernels.zig @@ -2,7 +2,7 @@ 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, gdn_prefill, decode, plan }; +pub const Group = enum { ops, act, attention, gated_delta, prefill, gdn_prefill, decode, plan, affine_tiles, affine_dot2 }; 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. diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index dcf6426df65..2ae4130f343 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -7,6 +7,8 @@ const launch = @import("launch.zig"); const Module = @import("module.zig").Module; const Function = @import("module.zig").Function; const Stream = @import("stream.zig").Stream; +const caps = @import("caps.zig"); +const affine = @import("launches/affine.zig"); const util = @import("launches/util.zig"); @@ -78,6 +80,8 @@ pub const Launcher = struct { wide: bool, /// The DeltaNet prefill runs chunked (off keeps the one-token recurrence). chunked: bool, + /// The MLX affine products and the registry that picks their tiles. + affine: affine.Kernels, const PlanFns = struct { kv_write: Function, @@ -126,7 +130,7 @@ pub const Launcher = struct { }; /// 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, chunked: bool = true }; + pub const Choices = struct { fuse: bool = true, wide: bool = true, chunked: bool = true, products: affine.Choices = .{} }; /// 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 { @@ -246,6 +250,10 @@ pub const Launcher = struct { }; l.softmax_stats = try att.function("tf_softmax_stats"); l.sum_partials = try att.function("tf_sum_partials"); + const tiles = l.mods[@backingInt(kernels.Group.affine_tiles)]; + const dot2 = l.mods[@backingInt(kernels.Group.affine_dot2)]; + l.affine = try affine.Kernels.load(tiles, dot2, caps.Caps.of(kernels.arch) orelse return error.Invalid, choices.products); + try l.affine.fillByteLut(r, dot2); return l; } @@ -306,6 +314,14 @@ pub const Launcher = struct { try launch.launch(f, .{ .grid = grid, .block = block, .shared = shared }, Stream{ .r = l.r, .handle = s }, args); } + pub fn tf_affine(l: *const Launcher, x: C, words: C, scale: C, bias: C, scale_kind: c_int, out: P, m: c_int, n: c_int, k: c_int, bits: c_int, group: c_int, schedule: c_int, fp16: c_int, s: S, partial: F, splits: c_int, out_half: c_int) Error!void { + try l.affine.run(l.r, .{ .x = ad(x), .words = ad(words), .scale = .{ .p = ad(scale), .kind = scale_kind }, .bias = .{ .p = ad(bias), .kind = scale_kind }, .out = ad(out), .m = m, .n = n, .k = k, .bits = bits, .group = group, .fp16 = fp16 }, schedule, s, ad(partial), splits, out_half != 0); + } + + pub fn tf_affine_routed(l: *const Launcher, x: C, words: C, scale: C, bias: C, scale_kind: c_int, out: P, items: CI, count: c_int, members: CI, x_div: c_int, rows: c_int, n: c_int, k: c_int, bits: c_int, group: c_int, fp16: c_int, s: S) Error!void { + try l.affine.routed(l.r, .{ .x = ad(x), .words = ad(words), .scale = .{ .p = ad(scale), .kind = scale_kind }, .bias = .{ .p = ad(bias), .kind = scale_kind }, .out = ad(out), .m = rows, .n = n, .k = k, .bits = bits, .group = group, .fp16 = fp16, .route = .{ .items = ad(items), .members = ad(members), .x_div = x_div } }, count, s); + } + /// 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; diff --git a/zig/src/hip/launches/affine.zig b/zig/src/hip/launches/affine.zig new file mode 100644 index 00000000000..7c2b8a0ccd2 --- /dev/null +++ b/zig/src/hip/launches/affine.zig @@ -0,0 +1,547 @@ +//! The MLX affine tiles of tiles/dot2_tiles.hip and tiles/dot2.hip launched from Zig; the registry picks one. + +const std = @import("std"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); +const hl = @import("../launch.zig"); +const Module = @import("../module.zig").Module; +const Function = @import("../module.zig").Function; +const Stream = @import("../stream.zig").Stream; +const util = @import("util.zig"); + +const Caps = @import("../caps.zig").Caps; +const registry = @import("core").registry; +const quant = @import("core").quant; +const tuning = @import("../tuning/tuning.zig"); +const mlx_entries = @import("mlx_entries.zig"); + +const Error = runtime.Error; + +/// Matrix cores for products: `off` keeps every product on dot2 tiles; `auto` and `on` use them where a tile exists. +pub const Matrix = enum { auto, on, off }; + +/// Which product tiles a run takes where two give the same bits; every one defaults on. +pub const Choices = struct { matrix: Matrix = .auto, stream: bool = true, gemm: bool = true }; + +/// quant/mlx.hpp's GroupTable, Routing and Affine as the kernels take them by value. +pub const GroupTable = extern struct { p: u64, kind: c_int }; +pub const Routing = extern struct { items: u64 = 0, members: u64 = 0, x_div: c_int = 1, first: c_int = 0 }; +pub const Arg = extern struct { + x: u64, + words: u64, + scale: GroupTable, + bias: GroupTable, + out: u64, + m: c_int, + n: c_int, + k: c_int, + bits: c_int, + group: c_int, + fp16: c_int, + route: Routing = .{}, + out16: u64 = 0, +}; + +/// quant/mlx_tiles.hpp's StreamSides: up to four products that share x, K, width and group in one launch. +pub const StreamSides = extern struct { + words: [4]u64 = @splat(0), + scale: [4]u64 = @splat(0), + bias: [4]u64 = @splat(0), + out: [4]u64 = @splat(0), + n: [4]c_int = @splat(0), + first: [5]c_int = @splat(0), + count: c_int = 0, + out_half: c_int = 0, + pair_cols: c_int = 0, + limit: f32 = 0, +}; + +/// One side of a group: its matrix and where its (rows, n) output goes. +pub const Side = struct { words: u64, scale: u64, bias: u64, n: c_int, out: u64 }; + +comptime { + std.debug.assert(@sizeOf(GroupTable) == 16 and @sizeOf(Routing) == 24 and @sizeOf(Arg) == 112 and @sizeOf(StreamSides) == 184); +} + +/// Everything a launch needs beside the kernels. +pub const Call = struct { + r: *const runtime.Runtime, + s: abi.Stream, + arg: Arg, + items: c_int = 1, + sides: []const Side = &.{}, + limit: f32 = 0, + out_half: bool = false, + partial: u64 = 0, + parts: c_int = 1, +}; + +/// A kernel of the registry: its launch on this backend's kernels. +pub const Launch = *const fn (*const Kernels, Call) Error!void; +pub const Registry = registry.Registry(Launch); +pub const Entry = Registry.E; + +pub const bit_widths = [_]c_int{ 2, 3, 4, 5, 6, 8 }; +const row_counts = [_]u8{ 1, 2, 4, 8 }; +const piece_counts = [_]u8{ 1, 2, 4 }; + +pub const lane_rows = 8; // kLaneRows +pub const lane_group_max = 128; +const fast_n = 256; +const stream_cbs = [_]c_int{ 2, 4, 8 }; // columns a lane carries in the stream tile +const stream_rows = [_]u8{ 1, 2, 4 }; // its row counts: columns * rows <= 16 +const stream_waves = 4; // kStreamWaves +const streams_wanted = 3000; // kStreamWavesWanted +const stream_code_words = 32; // kStreamCodeWords + +/// The K-parallel tiles of a short prompt: cb columns a lane set, r rows a pass over up to rb row blocks. +pub const KpTile = struct { cb: c_int, r: c_int, waves: c_int, rb: c_int, loop: bool = true }; +pub const kp_tiles = [_]KpTile{ + .{ .cb = 8, .r = 1, .waves = 2, .rb = 2, .loop = false }, + .{ .cb = 4, .r = 4, .waves = 2, .rb = 4 }, + .{ .cb = 4, .r = 8, .waves = 2, .rb = 4, .loop = false }, + .{ .cb = 4, .r = 2, .waves = 2, .rb = 4 }, +}; + +/// The GEMM tiles of the m >= 64 products: `gemm` (the default) or the reference `block`. +pub const Tile = enum { gemm, block }; + +/// Which GEMM tile of the 128-row family a launch runs: the matrix cores, the dot2 tile, or the reference tile. +pub const BlockKind = enum { matrix, gemm, block }; + +pub const Kernels = struct { + /// Whether block shape `tier` can take `m` rows: a tile that does not loop over its rows holds rb * r of them. + pub fn tierTakes(tier: usize, m: c_int) bool { + return tier >= kp_tiles.len or kp_tiles[tier].loop or m <= kp_tiles[tier].rb * kp_tiles[tier].r; + } + + caps: Caps, + wmma: bool, + /// gfx11: the matrix-core GEMM tile runs (gfx12's WMMA has other layouts). + matrix: bool, + /// `off` runs products on dot2 tiles, `on` and `auto` on matrix cores where a tile exists. + mode: Matrix, + /// Which GEMM tile the products take; the policy's reference switch picks the reference one. + tile: Tile, + lanes: [bit_widths.len][row_counts.len][piece_counts.len]Function, + row: [bit_widths.len][piece_counts.len]Function, + /// The stream tile (tiles/stream.hpp) by width, rows and columns a lane; null where columns * rows > 16. + stream: [bit_widths.len][stream_rows.len][stream_cbs.len]?Function, + /// The same tile with the (gate | up) activation as its epilogue. + pairs: [bit_widths.len][stream_rows.len][stream_cbs.len]?Function, + /// Off keeps the decode tiles before the stream tile (the policy's reference switch). + stream_on: bool, + block: [bit_widths.len]Function, + gemm: [bit_widths.len]Function, + wmma_gemm: [bit_widths.len]Function, + kp: [bit_widths.len][kp_tiles.len]Function, + span: [2]Function, + fold: Function, + wide: Function, + tiled: Function, + reference: Function, + fill: Function, + reg: Registry, + + /// `tiles` holds dot2_tiles.hip's kernels, `dot2` dot2.hip's; bf16 on the WMMA build, fp16 on RDNA2. + pub fn load(tiles_obj: Module, dot2_obj: Module, caps: Caps, choices: Choices) Error!Kernels { + var k: Kernels = undefined; + const wmma = caps.act == .bf16; + k.caps = caps; + k.wmma = wmma; + k.matrix = wmma and caps.matrix == .wmma11; + k.mode = choices.matrix; + k.tile = if (choices.gemm) .gemm else .block; + k.stream_on = choices.stream; + k.reg = Registry.init(tableFor(caps), &mlx_entries.all); + k.reg.verify(k.env(), .mlx) catch return error.Invalid; + // the GEMM tile's rows of x a lane keeps (tiles/gemm.hpp GemmShape): 8 for BF16, 16 for FP16 + if (wmma) try k.resolve("7DotBF16", "Li8E", tiles_obj) else try k.resolve("6DotF16", "Li16E", tiles_obj); + const r = "_ZN2tf4rocm"; + k.span = .{ try dot2_obj.function(r ++ "16affine_dot2_spanILi1EEEvNS0_6AffineEPfi"), try dot2_obj.function(r ++ "16affine_dot2_spanILi8EEEvNS0_6AffineEPfi") }; + k.fold = try dot2_obj.function(r ++ "16affine_dot2_foldEPKfNS0_10GroupTableES3_Pfiii"); + k.wide = try dot2_obj.function(r ++ "16affine_dot2_wideENS0_6AffineE"); + k.tiled = try dot2_obj.function(r ++ "17affine_dot2_tiledENS0_6AffineE"); + k.reference = try dot2_obj.function(r ++ "18affine_dot2_kernelENS0_6AffineE"); + k.fill = try dot2_obj.function(r ++ "13fill_byte_lutEP6__half"); + return k; + } + + fn resolve(k: *Kernels, comptime dot: []const u8, comptime shape: []const u8, m: Module) Error!void { + @setEvalBranchQuota(200_000); + inline for (bit_widths, 0..) |bits, b| { + k.block[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_dot2_blockINS0_{s}ELi{d}EEEvNS0_6AffineE", .{ dot, bits })); + if (k.matrix) k.wmma_gemm[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm16affine_wmma_gemmILi{d}EEEvNS0_6AffineE", .{bits})); + k.gemm[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_gemm_blockINS0_{s}ELi{d}E{s}EEvNS0_6AffineE", .{ dot, bits, shape })); + inline for (kp_tiles, 0..) |t, i| { + k.kp[b][i] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm14affine_gemm_kpINS0_{s}ELi{d}ELi{d}ELi{d}ELi{d}ELi{d}ELb{d}EEEvNS0_6AffineE", .{ dot, bits, t.cb, t.r, t.waves, t.rb, @intFromBool(t.loop) })); + } + inline for (piece_counts, 0..) |pieces, p| { + k.row[b][p] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm15affine_dot2_rowINS0_{s}ELi{d}ELi{d}EEEvNS0_6AffineEi", .{ dot, bits, pieces })); + inline for (row_counts, 0..) |rows, r| { + k.lanes[b][r][p] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_dot2_lanesINS0_{s}ELi{d}ELi{d}ELi{d}EEEvNS0_6AffineE", .{ dot, bits, rows, pieces })); + } + } + inline for (stream_rows, 0..) |rows, r| { + inline for (stream_cbs, 0..) |cb, c| { + k.stream[b][r][c] = if (cb * rows <= 16) + try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb0EEEvNS0_6AffineENS0_11StreamSidesEii", .{ dot, bits, rows, cb })) + else + null; + k.pairs[b][r][c] = if (cb * rows <= 16) + try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb1EEEvNS0_6AffineENS0_11StreamSidesEii", .{ dot, bits, rows, cb })) + else + null; + } + } + } + } + + /// fp16(bf16(code)) for every byte into the module's constant table: the RDNA2 fp16 tiles read it. Once a device. + pub fn fillByteLut(k: *const Kernels, r: *const runtime.Runtime, dot2_obj: Module) Error!void { + if (k.wmma) return; + const lut = try dot2_obj.global("_ZN2tf4rocm8kByteF16E"); + var args: hl.Args = .{}; + try args.add(lut.address); + try hl.launch(k.fill, .{ .grid = .{ .x = 1 }, .block = .{ .x = 256 } }, .{ .r = r, .handle = null }, &args); + try runtime.check(r.api.hipStreamSynchronize(null)); + } + + /// Launches on `s`; the counting stream runs nothing. + fn go(r: *const runtime.Runtime, f: Function, grid: hl.Dim3, block: hl.Dim3, s: abi.Stream, args: *hl.Args) Error!void { + if (s == util.counting) return; + try hl.launch(f, .{ .grid = grid, .block = block }, .{ .r = r, .handle = s }, args); + } + + fn refuse(what: []const u8) Error { + std.log.err("affine: {s}", .{what}); + return error.Invalid; + } + + fn bitIndex(bits: c_int) ?usize { + return std.mem.indexOfScalar(c_int, &bit_widths, bits); + } + + fn pieceIndex(group: c_int) usize { + return switch (group) { + 32 => 0, + 64 => 1, + else => 2, + }; + } + + fn cdiv(n: c_int, by: c_int) c_uint { + return @intCast(@divTrunc(n + by - 1, by)); + } + + /// Groups a lane covers: the groups rounded up to a power of two, at most 32; none under four groups. + pub fn rowLanes(groups: c_int) c_int { + if (groups < 4) return 0; + var lpc: c_int = 4; + while (lpc < groups and lpc < 32) lpc <<= 1; + return lpc; + } + + /// The lanes a column takes in the K-parallel tile: one a group, 32 at most (kp_lanes). + fn kpLanes(groups: c_int) c_int { + return if (groups > 16) 32 else if (groups > 8) 16 else 8; + } + + /// The bytes the GEMM tile's piece loads need the words aligned to, by width. + pub fn gemmAlign(bits: c_int) u64 { + return switch (bits) { + 4, 8 => 16, + 2, 6 => 8, + else => 4, + }; + } + + // ---- what the choice sees of this build and of a call ---- + + /// The GPU and the run's switches as the registry reads them. + pub fn env(k: *const Kernels) registry.Env { + return .{ .bf16 = k.wmma, .matrix = k.matrix, .matrix_on = k.matrix and k.mode != .off, .stream_on = k.stream_on, .gemm_on = k.tile == .gemm }; + } + + /// The MLX entry that takes a product, or null. + pub fn choose(k: *const Kernels, op: registry.Op, path: registry.Path, shape: registry.Shape) ?*const Entry { + return k.reg.select(k.env(), .mlx, op, path, shape); + } + + /// The costs of the GPU's generation: RDNA2's, or the gfx11 ones (RDNA4 takes them for its dot2 tiles). + fn tableFor(caps: Caps) *const tuning.Table { + return switch (caps.generation) { + .rdna2 => &tuning.gfx1030, + .rdna3, .rdna3_5, .rdna4 => &tuning.gfx1100, + }; + } + + /// The product of `a` as a shape: `items` is a routed plan's item count. + pub fn shapeOf(a: Arg, items: c_int) registry.Shape { + const kind: quant.Tables = switch (a.scale.kind) { + 1 => .bf16, + 2 => .f16, + else => .f32, + }; + return .{ + .m = @intCast(@max(a.m, 0)), + .n = @intCast(@max(a.n, 0)), + .k = @intCast(@max(a.k, 0)), + .bits = std.math.cast(u8, a.bits) orelse 0, + .group = std.math.cast(u16, a.group) orelse 0, + .fp16 = a.fp16 != 0, + .tables = kind, + .tables_alike = a.scale.kind == a.bias.kind, + .x_aligned = a.x % 16 == 0, + .words_aligned = a.words % gemmAlign(a.bits) == 0, + .items = if (a.route.items != 0) @intCast(@max(items, 0)) else 0, + }; + } + + // ---- the tiles ---- + + /// The stream tile on `total_n` columns (a group's sum); `sides` counts them off block by block when it has any. + pub fn streamGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, sides_in: StreamSides, total_n: c_int, items: c_int, s: abi.Stream) Error!void { + const b = bitIndex(a.bits).?; + var sides = sides_in; + // a pair's lane carries half as many output columns: a gate column and its up column make one + const pair_div: c_int = if (sides.pair_cols > 0) 2 else 1; + var lpc_log2: u5 = 0; + while ((@as(c_int, 1) << lpc_log2) < (a.k >> 5) and lpc_log2 < 5) lpc_log2 += 1; + const ri: usize = if (a.m == 1) 0 else if (a.m == 2) 1 else 2; + // the widest column count that still fills the card with waves, within the registers the lane's code words take + var pick: usize = 0; + var c: usize = stream_cbs.len; + while (c > 0) { + c -= 1; + if (stream_cbs[c] * stream_rows[ri] > 16 or stream_cbs[c] * a.bits > stream_code_words) continue; + pick = c; + const per_block: c_int = stream_waves * (@as(c_int, 32) >> lpc_log2) * @divExact(stream_cbs[c], pair_div); + if (@as(u64, cdiv(total_n, per_block)) * stream_waves * @as(u64, @intCast(items)) * cdiv(a.m, stream_rows[ri]) >= streams_wanted) break; + } + const per_block: c_int = stream_waves * (@as(c_int, 32) >> lpc_log2) * @divExact(stream_cbs[pick], pair_div); + var blocks: c_uint = cdiv(total_n, per_block); + if (sides.count > 0) { + blocks = 0; + for (0..@intCast(sides.count)) |i| { + sides.first[i] = @intCast(blocks); + blocks += cdiv(sides.n[i], per_block); + } + sides.first[@intCast(sides.count)] = @intCast(blocks); + } + var args: hl.Args = .{}; + try args.add(a); + try args.add(sides); + try args.add(@as(c_int, lpc_log2)); + try args.add(@as(c_int, switch (a.group) { + 32 => 0, + 64 => 1, + else => 2, + })); + const f = (if (sides.pair_cols > 0) k.pairs[b][ri][pick] else k.stream[b][ri][pick]).?; + try go(r, f, .{ .x = blocks, .y = cdiv(a.m, stream_rows[ri]), .z = @intCast(items) }, .{ .x = 32 * stream_waves }, s, &args); + } + + /// One row on the row tile: a lane owns a group, a wave reads a column's row in one run. + pub fn rowGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + try args.add(rowLanes(@divExact(a.k, a.group))); + try go(r, k.row[b][pieceIndex(a.group)], .{ .x = cdiv(a.n, 128), .z = @intCast(items) }, .{ .x = 128 }, s, &args); + } + + /// Up to 8 rows on the column tile. + pub fn lanesGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + const ri: usize = if (a.m == 1) 0 else if (a.m == 2) 1 else if (a.m <= 4) 2 else 3; + try go(r, k.lanes[b][ri][pieceIndex(a.group)], .{ .x = cdiv(a.n, 32), .z = @intCast(items) }, .{ .x = 256 }, s, &args); + } + + /// The wide tile of the RDNA2 decode products of 9 rows and more. + pub fn wideGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream) Error!void { + var args: hl.Args = .{}; + try args.add(a); + try go(r, k.wide, .{ .x = cdiv(a.n, 32), .y = cdiv(a.m, 128) }, .{ .x = 512 }, s, &args); + } + + /// Any group width up to 128 that the others do not take, 16 columns by 16 rows a block. + pub fn tiledGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream) Error!void { + var args: hl.Args = .{}; + try args.add(a); + try go(r, k.tiled, .{ .x = cdiv(a.n, 16), .y = cdiv(a.m, 16) }, .{ .x = 256 }, s, &args); + } + + /// The one-thread tile every product has: the reference of the others. + pub fn referenceGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream) Error!void { + var args: hl.Args = .{}; + try args.add(a); + try go(r, k.reference, .{ .x = cdiv(a.n, 32), .y = @intCast(a.m) }, .{ .x = 32 }, s, &args); + } + + /// The decode tile over groups [z * per, (z + 1) * per) into `partial`, then the fold in group order. + pub fn splitGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, partial: u64, parts: c_int, s: abi.Stream) Error!void { + const groups = @divTrunc(a.k, a.group); + var args: hl.Args = .{}; + try args.add(a); + try args.add(partial); + try args.add(@divExact(groups, parts)); + try go(r, k.span[if (a.m == 1) 0 else 1], .{ .x = cdiv(a.n, fast_n), .y = cdiv(a.m, 8), .z = @intCast(parts) }, .{ .x = fast_n }, s, &args); + var fold: hl.Args = .{}; + try fold.add(partial); + try fold.add(a.scale); + try fold.add(a.bias); + try fold.add(a.out); + try fold.add(a.m); + try fold.add(a.n); + try fold.add(groups); + try go(r, k.fold, .{ .x = cdiv(a.n, fast_n), .y = @intCast(a.m) }, .{ .x = fast_n }, s, &fold); + } + + /// The 128 x 128 tile of a kind over every item of a plan (or the plain product). + pub fn blockGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int, kind: BlockKind) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + const f = switch (kind) { + .matrix => k.wmma_gemm[b], + .gemm => k.gemm[b], + .block => k.block[b], + }; + try go(r, f, .{ .x = cdiv(a.n, 128), .y = cdiv(a.m, 128), .z = @intCast(items) }, .{ .x = 256 }, s, &args); + } + + /// K-parallel tile `tier` (an index of kp_tiles) of a short prompt. + pub fn kpGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int, tier: usize) Error!void { + const b = bitIndex(a.bits) orelse return refuse("bits"); + var args: hl.Args = .{}; + try args.add(a); + const t = kp_tiles[tier]; + const sets = @divExact(32, kpLanes(@divExact(a.k, a.group))); + const blocks = @min(cdiv(a.m, t.r), @as(c_uint, @intCast(t.rb))); + try go(r, k.kp[b][tier], .{ .x = cdiv(a.n, t.waves * t.cb * sets) * blocks, .z = @intCast(items) }, .{ .x = @intCast(32 * t.waves) }, s, &args); + } + + // ---- the entry points ---- + + /// Prefill's tile, same bits however a prompt is cut: matrix on gfx11 unless off, else dot2 GEMM; few rows K-split. + pub fn prefillLaunch(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int) Error!void { + const op: registry.Op = if (a.route.items != 0) .routed else .project; + const e = k.choose(op, .prefill, shapeOf(a, items)) orelse return refuse("prefill shape"); + try e.launch(k, .{ .r = r, .s = s, .arg = a, .items = items }); + } + + /// launch_affine on the auto schedule: `schedule` 3 is prefill's, 4 a lane round's; `partial`, `parts` the tests'. + pub fn run(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, schedule: c_int, s: abi.Stream, partial: u64, parts: c_int, out_half: bool) Error!void { + var a = arg; + if (schedule == 1) { + if (a.fp16 == 0 or k.wmma) return refuse("the reference schedule takes fp16 on RDNA2"); + return k.referenceGo(r, a, s); + } + if (schedule == 2 or schedule > 4) return refuse("no such schedule"); + var shape = shapeOf(a, 1); + shape.round = schedule == 4; + shape.parts = if (partial != 0 and parts > 1) @intCast(parts) else 1; + const e = k.choose(.project, if (schedule == 3) .prefill else .decode, shape) orelse return refuse("no tile takes this product"); + if (out_half) { + // the activation type's output is the decode tile's: fp16 on RDNA2, and either type from the stream tile + if (schedule == 3 or parts > 1 or !e.roundsAct(shape)) return refuse("fp16 output is the decode tile"); + a.out16 = a.out; + a.out = 0; + } + try e.launch(k, .{ .r = r, .s = s, .arg = a, .partial = partial, .parts = parts, .out_half = out_half }); + } + + /// affine_routed_launch: every item of a plan in one launch; `arg.m` is the most rows an item holds. + pub fn routed(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, items: c_int, s: abi.Stream) Error!void { + return k.routedWith(r, arg, items, s, k.tile); + } + + pub fn routedWith(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, items: c_int, s: abi.Stream, tile: Tile) Error!void { + // the family's own activation type: bf16 on the WMMA build, fp16 on RDNA2 + if ((arg.fp16 != 0) == k.wmma or arg.route.items == 0 or arg.route.members == 0 or items < 1 or arg.route.x_div < 1) return refuse("routed plan"); + var environment = k.env(); + environment.gemm_on = tile == .gemm; + const e = k.reg.select(environment, .mlx, .routed, .decode, shapeOf(arg, items)) orelse return refuse("no tile takes this plan"); + try e.launch(k, .{ .r = r, .s = s, .arg = arg, .items = items }); + } + + /// The stacked (gate | up) product as silu(gate) * up into `out16`, clamped by `limit` above 0; false if not taken. + pub fn pairRun(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, limit: f32, items: c_int, s: abi.Stream) Error!bool { + var shape = shapeOf(arg, items); + shape.pairs = arg.out16 != 0; + const e = k.choose(.routed_act, .decode, shape) orelse return false; + try e.launch(k, .{ .r = r, .s = s, .arg = arg, .items = items, .limit = limit }); + return true; + } + + /// Up to four products of `m` rows over one x in one launch; outputs (m, n) fp32, or activation type if `out_half`. + pub fn groupRun(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, group: []const Side, out_half: bool, s: abi.Stream) Error!void { + if (group.len == 0 or group.len > 4) return refuse("group shape"); + var a = arg; + a.n = 0; + for (group) |side| a.n = @max(a.n, side.n); + var shape = shapeOf(a, 1); + shape.round = true; + const e = k.choose(.group, .decode, shape) orelse return refuse("group shape"); + try e.launch(k, .{ .r = r, .s = s, .arg = a, .sides = group, .out_half = out_half }); + } + + /// The stream tile over a group: the sides' addresses and widths in one launch. + pub fn groupGo(k: *const Kernels, r: *const runtime.Runtime, arg: Arg, group: []const Side, out_half: bool, s: abi.Stream) Error!void { + var a = arg; + var sides: StreamSides = .{ .count = @intCast(group.len), .out_half = @intFromBool(out_half) }; + var total: c_int = 0; + a.n = 0; + for (group, 0..) |side, i| { + sides.words[i] = side.words; + sides.scale[i] = side.scale; + sides.bias[i] = side.bias; + sides.out[i] = side.out; + sides.n[i] = side.n; + total += side.n; + a.n = @max(a.n, side.n); + } + a.words = group[0].words; + a.scale.p = group[0].scale; + a.bias.p = group[0].bias; + try k.streamGo(r, a, sides, total, 1, s); + } + + /// The split count of a decode launch: 1 unless `mode` is 2 (the tests' forced comparison) and the groups divide. + pub fn splitCount(m: c_int, n: c_int, k: c_int, group: c_int, mode: c_int) c_int { + if (mode != 2 or m < 1 or n < 512) return 1; + if (!(group == 32 or group == 64 or group == 128) or k < group or @rem(k, group) != 0) return 1; + const groups = @divTrunc(k, group); + if (groups < 2) return 1; + // A full row tile or a wide column grid already fills the card. + const blocks = @divTrunc(n + fast_n - 1, fast_n) * @divTrunc(m + 8 - 1, 8); + if (blocks < 1) return 1; + var want = @divTrunc(256, blocks); + if (want < 2) want = 2; + if (want > groups) want = groups; + var count = want; + while (count >= 2) : (count -= 1) { + if (@rem(groups, count) == 0) return count; + } + return 1; + } +}; + +test "the split count follows the C rule" { + try std.testing.expectEqual(@as(c_int, 1), Kernels.splitCount(1, 4096, 4096, 64, 0)); + try std.testing.expectEqual(@as(c_int, 1), Kernels.splitCount(1, 256, 4096, 64, 2)); + try std.testing.expectEqual(@as(c_int, 8), Kernels.splitCount(1, 4096, 512, 64, 2)); +} + +test "the lane groups of a row tile" { + try std.testing.expectEqual(@as(c_int, 0), Kernels.rowLanes(3)); + try std.testing.expectEqual(@as(c_int, 4), Kernels.rowLanes(4)); + try std.testing.expectEqual(@as(c_int, 32), Kernels.rowLanes(64)); +} + +test { + _ = mlx_entries; +} diff --git a/zig/src/hip/launches/mlx_entries.zig b/zig/src/hip/launches/mlx_entries.zig new file mode 100644 index 00000000000..b9c8fe26c88 --- /dev/null +++ b/zig/src/hip/launches/mlx_entries.zig @@ -0,0 +1,408 @@ +//! The registry's MLX affine entries: each tile with its needs, the shapes it has code for and its launch. + +const std = @import("std"); +const registry = @import("core").registry; +const tuning = @import("../tuning/tuning.zig"); +const affine = @import("affine.zig"); + +const Entry = affine.Entry; +const Shape = registry.Shape; +const Env = registry.Env; +const Call = affine.Call; +const Op = registry.Op; +const Kernels = affine.Kernels; +const Error = @import("../runtime.zig").Error; +const Launch = affine.Launch; + +// ---- what the GPU has and the run switched on + +fn always(_: Env) bool { + return true; +} + +fn rdna2(e: Env) bool { + return !e.bf16; +} + +fn matrixCores(e: Env) bool { + return e.matrix; +} + +fn streamOn(e: Env) bool { + return e.stream_on; +} + +fn gemmOn(e: Env) bool { + return e.gemm_on; +} + +fn matrixOn(e: Env) bool { + return e.matrix and e.matrix_on and e.gemm_on; +} + +// ---- the shapes the tiles have code for + +fn groupOk(s: Shape) bool { + return s.group == 32 or s.group == 64 or s.group == 128; +} + +fn widthOk(s: Shape) bool { + return switch (s.bits) { + 2, 3, 4, 5, 6, 8 => true, + else => false, + }; +} + +/// The words the GEMM tiles load wide, and tables of one kind. +fn gemmFits(s: Shape) bool { + return s.words_aligned and s.tables_alike; +} + +/// The stream tile: whole groups of a multiple of 32, x on 16 bytes, 16-bit tables of one kind. +fn streamShape(s: Shape) bool { + return s.n >= 1 and s.group != 0 and s.group % 32 == 0 and s.group <= affine.lane_group_max and s.k % s.group == 0 and + s.x_aligned and s.tables != .f32 and s.tables_alike and widthOk(s); +} + +fn lanesOk(s: Shape) bool { + return s.m >= 1 and s.m <= affine.lane_rows and s.n >= 1 and s.group != 0 and s.group % 32 == 0 and + s.group <= affine.lane_group_max and s.k % s.group == 0; +} + +fn rowOk(s: Shape) bool { + return s.m == 1 and lanesOk(s) and Kernels.rowLanes(@intCast(s.k / s.group)) != 0; +} + +fn blockOk(s: Shape) bool { + return s.m >= 1 and s.n >= 1 and s.group != 0 and s.group % 32 == 0 and s.k % s.group == 0 and s.k % 16 == 0; +} + +fn prefillOk(s: Shape) bool { + return s.m >= 1 and s.n >= 1 and groupOk(s) and s.k % s.group == 0 and s.k % 16 == 0; +} + +/// What the activation type's dot2 kernels take of a product: any group of an even width. +fn dot2Shape(s: Shape) bool { + return s.m >= 1 and s.n >= 1 and s.k >= 1 and s.group != 0 and s.group % 2 == 0 and s.k % s.group == 0; +} + +/// What a decode launch takes of a product on this build: the checks every tile of it shares. +fn valid(s: Shape) bool { + if (s.fp16) return dot2Shape(s); + return s.m >= 1 and s.n >= 1 and groupOk(s) and s.k % s.group == 0 and s.k % 16 == 0; +} + +fn routedOk(s: Shape) bool { + return groupOk(s) and s.items >= 1; +} + +// ---- the decode tiles of a plain product + +fn fitsSplit(s: Shape) bool { + return s.parts > 1 and s.fp16 and valid(s) and groupOk(s) and (s.k / s.group) % s.parts == 0; +} + +fn fitsStream(s: Shape) bool { + return streamShape(s) and (s.round or valid(s)); +} + +fn fitsRow(s: Shape) bool { + return valid(s) and groupOk(s) and rowOk(s); +} + +fn fitsLanes(s: Shape) bool { + return valid(s) and groupOk(s) and lanesOk(s); +} + +fn fitsWide(s: Shape) bool { + return valid(s) and groupOk(s) and s.m > 8 and (s.m < 64 or s.k % 16 != 0); +} + +fn fitsMatrix(s: Shape) bool { + return valid(s) and blockOk(s) and !s.fp16 and gemmFits(s); +} + +fn fitsGemm(s: Shape) bool { + return valid(s) and groupOk(s) and blockOk(s) and gemmFits(s); +} + +fn fitsBlock(s: Shape) bool { + return valid(s) and groupOk(s) and blockOk(s); +} + +fn fitsTiled(s: Shape) bool { + return dot2Shape(s) and !groupOk(s) and s.m > 1 and s.group <= 128; +} + +fn fitsReference(s: Shape) bool { + return dot2Shape(s); +} + +// ---- the decode tiles of a plan over stacked experts, a group of products and a plan's gate and up + +fn fitsRoutedStream(s: Shape) bool { + return routedOk(s) and streamShape(s); +} + +fn fitsRoutedRow(s: Shape) bool { + return routedOk(s) and rowOk(s); +} + +fn fitsRoutedLanes(s: Shape) bool { + return routedOk(s) and lanesOk(s); +} + +fn fitsRoutedMatrix(s: Shape) bool { + return routedOk(s) and blockOk(s) and !s.fp16 and gemmFits(s); +} + +fn fitsRoutedGemm(s: Shape) bool { + return routedOk(s) and blockOk(s) and gemmFits(s); +} + +fn fitsRoutedBlock(s: Shape) bool { + return routedOk(s) and blockOk(s); +} + +fn fitsGroup(s: Shape) bool { + return streamShape(s); +} + +fn fitsPair(s: Shape) bool { + return s.pairs and s.n >= 2 and s.n % 2 == 0 and streamShape(s); +} + +// ---- the prefill tiles + +fn kpFits(comptime tier: usize) *const fn (Shape) bool { + return struct { + fn f(s: Shape) bool { + return prefillOk(s) and gemmFits(s) and Kernels.tierTakes(tier, @intCast(s.m)); + } + }.f; +} + +fn fitsPrefillMatrix(s: Shape) bool { + return prefillOk(s) and !s.fp16 and gemmFits(s); +} + +fn fitsPrefillGemm(s: Shape) bool { + return prefillOk(s) and gemmFits(s); +} + +fn fitsPrefillBlock(s: Shape) bool { + return prefillOk(s); +} + +// ---- the launches + +fn launchStream(k: *const Kernels, c: Call) Error!void { + try k.streamGo(c.r, c.arg, .{}, c.arg.n, c.items, c.s); +} + +fn launchPair(k: *const Kernels, c: Call) Error!void { + try k.streamGo(c.r, c.arg, .{ .pair_cols = @divExact(c.arg.n, 2), .limit = c.limit }, @divExact(c.arg.n, 2), c.items, c.s); +} + +fn launchGroup(k: *const Kernels, c: Call) Error!void { + try k.groupGo(c.r, c.arg, c.sides, c.out_half, c.s); +} + +fn launchRow(k: *const Kernels, c: Call) Error!void { + try k.rowGo(c.r, c.arg, c.s, c.items); +} + +fn launchLanes(k: *const Kernels, c: Call) Error!void { + try k.lanesGo(c.r, c.arg, c.s, c.items); +} + +fn launchWide(k: *const Kernels, c: Call) Error!void { + try k.wideGo(c.r, c.arg, c.s); +} + +fn launchTiled(k: *const Kernels, c: Call) Error!void { + try k.tiledGo(c.r, c.arg, c.s); +} + +fn launchReference(k: *const Kernels, c: Call) Error!void { + try k.referenceGo(c.r, c.arg, c.s); +} + +fn launchSplit(k: *const Kernels, c: Call) Error!void { + try k.splitGo(c.r, c.arg, c.partial, c.parts, c.s); +} + +fn launchBlock(comptime kind: affine.BlockKind) Launch { + return struct { + fn f(k: *const Kernels, c: Call) Error!void { + try k.blockGo(c.r, c.arg, c.s, c.items, kind); + } + }.f; +} + +fn launchKp(comptime tier: usize) Launch { + return struct { + fn f(k: *const Kernels, c: Call) Error!void { + try k.kpGo(c.r, c.arg, c.s, c.items, tier); + } + }.f; +} + +// ---- the entries + +/// What an entry is besides its op, path and name. +const Spec = struct { + family: registry.Family, + fits: *const fn (Shape) bool, + launch: Launch, + caps: *const fn (Env) bool = &always, + policy: *const fn (Env) bool = &always, + rounds: registry.Rounds = .never, + round_any: bool = false, +}; + +fn entry(comptime op: Op, comptime path: registry.Path, comptime name: []const u8, comptime spec: Spec) Entry { + return .{ + .id = "mlx." ++ @tagName(op) ++ "." ++ @tagName(path) ++ "." ++ name, + .format = .mlx, + .op = op, + .path = path, + .family = spec.family, + .caps = spec.caps, + .policy = spec.policy, + .fits = spec.fits, + .rounds = spec.rounds, + .round_any = spec.round_any, + .launch = spec.launch, + }; +} + +const project_decode = [_]Entry{ + entry(.project, .decode, "split", .{ .family = .split, .fits = &fitsSplit, .launch = &launchSplit, .caps = &rdna2 }), + entry(.project, .decode, "stream", .{ .family = .stream, .fits = &fitsStream, .launch = &launchStream, .policy = &streamOn, .rounds = .always, .round_any = true }), + entry(.project, .decode, "row", .{ .family = .row, .fits = &fitsRow, .launch = &launchRow, .rounds = .fp16 }), + entry(.project, .decode, "lanes", .{ .family = .lanes, .fits = &fitsLanes, .launch = &launchLanes, .rounds = .fp16 }), + entry(.project, .decode, "wide", .{ .family = .wide, .fits = &fitsWide, .launch = &launchWide, .caps = &rdna2 }), + entry(.project, .decode, "matrix", .{ .family = .gemm, .fits = &fitsMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), + entry(.project, .decode, "gemm", .{ .family = .gemm, .fits = &fitsGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(.project, .decode, "block", .{ .family = .gemm, .fits = &fitsBlock, .launch = launchBlock(.block) }), + entry(.project, .decode, "tiled", .{ .family = .tiled, .fits = &fitsTiled, .launch = &launchTiled, .caps = &rdna2 }), + entry(.project, .decode, "reference", .{ .family = .reference, .fits = &fitsReference, .launch = &launchReference, .caps = &rdna2 }), +}; + +const routed_decode = [_]Entry{ + entry(.routed, .decode, "stream", .{ .family = .stream, .fits = &fitsRoutedStream, .launch = &launchStream, .policy = &streamOn }), + entry(.routed, .decode, "row", .{ .family = .row, .fits = &fitsRoutedRow, .launch = &launchRow }), + entry(.routed, .decode, "lanes", .{ .family = .lanes, .fits = &fitsRoutedLanes, .launch = &launchLanes }), + entry(.routed, .decode, "matrix", .{ .family = .gemm, .fits = &fitsRoutedMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), + entry(.routed, .decode, "gemm", .{ .family = .gemm, .fits = &fitsRoutedGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(.routed, .decode, "block", .{ .family = .gemm, .fits = &fitsRoutedBlock, .launch = launchBlock(.block) }), +}; + +const other_decode = [_]Entry{ + entry(.group, .decode, "stream", .{ .family = .stream, .fits = &fitsGroup, .launch = &launchGroup, .policy = &streamOn, .round_any = true }), + entry(.routed_act, .decode, "stream", .{ .family = .stream, .fits = &fitsPair, .launch = &launchPair, .policy = &streamOn }), +}; + +fn prefill(comptime op: Op) [7]Entry { + return .{ + entry(op, .prefill, "kp0", .{ .family = .gemm, .fits = kpFits(0), .launch = launchKp(0), .policy = &gemmOn }), + entry(op, .prefill, "kp1", .{ .family = .gemm, .fits = kpFits(1), .launch = launchKp(1), .policy = &gemmOn }), + entry(op, .prefill, "kp2", .{ .family = .gemm, .fits = kpFits(2), .launch = launchKp(2), .policy = &gemmOn }), + entry(op, .prefill, "kp3", .{ .family = .gemm, .fits = kpFits(3), .launch = launchKp(3), .policy = &gemmOn }), + entry(op, .prefill, "matrix", .{ .family = .gemm, .fits = &fitsPrefillMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), + entry(op, .prefill, "gemm", .{ .family = .gemm, .fits = &fitsPrefillGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(op, .prefill, "block", .{ .family = .gemm, .fits = &fitsPrefillBlock, .launch = launchBlock(.block) }), + }; +} + +pub const all = project_decode ++ routed_decode ++ other_decode ++ prefill(.project) ++ prefill(.routed); + +// ---- the choices on the GPUs' tables + +const Caps = @import("../caps.zig").Caps; + +fn kernelsOn(gfx: []const u8) affine.Registry { + const caps = Caps.of(gfx).?; + return affine.Registry.init(if (caps.generation == .rdna2) &tuning.gfx1030 else &tuning.gfx1100, &all); +} + +fn envOn(gfx: []const u8, stream_on: bool, gemm_on: bool, matrix_on: bool) Env { + const caps = Caps.of(gfx).?; + const matrix = caps.act == .bf16 and caps.matrix == .wmma11; + return .{ .bf16 = caps.act == .bf16, .matrix = matrix, .matrix_on = matrix and matrix_on, .stream_on = stream_on, .gemm_on = gemm_on }; +} + +test "a lane round and a prompt each keep one family at every row count, on every GPU and policy" { + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1151" }) |gfx| { + const r = kernelsOn(gfx); + for ([_]bool{ true, false }) |matrix_on| try r.verify(envOn(gfx, true, true, matrix_on), .mlx); + } +} + +test "the previous decode tiles take over where the stream tile stops" { + const r = kernelsOn("gfx1030"); + var shape: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = true, .tables = .f16 }; + const env = envOn("gfx1030", true, true, false); + // a call outside a lane round: the stream tile to 16 rows, then the wide tile, then the GEMM tile from 64 + const want = [_]struct { u32, []const u8 }{ .{ 1, "stream" }, .{ 16, "stream" }, .{ 17, "wide" }, .{ 63, "wide" }, .{ 64, "gemm" }, .{ 200, "gemm" } }; + for (want) |w| { + shape.m = w[0]; + const e = r.select(env, .mlx, .project, .decode, shape).?; + try std.testing.expect(std.mem.endsWith(u8, e.id, w[1])); + } + // a lane round keeps the stream tile + shape.round = true; + for ([_]u32{ 1, 16, 17, 63, 64, 200 }) |m| { + shape.m = m; + try std.testing.expectEqual(registry.Family.stream, r.select(env, .mlx, .project, .decode, shape).?.family); + } + // the same with the stream tile switched off: the reference tiles by rows + const off = envOn("gfx1030", false, true, false); + shape.m = 4; + try std.testing.expectEqual(registry.Family.lanes, r.select(off, .mlx, .project, .decode, shape).?.family); + shape.m = 1; + try std.testing.expectEqual(registry.Family.row, r.select(off, .mlx, .project, .decode, shape).?.family); +} + +test "the matrix cores take 16 rows and more of a call outside a lane round" { + const r = kernelsOn("gfx1100"); + var shape: Shape = .{ .m = 15, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = false }; + const on = envOn("gfx1100", true, true, true); + try std.testing.expect(std.mem.endsWith(u8, r.select(on, .mlx, .project, .decode, shape).?.id, "stream")); + shape.m = 16; + try std.testing.expect(std.mem.endsWith(u8, r.select(on, .mlx, .project, .decode, shape).?.id, "matrix")); + const off = envOn("gfx1100", true, true, false); + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "stream")); + shape.m = 17; + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "gemm")); + // words the GEMM tile cannot load wide keep the reference tile + shape.words_aligned = false; + try std.testing.expect(std.mem.endsWith(u8, r.select(off, .mlx, .project, .decode, shape).?.id, "block")); +} + +test "a prompt takes the K-parallel tiles by rows and by items, then the 128-row tile" { + const r = kernelsOn("gfx1100"); + const env = envOn("gfx1100", true, true, true); + var shape: Shape = .{ .m = 1, .n = 4096, .k = 4096, .bits = 4, .group = 64, .fp16 = false }; + const plain = [_]struct { u32, []const u8 }{ .{ 1, "kp0" }, .{ 2, "kp0" }, .{ 3, "kp1" }, .{ 4, "kp1" }, .{ 5, "kp2" }, .{ 32, "kp2" }, .{ 33, "matrix" }, .{ 2048, "matrix" } }; + for (plain) |p| { + shape.m = p[0]; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .project, .prefill, shape).?.id, p[1])); + } + shape.items = 100; + shape.m = 30; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .routed, .prefill, shape).?.id, "kp3")); + shape.items = 301; + try std.testing.expect(std.mem.endsWith(u8, r.select(env, .mlx, .routed, .prefill, shape).?.id, "matrix")); + // without the matrix cores the dot2 GEMM tile + shape.items = 0; + shape.m = 64; + try std.testing.expect(std.mem.endsWith(u8, r.select(envOn("gfx1100", true, true, false), .mlx, .project, .prefill, shape).?.id, "gemm")); + // RDNA2 takes a plan of up to 410 items on the second K-parallel tile + const v = kernelsOn("gfx1030"); + shape.fp16 = true; + shape.items = 350; + shape.m = 10; + try std.testing.expect(std.mem.endsWith(u8, v.select(envOn("gfx1030", true, true, false), .mlx, .routed, .prefill, shape).?.id, "kp1")); +} diff --git a/zig/src/hip/ops/ops.zig b/zig/src/hip/ops/ops.zig index da9dbedb110..4a78678f720 100644 --- a/zig/src/hip/ops/ops.zig +++ b/zig/src/hip/ops/ops.zig @@ -5,6 +5,7 @@ const abi = @import("../abi.zig"); const Launcher = @import("../launches.zig").Launcher; const Arena = @import("../arena.zig").Arena; const types = @import("types.zig"); +const products = @import("project.zig"); const attention = @import("attention.zig"); const recurrence = @import("recurrence.zig"); const norms = @import("norms.zig"); @@ -15,6 +16,8 @@ const draw = @import("draw.zig"); pub const Kind = types.Kind; pub const Error = types.Error; pub const Tensor = types.Tensor; +pub const Affine = types.Affine; +pub const Projection = @import("core").quant.Projection; pub const Ops = struct { l: *const Launcher, @@ -27,6 +30,18 @@ pub const Ops = struct { /// 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, + pub const project = products.project; + pub const projectGroup = products.projectGroup; + pub const projectRoutedAct = products.projectRoutedAct; + pub const projectRouted = products.projectRouted; + pub const embedRows = products.embedRows; + pub const affine = products.affine; + pub const affineGroup = products.affineGroup; + pub const affineRoutedAct = products.affineRoutedAct; + pub const affineRouted = products.affineRouted; + pub const embedAffine = products.embedAffine; + pub const denseRows = products.denseRows; + /// Whether decode.hip's merged launches are on. pub fn fused(o: Ops) bool { return o.l.fuse; @@ -72,6 +87,8 @@ pub const Ops = struct { 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()); + try std.testing.expectEqual(@as(c_int, 2), Kind.f16.table()); + try std.testing.expectEqual(@as(c_int, 1), Kind.bf16.table()); } test "every launch compiles" { diff --git a/zig/src/hip/ops/project.zig b/zig/src/hip/ops/project.zig new file mode 100644 index 00000000000..9ef2038841b --- /dev/null +++ b/zig/src/hip/ops/project.zig @@ -0,0 +1,223 @@ +//! The products on a projection of any format, dispatched on its tag; `affine*` are the MLX affine path behind them. + +const t = @import("types.zig"); +const quant = @import("core").quant; +const launches = @import("../launches.zig"); +const affine_launch = @import("../launches/affine.zig"); +const registry = @import("core").registry; +const Ops = @import("ops.zig").Ops; +const Error = t.Error; +const Tensor = t.Tensor; +const Affine = t.Affine; +const Projection = quant.Projection; +const mlx = quant.mlx; +const p = t.p; +const f = t.f; +const i = t.i; +const int = t.int; + +/// The MLX matrix of a projection as the MLX launches take it. +fn affineOf(proj: Projection, h: mlx.Matrix) Affine { + const tables: t.Kind = switch (h.tables) { + .f32 => .f32, + .bf16 => .bf16, + .f16 => .f16, + }; + return .{ .words = h.words, .scale = h.scale, .bias = h.bias, .tables = tables, .n = proj.n, .k = proj.k, .bits = h.bits, .group = h.group, .partial = proj.partial }; +} + +/// matmul(x, proj) for a projection of any format: fp32 when `f32_out`, else x's kind (the MLX rules of `affine`). +pub fn project(o: Ops, x: Tensor, proj: Projection, m: usize, f32_out: bool) Error!Tensor { + switch (proj.handle) { + .mlx => |h| return affine(o, x, affineOf(proj, h), m, f32_out), + .dense => |h| { + if (f32_out or m == 0 or x.kind == .f32) return error.BadShape; + const out: Tensor = .{ .ptr = try o.arena.take(m * proj.n * x.kind.size()), .kind = x.kind }; + try denseRows(o, x, h.weight, out, m, proj.n, proj.k); + return out; + }, + } +} + +/// Up to four products of the same `m` rows in one launch; false, nothing launched, when no grouped tile takes them. +pub fn projectGroup(o: Ops, x: Tensor, ps: []const Projection, m: usize, outs: []Tensor) Error!bool { + var ws: [4]Affine = undefined; + if (ps.len > ws.len) return false; + for (ps, ws[0..ps.len]) |pr, *w| switch (pr.handle) { + .mlx => |h| w.* = affineOf(pr, h), + .dense => return false, + }; + return affineGroup(o, x, ws[0..ps.len], m, outs); +} + +/// The routed gate and up with the activation as the epilogue; null when the format or the tile does not take it. +pub fn projectRoutedAct(o: Ops, x: Tensor, proj: Projection, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize, limit: f32) Error!?Tensor { + switch (proj.handle) { + .mlx => |h| return affineRoutedAct(o, x, affineOf(proj, h), items, count, members, pairs, x_div, rows, limit), + .dense => return null, + } +} + +/// matmul_routed on a stack of experts: every item in one launch; out (pairs, N) fp32. +pub fn projectRouted(o: Ops, x: Tensor, proj: Projection, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize) Error!u64 { + switch (proj.handle) { + .mlx => |h| return affineRouted(o, x, affineOf(proj, h), items, count, members, pairs, x_div, rows), + .dense => return error.BadShape, + } +} + +/// gather_rows: `n` embedding rows of a table of any format with a row gather, by device ids, dequantized into `out`. +pub fn embedRows(o: Ops, table: Projection, ids: u64, n: usize, out: Tensor) Error!void { + switch (table.handle) { + .mlx => |h| return embedAffine(o, affineOf(table, h), ids, n, out), + .dense => |h| try o.l.tf_embed_dense(f(h.weight), @ptrFromInt(ids), int(n), int(table.k), p(out.ptr), @backingInt(out.kind), o.stream), + } +} + +/// The product of `m` rows of x with `w` as the registry sees it; a lane round keeps its decode tile at any row count. +fn shapeOf(o: Ops, x: Tensor, w: Affine, m: usize) registry.Shape { + return .{ + .m = @intCast(m), + .n = w.n, + .k = w.k, + .bits = w.bits, + .group = w.group, + .fp16 = x.kind == .f16, + .tables = switch (w.tables) { + .f32 => .f32, + .bf16 => .bf16, + .f16 => .f16, + }, + .x_aligned = x.ptr % 16 == 0, + .words_aligned = w.words % affine_launch.Kernels.gemmAlign(w.bits) == 0, + .round = o.window, + }; +} + +/// matmul(x, ...) as the Python wrapper runs it on the auto schedule: fp32 (`f32_out`), else the input dtype. +pub fn affine(o: Ops, x: Tensor, w: Affine, m: usize, f32_out: bool) Error!Tensor { + try w.check(); + if (m == 0) return error.BadShape; + const fp16 = x.kind == .f16; + if (x.kind == .f32 or (fp16 and o.bf16) or (!fp16 and !o.bf16)) return error.BadShape; + const n: usize = w.n; + const kind = w.tables.table(); + var half = false; + const z = o.l; + const shape = shapeOf(o, x, w, m); + const tile = z.affine.choose(.project, if (o.prefill) .prefill else .decode, shape) orelse return error.BadShape; + half = !f32_out and !o.prefill and tile.roundsAct(shape); + const out = try o.arena.take(m * n * @as(usize, if (half) 2 else 4)); + { + const arg: affine_launch.Arg = .{ + .x = x.ptr, + .words = w.words, + .scale = .{ .p = w.scale, .kind = kind }, + .bias = .{ .p = w.bias, .kind = kind }, + .out = if (half) 0 else out, + .m = int(m), + .n = int(n), + .k = int(w.k), + .bits = w.bits, + .group = w.group, + .fp16 = @intFromBool(fp16), + .out16 = if (half) out else 0, + }; + try tile.launch(&z.affine, .{ .r = z.r, .s = o.stream, .arg = arg }); + } + if (half) return .{ .ptr = out, .kind = x.kind }; + if (f32_out) return .{ .ptr = out, .kind = .f32 }; + const narrow = try o.arena.take(m * n * 2); + try o.cast(.{ .ptr = out, .kind = .f32 }, .{ .ptr = narrow, .kind = x.kind }, m * n); + return .{ .ptr = narrow, .kind = x.kind }; +} + +/// Up to four products of the same rows in one stream-tile launch, rounded to x's kind; false if unsupported. +pub fn affineGroup(o: Ops, x: Tensor, ws: []const Affine, m: usize, outs: []Tensor) Error!bool { + const z = o.l; + if (o.prefill or !o.fused() or ws.len < 2 or ws.len > 4 or m == 0 or x.kind == .f32) return false; + var widest: u32 = 0; + for (ws) |w| { + try w.check(); + if (w.k != ws[0].k or w.bits != ws[0].bits or w.group != ws[0].group or w.tables != ws[0].tables or w.partial) return false; + widest = @max(widest, w.n); + } + const kind = ws[0].tables.table(); + var widest_w = ws[0]; + widest_w.n = widest; + if (z.affine.choose(.group, .decode, shapeOf(o, x, widest_w, m)) == null) return false; + var sides: [4]affine_launch.Side = undefined; + for (ws, outs[0..ws.len], sides[0..ws.len]) |w, *out, *side| { + out.* = .{ .ptr = try o.arena.take(m * w.n * 2), .kind = x.kind }; + side.* = .{ .words = w.words, .scale = w.scale, .bias = w.bias, .n = int(w.n), .out = out.ptr }; + } + const arg: affine_launch.Arg = .{ + .x = x.ptr, + .words = 0, + .scale = .{ .p = 0, .kind = kind }, + .bias = .{ .p = 0, .kind = kind }, + .out = 0, + .m = int(m), + .n = int(widest), + .k = int(ws[0].k), + .bits = int(ws[0].bits), + .group = int(ws[0].group), + .fp16 = @intFromBool(x.kind == .f16), + }; + try z.affine.groupRun(z.r, arg, sides[0..ws.len], true, o.stream); + return true; +} + +/// Routed gate and up in one launch, silu(gate) * up as epilogue into x's kind; null when the tile cannot. +pub fn affineRoutedAct(o: Ops, x: Tensor, w: Affine, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize, limit: f32) Error!?Tensor { + const z = o.l; + if (o.prefill or !o.fused() or x.kind == .f32 or w.n % 2 != 0) return null; + try w.check(); + const kind = w.tables.table(); + var shape = shapeOf(o, x, w, rows); + shape.pairs = true; + if (z.affine.choose(.routed_act, .decode, shape) == null) return null; + const out = try o.arena.take(pairs * (w.n / 2) * 2); + const arg: affine_launch.Arg = .{ + .x = x.ptr, + .words = w.words, + .scale = .{ .p = w.scale, .kind = kind }, + .bias = .{ .p = w.bias, .kind = kind }, + .out = 0, + .m = int(rows), + .n = int(w.n), + .k = int(w.k), + .bits = int(w.bits), + .group = int(w.group), + .fp16 = @intFromBool(x.kind == .f16), + .route = .{ .items = items, .members = members, .x_div = int(x_div) }, + .out16 = out, + }; + if (!try z.affine.pairRun(z.r, arg, limit, int(count), o.stream)) return null; + return .{ .ptr = out, .kind = x.kind }; +} + +/// matmul_routed: every item (expert, first, count) in one launch over stacked weights; out (pairs, N) fp32. +pub fn affineRouted(o: Ops, x: Tensor, w: Affine, items: u64, count: usize, members: u64, pairs: usize, x_div: usize, rows: usize) Error!u64 { + try w.check(); + const out = try o.arena.of(f32, pairs * w.n); + if (o.prefill) { + const z = o.l; + const kind = w.tables.table(); + try z.affine.prefillLaunch(z.r, .{ .x = x.ptr, .words = w.words, .scale = .{ .p = w.scale, .kind = kind }, .bias = .{ .p = w.bias, .kind = kind }, .out = out, .m = int(rows), .n = int(w.n), .k = int(w.k), .bits = int(w.bits), .group = int(w.group), .fp16 = @intFromBool(x.kind == .f16), .route = .{ .items = items, .members = members, .x_div = int(x_div) } }, o.stream, int(count)); + return out; + } + try o.l.tf_affine_routed(p(x.ptr), p(w.words), p(w.scale), p(w.bias), w.tables.table(), p(out), i(items), int(count), i(members), int(x_div), int(rows), int(w.n), int(w.k), w.bits, w.group, @intFromBool(x.kind == .f16), o.stream); + return out; +} + +/// The MLX affine gather: `n` embedding rows of width `table.k` by device ids, dequantized into `out`. +pub fn embedAffine(o: Ops, table: Affine, ids: u64, n: usize, out: Tensor) Error!void { + try table.check(); + try o.l.tf_embed_rows(p(table.words), p(table.scale), p(table.bias), @backingInt(table.tables), @ptrFromInt(ids), int(n), table.bits, table.group, int(table.k), p(out.ptr), @backingInt(out.kind), o.stream); +} + +/// x (rows, k) of x's kind times fp32 weights (n, k), out (rows, n) in x's kind: an unquantized draft projection. +pub fn denseRows(o: Ops, x: Tensor, w: u64, out: Tensor, rows: usize, n: usize, k: usize) Error!void { + try o.l.tf_dense_rows(p(x.ptr), @backingInt(x.kind), f(w), p(out.ptr), int(rows), int(n), int(k), o.stream); +} diff --git a/zig/src/hip/ops/types.zig b/zig/src/hip/ops/types.zig index 7f6e521cfda..50cb8cc8bbc 100644 --- a/zig/src/hip/ops/types.zig +++ b/zig/src/hip/ops/types.zig @@ -1,4 +1,4 @@ -//! The types the launches share: buffer kinds, a device tensor and the address casts. +//! The types the launches share: buffer kinds, a device tensor, an MLX affine matrix and the address casts. const runtime = @import("../runtime.zig"); @@ -20,6 +20,15 @@ pub const Kind = enum(c_int) { .f32 => 2, }; } + + /// The affine kernels' table numbering: 0 fp32, 1 bf16, 2 fp16. + pub fn table(k: Kind) c_int { + return switch (k) { + .f32 => 0, + .bf16 => 1, + .f16 => 2, + }; + } }; pub const Error = runtime.Error || error{ OutOfDeviceMemory, BadShape }; @@ -27,6 +36,29 @@ pub const Error = runtime.Error || error{ OutOfDeviceMemory, BadShape }; /// A device buffer of `kind` values. pub const Tensor = struct { ptr: u64, kind: Kind }; +/// One MLX affine matrix (N, K): packed words (N, K * bits / 32), scale and bias (N, K / group) of `tables`. +pub const Affine = struct { + words: u64, + scale: u64, + bias: u64, + tables: Kind, + n: u32, + k: u32, + bits: u8, + group: u16, + /// A tensor-parallel slice along K: the product stays fp32, one rank's share of a sum. + partial: bool = false, + + pub fn check(a: Affine) Error!void { + const ok_bits = switch (a.bits) { + 2, 3, 4, 5, 6, 8 => true, + else => false, + }; + if (!ok_bits or (a.group != 32 and a.group != 64 and a.group != 128)) return error.BadShape; + if (a.k % a.group != 0 or (@as(u64, a.k) * a.bits) % 32 != 0) return error.BadShape; + } +}; + pub fn p(addr: u64) ?*anyopaque { return @ptrFromInt(addr); } diff --git a/zig/src/hip/tuning/gfx1030.zon b/zig/src/hip/tuning/gfx1030.zon new file mode 100644 index 00000000000..a420e64cb4b --- /dev/null +++ b/zig/src/hip/tuning/gfx1030.zon @@ -0,0 +1,46 @@ +// The kernel registry's costs on RDNA2 (fp16 activations, dot2 tiles, no matrix cores). +// +// An entry is `mlx...`. Among the entries that take a product the cheapest one runs; an entry not listed +// here is not tuned for this GPU and never runs on it. Beside its `cost` an entry says which products it takes: +// rows the most rows of a plain product (0: any), and rows_matrix the most when the matrix cores take the rows above it +// min_rows the fewest rows +// items the most items of a routed plan (0: any) +// plain, routed whether it takes plain products, routed plans (both by default) +// The numbers are the thresholds the launches kept before the registry; a measured table replaces them. +.{ + .gfx = "gfx1030", + .entries = .{ + // a lane round, or a call of few rows: the stream tile takes every product it can + .{ .id = "mlx.project.decode.split", .cost = 0 }, + .{ .id = "mlx.project.decode.stream", .cost = 1, .rows = 16 }, + .{ .id = "mlx.project.decode.row", .cost = 2 }, + .{ .id = "mlx.project.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.project.decode.wide", .cost = 4, .min_rows = 9 }, + .{ .id = "mlx.project.decode.gemm", .cost = 6, .min_rows = 64 }, + .{ .id = "mlx.project.decode.block", .cost = 7, .min_rows = 64 }, + .{ .id = "mlx.project.decode.tiled", .cost = 8 }, + .{ .id = "mlx.project.decode.reference", .cost = 9 }, + + .{ .id = "mlx.group.decode.stream", .cost = 1, .rows = 16 }, + .{ .id = "mlx.routed.decode.stream", .cost = 1, .rows = 16 }, + .{ .id = "mlx.routed.decode.row", .cost = 2 }, + .{ .id = "mlx.routed.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.routed.decode.gemm", .cost = 6, .min_rows = 9 }, + .{ .id = "mlx.routed.decode.block", .cost = 7, .min_rows = 9 }, + .{ .id = "mlx.routed_act.decode.stream", .cost = 1, .rows = 16 }, + + // a prompt: the K-parallel tiles for a few rows or a short plan, the 128-row tile past them + .{ .id = "mlx.project.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.project.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.project.prefill.kp1", .cost = 3, .rows = 4, .items = 410 }, + .{ .id = "mlx.project.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.project.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.project.prefill.block", .cost = 12 }, + .{ .id = "mlx.routed.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.routed.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.routed.prefill.kp1", .cost = 3, .rows = 4, .items = 410 }, + .{ .id = "mlx.routed.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.routed.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.routed.prefill.block", .cost = 12 }, + }, +} diff --git a/zig/src/hip/tuning/gfx1100.zon b/zig/src/hip/tuning/gfx1100.zon new file mode 100644 index 00000000000..462330a8b18 --- /dev/null +++ b/zig/src/hip/tuning/gfx1100.zon @@ -0,0 +1,46 @@ +// The kernel registry's costs on RDNA3 and RDNA3.5 (bf16 activations, dot2 tiles and the gfx11 matrix cores). +// +// An entry is `mlx...`. Among the entries that take a product the cheapest one runs; an entry not listed +// here is not tuned for this GPU and never runs on it. Beside its `cost` an entry says which products it takes: +// rows the most rows of a plain product (0: any), and rows_matrix the most when the matrix cores take the rows above it +// min_rows the fewest rows +// items the most items of a routed plan (0: any) +// plain, routed whether it takes plain products, routed plans (both by default) +// The numbers are the thresholds the launches kept before the registry; a measured table replaces them. +.{ + .gfx = "gfx1100", + .entries = .{ + // a lane round, or a call of few rows: the stream tile takes every product it can; the matrix cores take 16 rows and more + .{ .id = "mlx.project.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "mlx.project.decode.row", .cost = 2 }, + .{ .id = "mlx.project.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.project.decode.matrix", .cost = 5, .min_rows = 16 }, + .{ .id = "mlx.project.decode.gemm", .cost = 6, .min_rows = 9 }, + .{ .id = "mlx.project.decode.block", .cost = 7, .min_rows = 9 }, + + .{ .id = "mlx.group.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "mlx.routed.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + .{ .id = "mlx.routed.decode.row", .cost = 2 }, + .{ .id = "mlx.routed.decode.lanes", .cost = 3, .rows = 8 }, + .{ .id = "mlx.routed.decode.matrix", .cost = 5, .min_rows = 16 }, + .{ .id = "mlx.routed.decode.gemm", .cost = 6, .min_rows = 9 }, + .{ .id = "mlx.routed.decode.block", .cost = 7, .min_rows = 9 }, + .{ .id = "mlx.routed_act.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, + + // a prompt: the K-parallel tiles for a few rows or a short plan, the 128-row tile past them + .{ .id = "mlx.project.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.project.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.project.prefill.kp1", .cost = 3, .rows = 4, .items = 300 }, + .{ .id = "mlx.project.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.project.prefill.matrix", .cost = 10 }, + .{ .id = "mlx.project.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.project.prefill.block", .cost = 12 }, + .{ .id = "mlx.routed.prefill.kp0", .cost = 1, .rows = 2, .routed = false }, + .{ .id = "mlx.routed.prefill.kp3", .cost = 2, .items = 300, .plain = false }, + .{ .id = "mlx.routed.prefill.kp1", .cost = 3, .rows = 4, .items = 300 }, + .{ .id = "mlx.routed.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + .{ .id = "mlx.routed.prefill.matrix", .cost = 10 }, + .{ .id = "mlx.routed.prefill.gemm", .cost = 11 }, + .{ .id = "mlx.routed.prefill.block", .cost = 12 }, + }, +} diff --git a/zig/src/hip/tuning/tuning.zig b/zig/src/hip/tuning/tuning.zig new file mode 100644 index 00000000000..fbde326f2cb --- /dev/null +++ b/zig/src/hip/tuning/tuning.zig @@ -0,0 +1,21 @@ +//! The registry's costs on each GPU: the .zon tables beside this file, read at build time. + +const std = @import("std"); +const tuning = @import("core").tuning; + +pub const Row = tuning.Row; +pub const Table = tuning.Table; +pub const find = tuning.find; + +pub const gfx1030 = tuning.build(@import("gfx1030.zon")); +pub const gfx1100 = tuning.build(@import("gfx1100.zon")); + +test "the tables name each entry once" { + for ([_]*const Table{ &gfx1030, &gfx1100 }) |t| { + for (t.rows, 0..) |r, i| { + for (t.rows[i + 1 ..]) |o| try std.testing.expect(!std.mem.eql(u8, r.id, o.id)); + } + } + try std.testing.expect(find(&gfx1100, "mlx.project.decode.matrix") != null); + try std.testing.expect(find(&gfx1030, "mlx.project.decode.matrix") == null); +} diff --git a/zig/tests/hip_kernels.md b/zig/tests/hip_kernels.md index 121e6e2a0ef..4c77cfbdeba 100644 --- a/zig/tests/hip_kernels.md +++ b/zig/tests/hip_kernels.md @@ -16,9 +16,17 @@ The GPU tests check: 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. +- Every MLX affine entry the GPU has (dot2 tiles, the gfx11 matrix-core GEMM tile, the K-parallel and stream tiles), + on the served models' shapes and a ragged sweep of every width and group, within the error an fp32 sum may have + against float64; entries the registry picks between by rows write equal bytes. +- A row's product writes the same bytes alone and in a round of 2 to 32 rows, dense and routed, in every prompt tile. +- Products sharing x, and the routed gate and up with its activation, in one launch no further from float64 than + twice the launches they replace. Build notes: - `-Dhipcc` and `-Dhip-include` as for `hip-gpu-test`. +- No rocWMMA: the gfx11 matrix-core tile uses the compiler's WMMA builtins, so ROCm packages without + `rocwmma/rocwmma.hpp` (Ubuntu's ROCm 7.1) build it. - `-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`. From 9b6b26072c11f14bbd0cd9b061558e2d7f4dbc93 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 08:59:31 +0200 Subject: [PATCH 05/52] docs(hip): the device bitcode of Ubuntu's packaged HIP, and no rocWMMA header needed From ThinkOffApp's gfx1151 runs on this PR and #621: Ubuntu's HIP 7.1 keeps its device bitcode in LLVM's clang resource directory, and the kernels build there with -Dhip-device-lib set to it, without rocWMMA's header. --- zig/tests/hip_kernels.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zig/tests/hip_kernels.md b/zig/tests/hip_kernels.md index 121e6e2a0ef..cebd41e6441 100644 --- a/zig/tests/hip_kernels.md +++ b/zig/tests/hip_kernels.md @@ -21,4 +21,6 @@ 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`. + 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. From 5d058942ee82b20ae190d586117daacd12304541 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:20:52 +0200 Subject: [PATCH 06/52] chore(hip): gdn_prefill.hip drops the vLLM SPDX lines it kept from the fork's hand ports The kernel was written for TensorFold after FLA's chunk_gated_delta_rule; no code came from vLLM or FLA, and the header only came along from the opengfx1030/vllm-rdna ports. --- zig/kernels/hip/recurrence/gdn_prefill.hip | 4 ---- 1 file changed, 4 deletions(-) diff --git a/zig/kernels/hip/recurrence/gdn_prefill.hip b/zig/kernels/hip/recurrence/gdn_prefill.hip index ff7098ec340..eb637254379 100644 --- a/zig/kernels/hip/recurrence/gdn_prefill.hip +++ b/zig/kernels/hip/recurrence/gdn_prefill.hip @@ -1,7 +1,3 @@ -// SPDX-License-Identifier: Apache-2.0 - -// SPDX-FileCopyrightText: Copyright contributors to the vLLM project - // Chunked Gated DeltaNet for long prompts after FLA's chunk_gated_delta_rule, in five kernels: prep, kt, wy, h, o. // fp16 operands and fp32 accumulation through v_dot2_f32_f16; the state and every sum stay fp32. From e6c11fb95c8391ee69bb222c8a510168367d626f Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:44:35 +0200 Subject: [PATCH 07/52] feat(qwen3_5): the GPU backends' checkpoint loader, on the host Qwen3.5 / Qwen3.6 text checkpoints for the HIP engine, host side only: the geometry (dense and MoE, MTP layer count, rotary, layer types) from config.json, the MLX affine quantization table per module, one tensor index over the safetensors shards, the projections, the routed experts stacked, and the tensor-parallel cuts on core/quant. `zig build test` runs its tests; TF_QWEN_DIR indexes a real checkpoint. Draft: the geometry is a third Qwen text parser beside qwen27/config.zig and the Metal 2B's admission. #491 proposes one shared config and weight path instead; this is refit to that once agreed. --- zig/build/hip.zig | 9 + zig/src/families/qwen3_5/config.zig | 259 ++++++++++++++++ zig/src/families/qwen3_5/loader.zig | 21 ++ .../families/qwen3_5/weights/checkpoint.zig | 215 +++++++++++++ .../qwen3_5/weights/checkpoint_test.zig | 283 ++++++++++++++++++ zig/src/families/qwen3_5/weights/config.zig | 89 ++++++ zig/src/families/qwen3_5/weights/experts.zig | 193 ++++++++++++ zig/src/families/qwen3_5/weights/host.zig | 102 +++++++ .../families/qwen3_5/weights/projection.zig | 47 +++ .../families/qwen3_5/weights/real_test.zig | 56 ++++ zig/src/families/qwen3_5/weights/shard.zig | 81 +++++ zig/src/families/qwen3_5/weights/slicing.zig | 124 ++++++++ zig/src/families/qwen3_5/weights/table.zig | 136 +++++++++ 13 files changed, 1615 insertions(+) create mode 100644 zig/src/families/qwen3_5/loader.zig create mode 100644 zig/src/families/qwen3_5/weights/checkpoint.zig create mode 100644 zig/src/families/qwen3_5/weights/checkpoint_test.zig create mode 100644 zig/src/families/qwen3_5/weights/config.zig create mode 100644 zig/src/families/qwen3_5/weights/experts.zig create mode 100644 zig/src/families/qwen3_5/weights/host.zig create mode 100644 zig/src/families/qwen3_5/weights/projection.zig create mode 100644 zig/src/families/qwen3_5/weights/real_test.zig create mode 100644 zig/src/families/qwen3_5/weights/shard.zig create mode 100644 zig/src/families/qwen3_5/weights/slicing.zig create mode 100644 zig/src/families/qwen3_5/weights/table.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index c0d82db7318..91d7017309f 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -27,6 +27,15 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const run_hip_tests = b.addRunArtifact(hip_tests); test_step.dependOn(&run_hip_tests.step); b.step("hip-host-test", "HIP admission tests without GPU work").dependOn(&run_hip_tests.step); + const loader = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/families/qwen3_5/loader.zig"), + .target = b.graph.host, + .link_libc = true, + .imports = &.{.{ .name = "core", .module = coreModule(b, b.graph.host) }}, + }) })); + loader.has_side_effects = true; // TF_QWEN_DIR is not a cached input + test_step.dependOn(&loader.step); + b.step("test-qwen35", "Qwen3.5 / 3.6 checkpoint loader tests; TF_QWEN_DIR indexes a real checkpoint").dependOn(&loader.step); const hipcc = b.option([]const u8, "hipcc", "HIP compiler for model-free tests") orelse "hipcc"; const hipcc_resolved = b.findProgram(.{ .names = &.{hipcc} }) orelse hipcc; const hip_include = b.option([]const u8, "hip-include", "HIP header directory") orelse diff --git a/zig/src/families/qwen3_5/config.zig b/zig/src/families/qwen3_5/config.zig index 438b0ddd762..aa697ef49c6 100644 --- a/zig/src/families/qwen3_5/config.zig +++ b/zig/src/families/qwen3_5/config.zig @@ -258,3 +258,262 @@ test "admit untied heads and refuse a root and language tiedness disagreement" { defer gpa.free(mismatch); try std.testing.expectError(error.BadQwenConfig, parse(gpa, mismatch)); } + +// The geometry any backend reads, with its defaults and checks; Metal's admission above is stricter (one geometry). + +pub const Error = error{ + InvalidConfig, + MissingField, + UnsupportedModel, + InvalidMoe, + InvalidRotary, + InvalidLayerTypes, +} || std.mem.Allocator.Error || std.json.ParseError(std.json.Scanner); + +/// The Python `Spec`, plus the shared expert's width and the MTP layer count the config declares. +pub const Spec = struct { + hidden: usize, + intermediate: usize, + n_layers: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + key_heads: usize, + value_heads: usize, + key_dim: usize, + value_dim: usize, + conv: usize, + vocab: usize, + eps: f64, + rope_theta: f64, + rotary_dim: usize, + full_every: usize, + bits: u8, + group: u16, + experts: usize, + top_k: usize, + moe_width: usize, + shared_width: usize, + mtp_layers: usize, + + /// Whether layer `index` is full attention (the others are gated delta-net). + pub fn full(s: Spec, index: usize) bool { + return (index + 1) % s.full_every == 0; + } + + pub fn keyWidth(s: Spec) usize { + return s.key_heads * s.key_dim; + } + + pub fn valueWidth(s: Spec) usize { + return s.value_heads * s.value_dim; + } +}; + +/// The config's root object, when its model_type is a Qwen3.5 text model, dense or sparse. +pub fn declared(a: std.mem.Allocator, bytes: []const u8) Error!std.json.ObjectMap { + const doc = try objectOf(try std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{})); + const kind = doc.get("model_type") orelse return error.UnsupportedModel; + if (kind != .string or !(eql(kind.string, "qwen3_5") or eql(kind.string, "qwen3_5_moe"))) return error.UnsupportedModel; + return doc; +} + +/// The text tower's object: `text_config` when the config has one, else the root itself. +pub fn textTower(doc: std.json.ObjectMap) Error!std.json.ObjectMap { + return if (truthy(doc.get("text_config"))) try objectOf(doc.get("text_config").?) else doc; +} + +/// `cfg.get(key) or text.get(key) or {}`, an object. +pub fn pickObject(doc: std.json.ObjectMap, tower: std.json.ObjectMap, key: []const u8) Error!std.json.ObjectMap { + for ([_]std.json.ObjectMap{ doc, tower }) |source| if (truthy(source.get(key))) return objectOf(source.get(key).?); + return std.json.ObjectMap.empty; +} + +/// `tie_word_embeddings`: the output head is the embedding (the default). +pub fn isTied(doc: std.json.ObjectMap, tower: std.json.ObjectMap) bool { + return if (doc.get("tie_word_embeddings")) |v| truthyValue(v) else if (tower.get("tie_word_embeddings")) |v| truthyValue(v) else true; +} + +/// The Spec of a text tower whose weights are `bits` wide in groups of `group_size`. +pub fn geometry(tower: std.json.ObjectMap, bits: u8, group_size: u16) Error!Spec { + const experts = try optionalInt(tower, "num_experts", 0); + const top_k = try optionalInt(tower, "num_experts_per_tok", 0); + const moe_width = try optionalInt(tower, "moe_intermediate_size", 0); + if (experts != 0) { + if (top_k == 0 or top_k > experts or moe_width == 0) return error.InvalidMoe; + if (tower.get("norm_topk_prob")) |v| if (!truthyValue(v)) return error.InvalidMoe; + } + const model_width = try requiredInt(tower, "hidden_size"); + const attn_heads = try requiredInt(tower, "num_attention_heads"); + const per_head = if (truthy(tower.get("head_dim"))) try toInt(tower.get("head_dim").?) else model_width / attn_heads; + const rope = if (truthy(tower.get("rope_parameters"))) try objectOf(tower.get("rope_parameters").?) else std.json.ObjectMap.empty; + const partial = try numberOf(rope.get("partial_rotary_factor") orelse tower.get("partial_rotary_factor") orelse .{ .float = 0.25 }); + const product = @as(f64, @floatFromInt(per_head)) * partial; + if (!(product >= 0 and product <= @as(f64, @floatFromInt(per_head)))) return error.InvalidRotary; + const rotary: usize = @intFromFloat(product); + const base = try numberOf(rope.get("rope_theta") orelse if (truthy(tower.get("rope_theta"))) tower.get("rope_theta").? else .{ .integer = 10_000_000 }); + const spec: Spec = .{ + .hidden = model_width, + .intermediate = try optionalInt(tower, "intermediate_size", 0), + .n_layers = try requiredInt(tower, "num_hidden_layers"), + .heads = attn_heads, + .kv_heads = try requiredInt(tower, "num_key_value_heads"), + .head_dim = per_head, + .key_heads = try requiredInt(tower, "linear_num_key_heads"), + .value_heads = try requiredInt(tower, "linear_num_value_heads"), + .key_dim = try requiredInt(tower, "linear_key_head_dim"), + .value_dim = try requiredInt(tower, "linear_value_head_dim"), + .conv = try requiredInt(tower, "linear_conv_kernel_dim"), + .vocab = try requiredInt(tower, "vocab_size"), + .eps = try numberOf(tower.get("rms_norm_eps") orelse .{ .float = 1e-6 }), + .rope_theta = base, + .rotary_dim = rotary, + .full_every = try optionalInt(tower, "full_attention_interval", 4), + .bits = bits, + .group = group_size, + .experts = experts, + .top_k = top_k, + .moe_width = moe_width, + .shared_width = try optionalInt(tower, "shared_expert_intermediate_size", 0), + .mtp_layers = try optionalInt(tower, "mtp_num_hidden_layers", 0), + }; + if (rotary % 2 != 0 or rotary == 0 or rotary > per_head) return error.InvalidRotary; + if (spec.full_every == 0 or attn_heads == 0) return error.InvalidConfig; + if (tower.get("layer_types")) |kinds| if (kinds != .null) { + if (kinds != .array) return error.InvalidLayerTypes; + for (kinds.array.items, 0..) |item, i| { + const want = if (spec.full(i)) "full_attention" else "linear_attention"; + if (item != .string or !eql(item.string, want)) return error.InvalidLayerTypes; + } + }; + return spec; +} + +fn eql(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +fn objectOf(v: std.json.Value) Error!std.json.ObjectMap { + return if (v == .object) v.object else error.InvalidConfig; +} + +/// Python truthiness of an optional JSON value (`x.get(k) or default`). +fn truthy(v: ?std.json.Value) bool { + return if (v) |value| truthyValue(value) else false; +} + +fn truthyValue(v: std.json.Value) bool { + return switch (v) { + .null => false, + .bool => |b| b, + .integer => |i| i != 0, + .float => |f| f != 0, + .string => |s| s.len > 0, + .array => |x| x.items.len > 0, + .object => |o| o.count() > 0, + else => true, + }; +} + +/// Python `int(x)` of a JSON number. +fn toInt(v: std.json.Value) Error!usize { + return switch (v) { + .integer => |i| std.math.cast(usize, i) orelse error.InvalidConfig, + .float => |f| if (f >= 0 and f < 1e15) @intFromFloat(f) else error.InvalidConfig, + else => error.InvalidConfig, + }; +} + +fn numberOf(v: std.json.Value) Error!f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.InvalidConfig, + }; +} + +fn requiredInt(o: std.json.ObjectMap, name: []const u8) Error!usize { + return toInt(o.get(name) orelse return error.MissingField); +} + +/// `int(o.get(name, default) or 0)`: absent is `default`, null or zero is 0. +fn optionalInt(o: std.json.ObjectMap, name: []const u8, default: usize) Error!usize { + const v = o.get(name) orelse return default; + return if (truthyValue(v)) toInt(v) else 0; +} + +const sample_text = + \\{"model_type": "qwen3_5", "tie_word_embeddings": false, + \\ "text_config": {"hidden_size": 4096, "intermediate_size": 12288, "num_hidden_layers": 8, + \\ "num_attention_heads": 16, "num_key_value_heads": 4, "head_dim": 256, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 248320, + \\ "rms_norm_eps": 1e-06, "full_attention_interval": 4, "mtp_num_hidden_layers": 1, + \\ "layer_types": ["linear_attention", "linear_attention", "linear_attention", "full_attention", + \\ "linear_attention", "linear_attention", "linear_attention", "full_attention"], + \\ "rope_parameters": {"rope_theta": 10000000, "partial_rotary_factor": 0.25}}} +; + +test "text_config parses into the Python Spec" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const doc = try declared(arena.allocator(), sample_text); + const tower = try textTower(doc); + const s = try geometry(tower, 4, 64); + try std.testing.expectEqual(@as(usize, 4096), s.hidden); + try std.testing.expectEqual(@as(usize, 12288), s.intermediate); + try std.testing.expectEqual(@as(usize, 64), s.rotary_dim); + try std.testing.expectEqual(@as(usize, 256), s.head_dim); + try std.testing.expectEqual(@as(usize, 2048), s.keyWidth()); + try std.testing.expectEqual(@as(usize, 4096), s.valueWidth()); + try std.testing.expectEqual(@as(f64, 10_000_000), s.rope_theta); + try std.testing.expectEqual(@as(f64, 1e-6), s.eps); + try std.testing.expectEqual(@as(u8, 4), s.bits); + try std.testing.expectEqual(@as(u16, 64), s.group); + try std.testing.expectEqual(@as(usize, 0), s.experts); + try std.testing.expectEqual(@as(usize, 1), s.mtp_layers); + try std.testing.expect(!isTied(doc, tower)); + try std.testing.expect(s.full(3) and s.full(7) and !s.full(0) and !s.full(4)); +} + +test "a top-level config, the partial rotary default and the MoE fields" { + const text = + \\{"model_type": "qwen3_5_moe", + \\ "hidden_size": 2048, "num_hidden_layers": 4, "num_attention_heads": 16, "num_key_value_heads": 2, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 1000, "rope_theta": 5000000, + \\ "partial_rotary_factor": 0.5, "num_experts": 256, "num_experts_per_tok": 8, + \\ "moe_intermediate_size": 512, "shared_expert_intermediate_size": 512} + ; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const doc = try declared(arena.allocator(), text); + const tower = try textTower(doc); + const s = try geometry(tower, 8, 64); + try std.testing.expect(isTied(doc, tower)); + try std.testing.expectEqual(@as(usize, 128), s.head_dim); + try std.testing.expectEqual(@as(usize, 64), s.rotary_dim); + try std.testing.expectEqual(@as(f64, 5_000_000), s.rope_theta); + try std.testing.expectEqual(@as(usize, 256), s.experts); + try std.testing.expectEqual(@as(usize, 8), s.top_k); + try std.testing.expectEqual(@as(usize, 512), s.moe_width); + try std.testing.expectEqual(@as(usize, 512), s.shared_width); + try std.testing.expectEqual(@as(usize, 0), s.intermediate); + try std.testing.expectEqual(@as(usize, 4), s.full_every); +} + +test "the Python loader's refusals" { + const a = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const wrong = try std.mem.replaceOwned(u8, a, sample_text, "\"qwen3_5\"", "\"llama\""); + defer a.free(wrong); + try std.testing.expectError(error.UnsupportedModel, declared(arena.allocator(), wrong)); + const types = try std.mem.replaceOwned(u8, a, sample_text, "\"full_attention\"],", "\"linear_attention\"],"); + defer a.free(types); + const tower = try textTower(try declared(arena.allocator(), types)); + try std.testing.expectError(error.InvalidLayerTypes, geometry(tower, 4, 64)); + const moe = try std.mem.replaceOwned(u8, a, sample_text, "\"vocab_size\"", "\"num_experts\": 8, \"num_experts_per_tok\": 9, \"vocab_size\""); + defer a.free(moe); + try std.testing.expectError(error.InvalidMoe, geometry(try textTower(try declared(arena.allocator(), moe)), 4, 64)); +} diff --git a/zig/src/families/qwen3_5/loader.zig b/zig/src/families/qwen3_5/loader.zig new file mode 100644 index 00000000000..a6d5f0f0c48 --- /dev/null +++ b/zig/src/families/qwen3_5/loader.zig @@ -0,0 +1,21 @@ +//! Qwen3.5 / Qwen3.6 text checkpoints on the host for the GPU backends: configuration, tensor index, projections, cuts. + +pub const config = @import("weights/config.zig"); +pub const table = @import("weights/table.zig"); +pub const host = @import("weights/host.zig"); +pub const checkpoint = @import("weights/checkpoint.zig"); +pub const slicing = @import("weights/slicing.zig"); +pub const Config = config.Config; +pub const Spec = config.Spec; +pub const Checkpoint = checkpoint.Checkpoint; + +test { + _ = config; + _ = table; + _ = @import("weights/shard.zig"); + _ = @import("weights/projection.zig"); + _ = @import("weights/checkpoint_test.zig"); + _ = @import("weights/real_test.zig"); + @import("std").testing.refAllDecls(slicing); + _ = @import("config.zig"); +} diff --git a/zig/src/families/qwen3_5/weights/checkpoint.zig b/zig/src/families/qwen3_5/weights/checkpoint.zig new file mode 100644 index 00000000000..bc20b6c640a --- /dev/null +++ b/zig/src/families/qwen3_5/weights/checkpoint.zig @@ -0,0 +1,215 @@ +//! A Qwen3.5 / Qwen3.6 checkpoint on the host: the Python ROCm loader's tensor names, fallbacks and conversions. + +const std = @import("std"); +const config = @import("config.zig"); +const table = @import("table.zig"); +const host = @import("host.zig"); +const projection = @import("projection.zig"); +const experts = @import("experts.zig"); + +const Tensor = table.Tensor; +const Table = table.Table; +/// The text tower's key prefix, as the MLX conversions name it. +pub const prefix = "language_model.model."; + +pub const Checkpoint = struct { + gpa: std.mem.Allocator, + io: std.Io, + config: config.Config, + files: table.Files, + main: Table, + + /// Reads config.json and maps the model's own safetensors files. + pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Checkpoint { + var cfg = try config.Config.read(gpa, io, dir); + errdefer cfg.deinit(); + var files = try table.Files.list(gpa, io, dir); + errdefer files.deinit(); + if (files.model.len == 0) return error.NoSafetensors; + const main = try Table.open(gpa, io, files.model, "", cfg.quant); + return .{ .gpa = gpa, .io = io, .config = cfg, .files = files, .main = main }; + } + + pub fn close(c: *Checkpoint) void { + c.main.close(c.io); + c.files.deinit(); + c.config.deinit(); + c.* = undefined; + } + + pub fn spec(c: *const Checkpoint) config.Spec { + return c.config.spec; + } + + /// The embedding, MLX affine words or a float table the row gather reads; `a` holds any converted tables. + pub fn embed(c: *const Checkpoint, a: std.mem.Allocator) !host.Projection { + const p = try projection.projection(a, &c.main, prefix ++ "embed_tokens"); + if (p.rows() != c.spec().vocab) return error.UnexpectedTensor; + return p; + } + + pub fn finalNorm(c: *const Checkpoint, a: std.mem.Allocator) !Tensor { + return projection.float(a, &c.main, prefix ++ "norm.weight"); + } + + /// The output head, or null when it is the embedding (`tie_word_embeddings`). + pub fn head(c: *const Checkpoint, a: std.mem.Allocator) !?host.Projection { + if (c.config.tied) return null; + return try projection.projection(a, &c.main, "language_model.lm_head"); + } + + /// Layer `index`, read and converted; free it with `deinit`. + pub fn layer(c: *const Checkpoint, index: usize) !host.Layer { + const s = c.spec(); + if (index >= s.n_layers) return error.InvalidModel; + var arena: std.heap.ArenaAllocator = .init(c.gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const t = &c.main; + var name: [128]u8 = undefined; + const base = std.fmt.bufPrint(&name, prefix ++ "layers.{d}.", .{index}) catch unreachable; + var scratch: [160]u8 = undefined; + const input_norm = try projection.float(a, t, projection.join(&scratch, &.{ base, "input_layernorm.weight" })); + const post_norm = try projection.float(a, t, projection.join(&scratch, &.{ base, "post_attention_layernorm.weight" })); + const mlp = try readMlp(a, t, projection.join(&scratch, &.{ base, "mlp." }), s); + if (s.full(index)) { + const attn = projection.join(&scratch, &.{ base, "self_attn." }); + const body: host.Body = .{ .full = .{ + .input_norm = input_norm, + .post_norm = post_norm, + .q = try sub(a, t, attn, "q_proj"), + .k = try sub(a, t, attn, "k_proj"), + .v = try sub(a, t, attn, "v_proj"), + .o = try sub(a, t, attn, "o_proj"), + .q_norm = try subFloat(a, t, attn, "q_norm.weight"), + .k_norm = try subFloat(a, t, attn, "k_norm.weight"), + .mlp = mlp, + } }; + return .{ .arena = arena, .body = body }; + } + const lin = projection.join(&scratch, &.{ base, "linear_attn." }); + // the arena is copied into the result last: allocations made after the copy would be lost + const body: host.Body = .{ .linear = .{ + .input_norm = input_norm, + .post_norm = post_norm, + .qkv = try sub(a, t, lin, "in_proj_qkv"), + .z = try sub(a, t, lin, "in_proj_z"), + .a = try sub(a, t, lin, "in_proj_a"), + .b = try sub(a, t, lin, "in_proj_b"), + .conv = try subConv(a, t, lin), + .a_log = try subFloat(a, t, lin, "A_log"), + .dt_bias = try subFloat(a, t, lin, "dt_bias"), + .gnorm = try subFloat(a, t, lin, "norm.weight"), + .out = try sub(a, t, lin, "out_proj"), + .mlp = mlp, + } }; + return .{ .arena = arena, .body = body }; + } + + /// The MTP layer from `mtp*.safetensors` or the model's own shards; null when absent. + pub fn mtp(c: *const Checkpoint) !?host.Mtp { + const side = c.files.side; + const shards = if (side.len > 0) side else c.files.model; + if (shards.len == 0) return null; + const own = c.main.has("mtp.norm_e.weight") or c.main.has("mtp.pre_fc_norm_embedding.weight"); + var opened: ?Table = null; + errdefer if (opened) |*o| o.close(c.io); + var t = &c.main; + if (side.len > 0 or !own) { + opened = try Table.open(c.gpa, c.io, shards, "language_model.", c.config.quant); + t = &opened.?; + } + if (side.len == 0 and !t.has("mtp.norm_e.weight") and !t.has("mtp.pre_fc_norm_embedding.weight")) { + if (opened) |*o| o.close(c.io); + return null; + } + var arena: std.heap.ArenaAllocator = .init(c.gpa); + errdefer arena.deinit(); + var m = try readMtp(arena.allocator(), t, c.spec()); + m.arena = arena; + m.owned = opened; + m.io = c.io; + return m; + } +}; + +fn sub(a: std.mem.Allocator, t: *const Table, base: []const u8, name: []const u8) !host.Projection { + var buf: [192]u8 = undefined; + return projection.projection(a, t, projection.join(&buf, &.{ base, name })); +} + +fn subFloat(a: std.mem.Allocator, t: *const Table, base: []const u8, name: []const u8) !Tensor { + var buf: [192]u8 = undefined; + return projection.float(a, t, projection.join(&buf, &.{ base, name })); +} + +fn subConv(a: std.mem.Allocator, t: *const Table, base: []const u8) !Tensor { + var buf: [192]u8 = undefined; + return projection.conv(a, t, projection.join(&buf, &.{ base, "conv1d.weight" })); +} + +/// The routed MLP when the config has experts, else gate, up and down. +fn readMlp(a: std.mem.Allocator, t: *const Table, mlp: []const u8, s: config.Spec) !host.Mlp { + if (s.experts != 0) return .{ .routed = try experts.routed(a, t, mlp, s) }; + return .{ .dense = .{ + .gate = try sub(a, t, mlp, "gate_proj"), + .up = try sub(a, t, mlp, "up_proj"), + .down = try sub(a, t, mlp, "down_proj"), + } }; +} + +/// The head's tensors under `mtp.`: the Qwen3 shape (`pre_fc_norm_embedding`) or the Flash Next one (`norm_e`). +fn readMtp(a: std.mem.Allocator, t: *const Table, s: config.Spec) !host.Mtp { + const head: ?host.Projection = if (t.has("mtp.head_proj.weight")) try projection.projection(a, t, "mtp.head_proj") else null; + if (!t.has("mtp.pre_fc_norm_embedding.weight")) { + return .{ + .arena = undefined, + .io = undefined, + .fc_e_norm = try projection.float(a, t, "mtp.norm_e.weight"), + .fc_h_norm = try projection.float(a, t, "mtp.norm_h.weight"), + .fc_e = try projection.projection(a, t, "mtp.fc_e"), + .fc_h = try projection.projection(a, t, "mtp.fc_h"), + .q_norm = try projection.float(a, t, "mtp.q_norm.weight"), + .k_norm = try projection.float(a, t, "mtp.k_norm.weight"), + .q = try projection.projection(a, t, "mtp.q_proj"), + .k = try projection.projection(a, t, "mtp.k_proj"), + .v = try projection.projection(a, t, "mtp.v_proj"), + .o = try projection.projection(a, t, "mtp.o_proj"), + .final_norm = try projection.float(a, t, "mtp.final_norm.weight"), + .head = head, + .input_norm = null, + .post_norm = null, + .mlp = null, + .gated = false, + }; + } + const layer = "mtp.layers.0."; + const attn = layer ++ "self_attn."; + const mlp = layer ++ "mlp."; + const halves = try projection.halves(a, try projection.projection(a, t, "mtp.fc")); + const routed = t.has(mlp ++ "switch_mlp.up_proj.weight") or t.has(mlp ++ "switch_mlp.up_proj.qweight"); + return .{ + .arena = undefined, + .io = undefined, + .fc_e_norm = try projection.float(a, t, "mtp.pre_fc_norm_embedding.weight"), + .fc_h_norm = try projection.float(a, t, "mtp.pre_fc_norm_hidden.weight"), + .fc_e = halves[0], + .fc_h = halves[1], + .q_norm = try projection.float(a, t, attn ++ "q_norm.weight"), + .k_norm = try projection.float(a, t, attn ++ "k_norm.weight"), + .q = try projection.projection(a, t, attn ++ "q_proj"), + .k = try projection.projection(a, t, attn ++ "k_proj"), + .v = try projection.projection(a, t, attn ++ "v_proj"), + .o = try projection.projection(a, t, attn ++ "o_proj"), + .final_norm = try projection.float(a, t, "mtp.norm.weight"), + .head = head, + .input_norm = try projection.float(a, t, layer ++ "input_layernorm.weight"), + .post_norm = try projection.float(a, t, layer ++ "post_attention_layernorm.weight"), + .mlp = if (routed) .{ .routed = try experts.routed(a, t, mlp, s) } else .{ .dense = .{ + .gate = try projection.projection(a, t, mlp ++ "gate_proj"), + .up = try projection.projection(a, t, mlp ++ "up_proj"), + .down = try projection.projection(a, t, mlp ++ "down_proj"), + } }, + .gated = true, + }; +} diff --git a/zig/src/families/qwen3_5/weights/checkpoint_test.zig b/zig/src/families/qwen3_5/weights/checkpoint_test.zig new file mode 100644 index 00000000000..8a5b3f7397d --- /dev/null +++ b/zig/src/families/qwen3_5/weights/checkpoint_test.zig @@ -0,0 +1,283 @@ +//! Host tests of the checkpoint index on small synthetic safetensors files, checked against the Python loader's rules. + +const std = @import("std"); +const checkpoint = @import("checkpoint.zig"); +const convert = @import("core").quant.convert; +const host = @import("host.zig"); +const DType = @import("table.zig").DType; + +const io = std.testing.io; +const gpa = std.testing.allocator; + +/// One tensor of a synthetic file: `bytes` (or `size` bytes of a name-seeded pattern). +const Entry = struct { name: []const u8, dtype: []const u8, shape: []const usize, bytes: []const u8 = &.{} }; + +const Image = struct { + arena: std.heap.ArenaAllocator, + entries: std.ArrayList(Entry) = .empty, + + fn init() Image { + return .{ .arena = .init(gpa) }; + } + + fn deinit(m: *Image) void { + m.arena.deinit(); + } + + fn elems(shape: []const usize) usize { + var n: usize = 1; + for (shape) |d| n *= d; + return n; + } + + /// A tensor whose bytes are a pattern seeded by its name (`bits` per element for the size). + fn put(m: *Image, name: []const u8, dtype: []const u8, shape: []const usize) !void { + const a = m.arena.allocator(); + const size: usize = if (std.mem.eql(u8, dtype, "BF16")) 2 else 4; + const bytes = try a.alloc(u8, elems(shape) * size); + var seed: u8 = 0; + for (name) |c| seed +%= c; + for (bytes, 0..) |*b, i| b.* = seed +% @as(u8, @truncate(i * 7)); + // bf16 patterns stay finite: a high byte under 0x40 is a small positive number + if (size == 2) for (bytes[1..], 0..) |*b, i| { + if (i % 2 == 0) b.* &= 0x3F; + }; + try m.entries.append(a, .{ .name = try a.dupe(u8, name), .dtype = dtype, .shape = try a.dupe(usize, shape), .bytes = bytes }); + } + + /// An affine projection [n, k] at `bits`: words, scales and biases. + fn affine(m: *Image, name: []const u8, n: usize, k: usize, bits: usize, group: usize) !void { + var buf: [160]u8 = undefined; + try m.put(try std.fmt.bufPrint(&buf, "{s}.weight", .{name}), "U32", &.{ n, k * bits / 32 }); + try m.put(try std.fmt.bufPrint(&buf, "{s}.scales", .{name}), "BF16", &.{ n, k / group }); + try m.put(try std.fmt.bufPrint(&buf, "{s}.biases", .{name}), "BF16", &.{ n, k / group }); + } + + fn find(m: *const Image, name: []const u8) []const u8 { + for (m.entries.items) |e| if (std.mem.eql(u8, e.name, name)) return e.bytes; + unreachable; + } + + fn write(m: *Image, dir: std.Io.Dir, file: []const u8) !void { + const a = m.arena.allocator(); + var header: std.ArrayList(u8) = .empty; + var data: std.ArrayList(u8) = .empty; + try header.append(a, '{'); + for (m.entries.items, 0..) |e, i| { + const start = data.items.len; + try data.appendSlice(a, e.bytes); + try header.print(a, "{s}\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[", .{ if (i > 0) "," else "", e.name, e.dtype }); + for (e.shape, 0..) |d, j| try header.print(a, "{s}{d}", .{ if (j > 0) "," else "", d }); + try header.print(a, "],\"data_offsets\":[{d},{d}]}}", .{ start, data.items.len }); + } + try header.append(a, '}'); + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(a, &std.mem.toBytes(std.mem.nativeToLittle(u64, header.items.len))); + try out.appendSlice(a, header.items); + try out.appendSlice(a, data.items); + try dir.writeFile(io, .{ .sub_path = file, .data = out.items }); + } +}; + +const dense_config = + \\{"model_type": "qwen3_5", "tie_word_embeddings": true, + \\ "quantization": {"group_size": 32, "bits": 4, "mode": "affine"}, + \\ "text_config": {"hidden_size": 64, "intermediate_size": 32, "num_hidden_layers": 2, + \\ "num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, + \\ "linear_num_value_heads": 2, "linear_key_head_dim": 32, "linear_value_head_dim": 16, + \\ "linear_conv_kernel_dim": 4, "vocab_size": 16, "full_attention_interval": 2, + \\ "layer_types": ["linear_attention", "full_attention"]}} +; + +const moe_config = + \\{"model_type": "qwen3_5_moe", "tie_word_embeddings": true, + \\ "quantization": {"group_size": 32, "bits": 4, "mode": "affine", + \\ "language_model.model.layers.0.mlp.gate": {"group_size": 32, "bits": 8}, + \\ "language_model.model.layers.0.mlp.shared_expert_gate": {"group_size": 32, "bits": 8}}, + \\ "text_config": {"hidden_size": 64, "num_hidden_layers": 1, "num_attention_heads": 2, + \\ "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, "linear_num_value_heads": 2, + \\ "linear_key_head_dim": 32, "linear_value_head_dim": 16, "linear_conv_kernel_dim": 4, "vocab_size": 16, + \\ "full_attention_interval": 1, "num_experts": 2, "num_experts_per_tok": 1, "moe_intermediate_size": 32, + \\ "shared_expert_intermediate_size": 32}} +; + +const L = "language_model.model."; + +fn attention(m: *Image, base: []const u8) !void { + var buf: [160]u8 = undefined; + const shapes = [_]struct { []const u8, usize }{ .{ "q_proj", 64 }, .{ "k_proj", 32 }, .{ "v_proj", 32 }, .{ "o_proj", 64 } }; + for (shapes) |p| try m.affine(try std.fmt.bufPrint(&buf, "{s}self_attn.{s}", .{ base, p[0] }), p[1], 64, 4, 32); + try m.put(try std.fmt.bufPrint(&buf, "{s}self_attn.q_norm.weight", .{base}), "BF16", &.{32}); + try m.put(try std.fmt.bufPrint(&buf, "{s}self_attn.k_norm.weight", .{base}), "BF16", &.{32}); +} + +fn norms(m: *Image, base: []const u8) !void { + var buf: [160]u8 = undefined; + try m.put(try std.fmt.bufPrint(&buf, "{s}input_layernorm.weight", .{base}), "BF16", &.{64}); + try m.put(try std.fmt.bufPrint(&buf, "{s}post_attention_layernorm.weight", .{base}), "BF16", &.{64}); +} + +fn trunk(m: *Image) !void { + try m.affine(L ++ "embed_tokens", 16, 64, 4, 32); + try m.put(L ++ "norm.weight", "BF16", &.{64}); +} + +test "a dense model: layers, embedding, tied head and the MTP side file" { + var img = Image.init(); + defer img.deinit(); + var side = Image.init(); + defer side.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try trunk(&img); + try norms(&img, L ++ "layers.0."); + const lin = L ++ "layers.0.linear_attn."; + try img.affine(lin ++ "in_proj_qkv", 96, 64, 4, 32); + try img.affine(lin ++ "in_proj_z", 32, 64, 4, 32); + try img.affine(lin ++ "in_proj_a", 2, 64, 4, 32); + try img.affine(lin ++ "in_proj_b", 2, 64, 4, 32); + try img.put(lin ++ "conv1d.weight", "BF16", &.{ 96, 4, 1 }); + try img.put(lin ++ "A_log", "BF16", &.{2}); + try img.put(lin ++ "dt_bias", "BF16", &.{2}); + try img.put(lin ++ "norm.weight", "BF16", &.{16}); + try img.affine(lin ++ "out_proj", 64, 32, 4, 32); + inline for (.{ "layers.0.", "layers.1." }) |l| { + try img.affine(L ++ l ++ "mlp.gate_proj", 32, 64, 4, 32); + try img.affine(L ++ l ++ "mlp.up_proj", 32, 64, 4, 32); + try img.affine(L ++ l ++ "mlp.down_proj", 64, 32, 4, 32); + } + try norms(&img, L ++ "layers.1."); + try attention(&img, L ++ "layers.1."); + try img.put("vision_tower.patch_embed.weight", "BF16", &.{4}); + + try side.put("mtp.pre_fc_norm_embedding.weight", "BF16", &.{64}); + try side.put("mtp.pre_fc_norm_hidden.weight", "BF16", &.{64}); + try side.put("mtp.norm.weight", "BF16", &.{64}); + try side.affine("mtp.fc", 64, 128, 4, 32); + try norms(&side, "mtp.layers.0."); + try attention(&side, "mtp.layers.0."); + try side.affine("mtp.layers.0.mlp.gate_proj", 32, 64, 4, 32); + try side.affine("mtp.layers.0.mlp.up_proj", 32, 64, 4, 32); + try side.affine("mtp.layers.0.mlp.down_proj", 64, 32, 4, 32); + + try img.write(tmp.dir, "model.safetensors"); + try side.write(tmp.dir, "mtp.safetensors"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = dense_config }); + const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(root); + + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + try std.testing.expectEqual(@as(u8, 4), embed.mlx.bits); + try std.testing.expectEqual(host.Tensor{ .dtype = .i32, .rank = 2, .shape = .{ 16, 8, 1, 1, 1 }, .bytes = embed.mlx.words.bytes }, embed.mlx.words); + try std.testing.expect(try ck.head(scratch.allocator()) == null); + const final = try ck.finalNorm(scratch.allocator()); + try std.testing.expectEqual(convert.load(.bf16, img.find(L ++ "norm.weight"), 5), convert.load(.f32, final.bytes, 5)); + + var l0 = try ck.layer(0); + defer l0.deinit(); + const x = l0.body.linear; + // the conv weight loses its trailing 1 and is widened to fp32 + try std.testing.expectEqual(@as(u8, 2), x.conv.rank); + try std.testing.expectEqual(DType.f32, x.conv.dtype); + try std.testing.expectEqual(@as(usize, 4), x.conv.shape[1]); + try std.testing.expectEqual(convert.load(.bf16, img.find(lin ++ "conv1d.weight"), 9), convert.load(.f32, x.conv.bytes, 9)); + try std.testing.expectEqual(@as(usize, 96), x.qkv.mlx.words.shape[0]); + try std.testing.expectEqualSlices(u8, img.find(lin ++ "in_proj_qkv.weight"), x.qkv.mlx.words.bytes); + try std.testing.expectEqual(DType.bf16, x.qkv.mlx.scales.dtype); + try std.testing.expectEqual(@as(usize, 16), x.gnorm.numel()); + try std.testing.expect(x.mlp == .dense); + + var l1 = try ck.layer(1); + defer l1.deinit(); + try std.testing.expectEqual(@as(usize, 64), l1.body.full.q.rows()); + try std.testing.expectError(error.InvalidModel, ck.layer(2)); + + var head = (try ck.mtp()).?; + defer head.deinit(); + try std.testing.expect(head.gated and head.head == null and head.mlp.? == .dense); + // fc [64, 128] splits into two [64, 64] halves, row by row, words and tables on the same boundary + const words = side.find("mtp.fc.weight"); + const scales = side.find("mtp.fc.scales"); + for ([_]usize{ 0, 63 }) |r| { + try std.testing.expectEqualSlices(u8, words[r * 64 ..][0..32], head.fc_e.mlx.words.bytes[r * 32 ..][0..32]); + try std.testing.expectEqualSlices(u8, words[r * 64 + 32 ..][0..32], head.fc_h.mlx.words.bytes[r * 32 ..][0..32]); + try std.testing.expectEqualSlices(u8, scales[r * 8 + 4 ..][0..4], head.fc_h.mlx.scales.bytes[r * 4 ..][0..4]); + } +} + +test "MoE experts: gate and up fused per expert, the shared expert last, router rows with the shared gate last" { + var img = Image.init(); + defer img.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const base = L ++ "layers.0."; + const mlp = base ++ "mlp."; + try trunk(&img); + try norms(&img, base); + try attention(&img, base); + try img.affine(mlp ++ "gate", 2, 64, 8, 32); + try img.affine(mlp ++ "shared_expert_gate", 1, 64, 8, 32); + for ([_][]const u8{ "gate_proj", "up_proj" }) |p| { + var buf: [160]u8 = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }) |part| { + const small = std.mem.eql(u8, part, "weight"); + try img.put(try std.fmt.bufPrint(&buf, "{s}switch_mlp.{s}.{s}", .{ mlp, p, part }), if (small) "U32" else "BF16", if (small) &.{ 2, 32, 8 } else &.{ 2, 32, 2 }); + try img.put(try std.fmt.bufPrint(&buf, "{s}shared_expert.{s}.{s}", .{ mlp, p, part }), if (small) "U32" else "BF16", if (small) &.{ 32, 8 } else &.{ 32, 2 }); + } + } + for ([_][]const u8{ "weight", "scales", "biases" }) |part| { + var buf: [160]u8 = undefined; + const small = std.mem.eql(u8, part, "weight"); + try img.put(try std.fmt.bufPrint(&buf, "{s}switch_mlp.down_proj.{s}", .{ mlp, part }), if (small) "U32" else "BF16", if (small) &.{ 2, 64, 4 } else &.{ 2, 64, 1 }); + // the shared expert may carry a leading 1 + try img.put(try std.fmt.bufPrint(&buf, "{s}shared_expert.down_proj.{s}", .{ mlp, part }), if (small) "U32" else "BF16", if (small) &.{ 1, 64, 4 } else &.{ 1, 64, 1 }); + } + try img.write(tmp.dir, "model.safetensors"); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = moe_config }); + const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(root); + + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + try std.testing.expect(try ck.mtp() == null); + var layer = try ck.layer(0); + defer layer.deinit(); + const r = layer.body.full.mlp.routed; + const e = r.experts; + try std.testing.expect(e.gated and e.count == 3 and e.width == 32 and e.dims == 64); + try std.testing.expectEqual(@as(usize, 3), e.fused.mlx.words.shape[0]); + try std.testing.expectEqual(@as(usize, 64), e.fused.mlx.words.shape[1]); + const per = 32 * 8 * 4; + const gate = img.find(mlp ++ "switch_mlp.gate_proj.weight"); + const up = img.find(mlp ++ "switch_mlp.up_proj.weight"); + const fused = e.fused.mlx.words.bytes; + try std.testing.expectEqualSlices(u8, gate[per .. 2 * per], fused[(2 * per) * 1 ..][0..per]); + try std.testing.expectEqualSlices(u8, up[per .. 2 * per], fused[(2 * per) * 1 + per ..][0..per]); + try std.testing.expectEqualSlices(u8, img.find(mlp ++ "shared_expert.gate_proj.weight"), fused[2 * 2 * per ..][0..per]); + try std.testing.expectEqualSlices(u8, img.find(mlp ++ "shared_expert.up_proj.weight"), fused[2 * 2 * per + per ..][0..per]); + try std.testing.expectEqualSlices(u8, img.find(mlp ++ "shared_expert.down_proj.scales"), e.down.mlx.scales.bytes[2 * 64 * 2 ..][0 .. 64 * 2]); + // the router: 8-bit codes unpacked as s * q + b, rounded to bf16, the shared gate row last + try std.testing.expectEqualSlices(usize, &.{ 3, 64 }, r.router.shape[0..2]); + const words = img.find(mlp ++ "gate.weight"); + const scales = img.find(mlp ++ "gate.scales"); + const biases = img.find(mlp ++ "gate.biases"); + for ([_]usize{ 0, 7, 70, 127 }) |i| { + const row = i / 64; + const code: f32 = @floatFromInt(words[i]); + const g = row * 2 + (i % 64) / 32; + const want = convert.bf16(code * convert.load(.bf16, scales, g) + convert.load(.bf16, biases, g)); + try std.testing.expectEqual(want, std.mem.readInt(u16, r.router.bytes[2 * i ..][0..2], .little)); + try std.testing.expectEqual(@as(u32, want) << 16, std.mem.readInt(u32, r.rows32.bytes[4 * i ..][0..4], .little)); + } + const shared_words = img.find(mlp ++ "shared_expert_gate.weight"); + const last: f32 = @floatFromInt(shared_words[5]); + const sg = 0; + try std.testing.expectEqual( + convert.bf16(last * convert.load(.bf16, img.find(mlp ++ "shared_expert_gate.scales"), sg) + convert.load(.bf16, img.find(mlp ++ "shared_expert_gate.biases"), sg)), + std.mem.readInt(u16, r.router.bytes[2 * (128 + 5) ..][0..2], .little), + ); +} diff --git a/zig/src/families/qwen3_5/weights/config.zig b/zig/src/families/qwen3_5/weights/config.zig new file mode 100644 index 00000000000..337897c09ac --- /dev/null +++ b/zig/src/families/qwen3_5/weights/config.zig @@ -0,0 +1,89 @@ +//! The HIP loader's configuration: the family's geometry (../config.zig) with the checkpoint's quantization table. + +const std = @import("std"); +const quant = @import("core").quant; +const shared = @import("../config.zig"); + +pub const Error = shared.Error || error{UnsupportedQuantization}; + +/// One affine width: MLX groups of `group` weights share a scale and a bias, `bits` per weight. +pub const Width = quant.mlx.Width; + +pub const Spec = shared.Spec; + +pub const Config = struct { + arena: std.heap.ArenaAllocator, + spec: Spec, + quant: quant.Config, + /// `tie_word_embeddings`: the output head is the embedding. + tied: bool, + + pub fn deinit(c: *Config) void { + c.arena.deinit(); + c.* = undefined; + } + + /// The config of the checkpoint directory `dir`. + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 26)); + defer gpa.free(bytes); + return parse(gpa, bytes); + } + + /// `load()`'s reading of config.json: top level or `text_config`, model_type qwen3_5 or qwen3_5_moe. + pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) Error!Config { + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const doc = try shared.declared(a, bytes); + const tower = try shared.textTower(doc); + const table = try quant.detect(a, .{ .root = doc, .quantization = try shared.pickObject(doc, tower, "quantization") }); + const width = try table.width(""); + const spec = try shared.geometry(tower, width.bits, width.group); + return .{ .arena = arena, .spec = spec, .quant = table, .tied = shared.isTied(doc, tower) }; + } +}; + +const sample = + \\{"model_type": "qwen3_5", "tie_word_embeddings": false, + \\ "quantization": {"group_size": 64, "bits": 4, "mode": "affine", + \\ "language_model.model.layers.0.mlp.gate": {"group_size": 32, "bits": 8}, + \\ "vision_tower.x": {"group_size": 64, "bits": 7}}, + \\ "text_config": {"hidden_size": 4096, "intermediate_size": 12288, "num_hidden_layers": 8, + \\ "num_attention_heads": 16, "num_key_value_heads": 4, "head_dim": 256, + \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, + \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 248320, + \\ "rms_norm_eps": 1e-06, "full_attention_interval": 4, "mtp_num_hidden_layers": 1, + \\ "layer_types": ["linear_attention", "linear_attention", "linear_attention", "full_attention", + \\ "linear_attention", "linear_attention", "linear_attention", "full_attention"], + \\ "rope_parameters": {"rope_theta": 10000000, "partial_rotary_factor": 0.25}}} +; + +test "the config carries the geometry, the quantization width and the tying" { + var c = try Config.parse(std.testing.allocator, sample); + defer c.deinit(); + try std.testing.expectEqual(@as(usize, 4096), c.spec.hidden); + try std.testing.expectEqual(@as(u8, 4), c.spec.bits); + try std.testing.expectEqual(@as(u16, 64), c.spec.group); + try std.testing.expect(!c.tied); +} + +test "per-tensor widths override the global one, and a bad entry fails only when used" { + var c = try Config.parse(std.testing.allocator, sample); + defer c.deinit(); + try std.testing.expectEqual(Width{ .bits = 8, .group = 32 }, try c.quant.width("language_model.model.layers.0.mlp.gate")); + try std.testing.expectEqual(Width{ .bits = 4, .group = 64 }, try c.quant.width("language_model.model.layers.1.mlp.gate")); + try std.testing.expectError(error.UnsupportedQuantization, c.quant.width("vision_tower.x")); +} + +test "the Python loader's refusals of a quantization" { + const a = std.testing.allocator; + const bits = try std.mem.replaceOwned(u8, a, sample, "\"bits\": 4,", "\"bits\": 7,"); + defer a.free(bits); + try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, bits)); + const gptq = try std.mem.replaceOwned(u8, a, sample, "\"mode\": \"affine\"", "\"mode\": \"gptq\""); + defer a.free(gptq); + try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, gptq)); +} diff --git a/zig/src/families/qwen3_5/weights/experts.zig b/zig/src/families/qwen3_5/weights/experts.zig new file mode 100644 index 00000000000..16c7afa0153 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/experts.zig @@ -0,0 +1,193 @@ +//! The Python loader's `_routed`, `_experts` and `_affine_side`: router rows and the stacked affine experts. + +const std = @import("std"); +const quant = @import("core").quant; +const table = @import("table.zig"); +const convert = quant.convert; +const config = @import("config.zig"); +const host = @import("host.zig"); +const projection = @import("projection.zig"); + +const Tensor = table.Tensor; +const Table = table.Table; +const DType = table.DType; +pub const Error = projection.Error; + +fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { + std.log.err("{s}: {s}", .{ key, what }); + return error.UnexpectedTensor; +} + +/// `_router_rows`: one router's rows [R, D] as fp32, a float tensor as stored or an affine group table unpacked. +fn routerRows(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!struct { data: []f32, rows: usize, cols: usize } { + var buf: [256]u8 = undefined; + var other: [256]u8 = undefined; + const weight = try t.get(projection.join(&buf, &.{ key, ".weight" })); + if (convert.isFloat(weight.dtype)) { + if (weight.rank != 2) return refuse(key, "router weight must be (rows, hidden)"); + const wide = try convert.float32(a, weight); + const out = try a.alloc(f32, weight.numel()); + for (out, 0..) |*o, i| o.* = convert.load(.f32, wide.bytes, i); + return .{ .data = out, .rows = weight.shape[0], .cols = weight.shape[1] }; + } + const group = (try t.width(key)).group; + const scale = try t.get(projection.join(&buf, &.{ key, ".scales" })); + const bias = try t.get(projection.join(&other, &.{ key, ".biases" })); + const data = try quant.mlx.dequant(a, weight, scale, bias, group); + return .{ .data = data, .rows = weight.shape[0], .cols = scale.shape[1] * group }; +} + +/// The routed stack and the shared expert's tensor for one suffix, as `_shared_last` checks them. +const Pair = struct { mine: Tensor, one: Tensor }; + +fn pair(t: *const Table, stack_key: []const u8, shared: []const u8, suffix: []const u8) Error!Pair { + var b1: [256]u8 = undefined; + var b2: [256]u8 = undefined; + var mine = try t.get(projection.join(&b1, &.{ stack_key, suffix })); + var one = try t.get(projection.join(&b2, &.{ shared, suffix })); + if (mine.dtype == .u32) mine.dtype = .i32; + if (one.dtype == .u32) one.dtype = .i32; + if (one.rank == mine.rank and one.shape[0] == 1) { + one.rank -= 1; + one.shape = .{ one.shape[1], one.shape[2], one.shape[3], one.shape[4], 1 }; + } + if (mine.rank != one.rank + 1 or !std.mem.eql(usize, mine.shape[1..mine.rank], one.shape[0..one.rank])) return refuse(stack_key, "does not stack with the shared expert"); + return .{ .mine = mine, .one = one }; +} + +/// `fused` words, scales and biases of `srcs` stacked per expert, each expert's slices side by side along N. +fn stack(a: std.mem.Allocator, srcs: []const Pair, dtype: DType) Error!Tensor { + const count = srcs[0].mine.shape[0] + 1; + const rest = srcs[0].mine.shape[2]; + var rows: usize = 0; + for (srcs) |s| rows += s.mine.shape[1]; + const size = dtype.size(); + const out = try a.alloc(u8, count * rows * rest * size); + var at: usize = 0; + for (0..count) |e| for (srcs) |s| { + const n = s.mine.shape[1] * rest; + const src = if (e + 1 < count) s.mine.bytes[e * n * s.mine.dtype.size() ..][0 .. n * s.mine.dtype.size()] else s.one.bytes; + if (s.mine.dtype == dtype) { + @memcpy(out[at..][0..src.len], src); + } else for (0..n) |i| { + std.mem.writeInt(u32, out[at + 4 * i ..][0..4], @bitCast(convert.load(s.mine.dtype, src, i)), .little); + } + at += n * size; + }; + return .{ .dtype = dtype, .rank = 3, .shape = .{ count, rows, rest, 1, 1 }, .bytes = out }; +} + +/// The dtype the group tables of `srcs` share, or fp32 when they differ or the kernels do not read them as stored. +fn tableDtype(srcs: []const Pair, other: []const Pair) DType { + const first = srcs[0].mine.dtype; + for ([_][]const Pair{ srcs, other }) |list| for (list) |s| { + if (s.mine.dtype != first or s.one.dtype != first) return .f32; + }; + return if (convert.tableDtype(first)) first else .f32; +} + +/// One projection's tensors, checked as `_affine_side` does against (bits, group). +const Part = struct { words: Pair, scales: Pair, biases: Pair }; + +fn part(t: *const Table, stack_key: []const u8, shared: []const u8, w: config.Width) Error!Part { + const p: Part = .{ + .words = try pair(t, stack_key, shared, ".weight"), + .scales = try pair(t, stack_key, shared, ".scales"), + .biases = try pair(t, stack_key, shared, ".biases"), + }; + const words, const scale, const bias = .{ p.words.mine, p.scales.mine, p.biases.mine }; + if (words.dtype != .i32 or scale.rank != 3 or !std.mem.eql(usize, scale.shape[0..3], bias.shape[0..3])) return refuse(stack_key, "not an MLX affine expert stack"); + const k = scale.shape[2] * w.group; + if (words.shape[2] != k * w.bits / 32 or !std.mem.eql(usize, words.shape[0..2], scale.shape[0..2])) return refuse(stack_key, "packed stack does not fit K, bits and group"); + return p; +} + +fn side(a: std.mem.Allocator, parts: []const Part, w: config.Width) Error!host.Projection { + var words: [2]Pair = undefined; + var scales: [2]Pair = undefined; + var biases: [2]Pair = undefined; + for (parts, 0..) |p, i| { + words[i] = p.words; + scales[i] = p.scales; + biases[i] = p.biases; + } + const n = parts.len; + const dtype = tableDtype(scales[0..n], biases[0..n]); + return .{ .mlx = .{ + .words = try stack(a, words[0..n], .i32), + .scales = try stack(a, scales[0..n], dtype), + .biases = try stack(a, biases[0..n], dtype), + .bits = w.bits, + .group = w.group, + } }; +} + +/// `_experts`: a layer's E + 1 affine experts, the shared one last, gate and up fused per expert. +pub fn experts(a: std.mem.Allocator, t: *const Table, prefix: []const u8) Error!host.Experts { + var b: [4][256]u8 = undefined; + const mine = projection.join(&b[0], &.{ prefix, "switch_mlp." }); + const shared = projection.join(&b[1], &.{ prefix, "shared_expert." }); + if (!t.has(projection.join(&b[2], &.{ mine, "up_proj.weight" }))) { + if (t.has(projection.join(&b[2], &.{ mine, "up_proj.qweight" }))) return error.UnsupportedQuantization; + _ = try t.get(projection.join(&b[2], &.{ mine, "up_proj.weight" })); + } + const gated = t.has(projection.join(&b[2], &.{ mine, "gate_proj.weight" })); + var names: [3][2][256]u8 = undefined; + const keys = [3][]const u8{ "up_proj", "gate_proj", "down_proj" }; + var routed_keys: [3][]const u8 = undefined; + var shared_keys: [3][]const u8 = undefined; + for (keys, 0..) |k, i| { + routed_keys[i] = projection.join(&names[i][0], &.{ mine, k }); + shared_keys[i] = projection.join(&names[i][1], &.{ shared, k }); + } + const up_w = try t.width(routed_keys[0]); + const down_w = try t.width(routed_keys[2]); + if (gated and !std.meta.eql(try t.width(routed_keys[1]), up_w)) return refuse(mine, "gate and up differ in width"); + const up = try part(t, routed_keys[0], shared_keys[0], up_w); + const down = try part(t, routed_keys[2], shared_keys[2], down_w); + var fused_parts: [2]Part = undefined; + var n: usize = 0; + if (gated) { + fused_parts[0] = try part(t, routed_keys[1], shared_keys[1], up_w); + n = 1; + if (!std.mem.eql(usize, fused_parts[0].words.mine.shape[0..3], up.words.mine.shape[0..3])) return refuse(mine, "gate and up differ in shape"); + } + fused_parts[n] = up; + n += 1; + const fused = try side(a, fused_parts[0..n], up_w); + const d = try side(a, &.{down}, down_w); + return .{ + .fused = fused, + .gated = gated, + .down = d, + .width = up.words.mine.shape[1], + .dims = down.words.mine.shape[1], + .count = up.words.mine.shape[0] + 1, + }; +} + +/// `_routed`: router rows [E + 1, D] in bf16 (the shared expert's gate row last), widened once, and the experts. +pub fn routed(a: std.mem.Allocator, t: *const Table, prefix: []const u8, spec: config.Spec) Error!host.Routed { + var b: [2][256]u8 = undefined; + const gate = try routerRows(a, t, projection.join(&b[0], &.{ prefix, "gate" })); + const shared_gate = try routerRows(a, t, projection.join(&b[1], &.{ prefix, "shared_expert_gate" })); + const rows = gate.rows + shared_gate.rows; + if (gate.cols != shared_gate.cols or rows != spec.experts + 1 or gate.cols != spec.hidden) return refuse(prefix, "router rows do not fit E + 1 by hidden"); + const router = try a.alloc(u8, rows * gate.cols * 2); + const rows32 = try a.alloc(u8, rows * gate.cols * 4); + var at: usize = 0; + for ([_][]f32{ gate.data, shared_gate.data }) |part_rows| for (part_rows) |v| { + const half = convert.bf16(v); + std.mem.writeInt(u16, router[2 * at ..][0..2], half, .little); + std.mem.writeInt(u32, rows32[4 * at ..][0..4], @as(u32, half) << 16, .little); + at += 1; + }; + const ex = try experts(a, t, prefix); + if (ex.count != rows) return refuse(prefix, "router and experts disagree on E + 1"); + return .{ + .router = .{ .dtype = .bf16, .rank = 2, .shape = .{ rows, gate.cols, 1, 1, 1 }, .bytes = router }, + .rows32 = .{ .dtype = .f32, .rank = 2, .shape = .{ rows, gate.cols, 1, 1, 1 }, .bytes = rows32 }, + .experts = ex, + .top_k = spec.top_k, + }; +} diff --git a/zig/src/families/qwen3_5/weights/host.zig b/zig/src/families/qwen3_5/weights/host.zig new file mode 100644 index 00000000000..b0dc214f166 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/host.zig @@ -0,0 +1,102 @@ +//! What the loader hands the GPU, still on the host: the Python TextModel's layers with the bytes its kernels read. + +const std = @import("std"); +const quant = @import("core").quant; +const table = @import("table.zig"); + +pub const Tensor = table.Tensor; + +/// A projection as its format read it from the checkpoint. +pub const Projection = quant.Host; + +/// A layer's E + 1 experts, shared last: `fused` is gate then up along N per expert, or up alone when not `gated`. +pub const Experts = struct { + fused: Projection, + gated: bool, + down: Projection, + /// The expert MLP's inner width (rows of the gate, and of the up). + width: usize, + /// The model width (rows of the down). + dims: usize, + /// E + 1. + count: usize, +}; + +/// The router rows [E + 1, D] with the shared gate last, in bf16 and widened to `rows32`; `remap` is a rank's own ids. +pub const Routed = struct { router: Tensor, rows32: Tensor, experts: Experts, top_k: usize, remap: ?Tensor = null }; + +pub const DenseMlp = struct { gate: Projection, up: Projection, down: Projection }; + +pub const Mlp = union(enum) { dense: DenseMlp, routed: Routed }; + +/// A gated delta-net layer. Norms, conv [channels, kernel], a_log, dt_bias and gnorm are fp32. +pub const Linear = struct { + input_norm: Tensor, + post_norm: Tensor, + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + conv: Tensor, + a_log: Tensor, + dt_bias: Tensor, + gnorm: Tensor, + out: Projection, + mlp: Mlp, +}; + +pub const Full = struct { + input_norm: Tensor, + post_norm: Tensor, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + q_norm: Tensor, + k_norm: Tensor, + mlp: Mlp, +}; + +pub const Body = union(enum) { linear: Linear, full: Full }; + +/// One layer's tensors; `arena` holds what was converted or stacked, the rest points into the mapped files. +pub const Layer = struct { + arena: std.heap.ArenaAllocator, + body: Body, + + pub fn deinit(l: *Layer) void { + l.arena.deinit(); + l.* = undefined; + } +}; + +/// The MTP head: the Flash Next shape, or the Qwen3 one (`gated`) with input and post norms and an MLP. +pub const Mtp = struct { + arena: std.heap.ArenaAllocator, + /// The side files' table when the head came from them: the head's tensors point into its maps. + owned: ?table.Table = null, + io: std.Io, + fc_e_norm: Tensor, + fc_h_norm: Tensor, + fc_e: Projection, + fc_h: Projection, + q_norm: Tensor, + k_norm: Tensor, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + final_norm: Tensor, + /// `null` ties with the main model's output head. + head: ?Projection, + input_norm: ?Tensor, + post_norm: ?Tensor, + mlp: ?Mlp, + gated: bool, + + pub fn deinit(m: *Mtp) void { + if (m.owned) |*t| t.close(m.io); + m.arena.deinit(); + m.* = undefined; + } +}; diff --git a/zig/src/families/qwen3_5/weights/projection.zig b/zig/src/families/qwen3_5/weights/projection.zig new file mode 100644 index 00000000000..c908dda33fb --- /dev/null +++ b/zig/src/families/qwen3_5/weights/projection.zig @@ -0,0 +1,47 @@ +//! The Python loader's `_packed`, `_float`, `_conv` and `_halves`: a tensor or a projection's, read and checked. + +const std = @import("std"); +const quant = @import("core").quant; +const table = @import("table.zig"); +const host = @import("host.zig"); + +const convert = quant.convert; +const Tensor = table.Tensor; +const Table = table.Table; +pub const Error = table.Error || convert.Error || error{UnexpectedTensor}; + +pub const join = quant.join; + +fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { + std.log.err("{s}: {s}", .{ key, what }); + return error.UnexpectedTensor; +} + +/// `_float`: the tensor widened to fp32. +pub fn float(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!Tensor { + const src = try t.get(key); + if (!convert.isFloat(src.dtype)) return refuse(key, "not a floating tensor"); + return convert.float32(a, src); +} + +/// `_conv`: a depthwise conv weight as fp32 (channels, kernel); a trailing 1 is squeezed. +pub fn conv(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!Tensor { + var w = try float(a, t, key); + if (w.rank == 3 and w.shape[2] == 1) { + w.rank = 2; + } else if (w.rank == 3 and w.shape[1] == 1) { + return refuse(key, "still in the unsanitized (channels, 1, kernel) layout"); + } + if (w.rank != 2) return refuse(key, "conv weight must be (channels, kernel)"); + return w; +} + +/// `_packed`: a projection in whichever format its tensors are in. +pub fn projection(a: std.mem.Allocator, t: *const Table, key: []const u8) !host.Projection { + return quant.read(a, t, key); +} + +/// `_halves`: a fused [embedding | hidden] projection split in two along K, words and group tables alike. +pub fn halves(a: std.mem.Allocator, fused: host.Projection) ![2]host.Projection { + return quant.halves(a, fused); +} diff --git a/zig/src/families/qwen3_5/weights/real_test.zig b/zig/src/families/qwen3_5/weights/real_test.zig new file mode 100644 index 00000000000..c86fe1bc0b8 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/real_test.zig @@ -0,0 +1,56 @@ +//! The index check on a real checkpoint: TF_QWEN_DIR names a model directory; every tensor the loader reads resolves. + +const std = @import("std"); +const checkpoint = @import("checkpoint.zig"); +const host = @import("host.zig"); + +/// What a full pass over a checkpoint found. +pub const Summary = struct { layers: usize = 0, full: usize = 0, moe: usize = 0, mtp: bool = false, tied: bool = false, bytes: usize = 0 }; + +fn mlpBytes(m: host.Mlp) usize { + return switch (m) { + .dense => |d| d.gate.bytes() + d.up.bytes() + d.down.bytes(), + .routed => |r| r.router.bytes.len + r.rows32.bytes.len + r.experts.fused.bytes() + r.experts.down.bytes(), + }; +} + +/// Reads and checks every layer, the embedding, the head and the MTP layer of the checkpoint in `dir`. +pub fn run(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Summary { + var ck = try checkpoint.Checkpoint.open(gpa, io, dir); + defer ck.close(); + var sum: Summary = .{ .tied = ck.config.tied }; + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + sum.bytes += embed.bytes(); + _ = try ck.finalNorm(scratch.allocator()); + if (try ck.head(scratch.allocator())) |h| sum.bytes += h.bytes(); + for (0..ck.spec().n_layers) |i| { + var layer = try ck.layer(i); + defer layer.deinit(); + sum.layers += 1; + const mlp = switch (layer.body) { + .full => |f| blk: { + sum.full += 1; + break :blk f.mlp; + }, + .linear => |l| l.mlp, + }; + if (mlp == .routed) sum.moe += 1; + sum.bytes += mlpBytes(mlp); + } + if (try ck.mtp()) |m| { + var head = m; + defer head.deinit(); + sum.mtp = true; + if (head.mlp) |x| sum.bytes += mlpBytes(x); + } + return sum; +} + +test "the real checkpoint (TF_QWEN_DIR) resolves every tensor with consistent shapes" { + const dir = std.testing.environ.getPosix("TF_QWEN_DIR") orelse return error.SkipZigTest; + const sum = try run(std.testing.allocator, std.testing.io, dir); + std.debug.print("qwen35 index: {d} layers ({d} full attention, {d} MoE), tied head {}, MTP {}, {d} MiB of projections and MLPs\n", .{ sum.layers, sum.full, sum.moe, sum.tied, sum.mtp, sum.bytes >> 20 }); + try std.testing.expect(sum.layers > 0); +} diff --git a/zig/src/families/qwen3_5/weights/shard.zig b/zig/src/families/qwen3_5/weights/shard.zig new file mode 100644 index 00000000000..e09e502bc97 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/shard.zig @@ -0,0 +1,81 @@ +//! One safetensors file mapped read-only; tensors above core's max rank and unnamed dtypes stay out of its index. + +const std = @import("std"); +const Io = std.Io; +const st = @import("core").safetensors; + +pub const Tensor = st.Tensor; + +pub const Shard = struct { + file: Io.File, + map: Io.File.MemoryMap, + data: usize, + names: st.Header, + arena: std.heap.ArenaAllocator, + + pub fn open(gpa: std.mem.Allocator, io: Io, path: []const u8) !Shard { + var file = try Io.Dir.cwd().openFile(io, path, .{}); + errdefer file.close(io); + const len: usize = @intCast(try file.length(io)); + if (len < 8) return error.BadSafetensors; + var map = try Io.File.MemoryMap.create(io, file, .{ .len = len, .protection = .{ .read = true, .write = false }, .populate = false }); + errdefer map.destroy(io); + const header_len: usize = @intCast(std.mem.readInt(u64, map.memory[0..8], .little)); + if (header_len > len - 8) return error.BadSafetensors; + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const names = try parse(arena.allocator(), map.memory[8..][0..header_len], len - 8 - header_len); + return .{ .file = file, .map = map, .data = 8 + header_len, .names = names, .arena = arena }; + } + + pub fn close(s: *Shard, io: Io) void { + s.map.destroy(io); + s.file.close(io); + s.arena.deinit(); + s.* = undefined; + } + + pub fn get(s: *const Shard, name: []const u8) ?Tensor { + const e = s.names.get(name) orelse return null; + return .{ .dtype = e.dtype, .rank = e.rank, .shape = e.shape, .bytes = s.map.memory[s.data + e.begin .. s.data + e.end] }; + } +}; + +/// core's `parseHeader` without its refusals of rank and dtype; sizes and ranges are still checked. +fn parse(arena: std.mem.Allocator, json: []const u8, data_len: usize) !st.Header { + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}); + var out: st.Header = .empty; + var it = parsed.object.iterator(); + while (it.next()) |kv| { + if (std.mem.eql(u8, kv.key_ptr.*, "__metadata__")) continue; + const o = kv.value_ptr.object; + const dtype = st.DType.parse(o.get("dtype").?.string) orelse continue; + const shape = o.get("shape").?.array.items; + if (shape.len > st.max_rank) continue; + var e: st.Entry = .{ .dtype = dtype, .rank = @intCast(shape.len), .shape = @splat(1), .begin = 0, .end = 0 }; + var n: usize = dtype.size(); + for (shape, 0..) |d, i| { + e.shape[i] = @intCast(d.integer); + n *= e.shape[i]; + } + const offs = o.get("data_offsets").?.array.items; + e.begin = @intCast(offs[0].integer); + e.end = @intCast(offs[1].integer); + if (e.end < e.begin or e.end - e.begin != n or e.end > data_len) return error.BadSafetensors; + try out.put(arena, kv.key_ptr.*, e); + } + return out; +} + +test "a tensor above the max rank and an unknown dtype are left out" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const json = + \\{"a": {"dtype": "U32", "shape": [2], "data_offsets": [0, 8]}, + \\ "patch": {"dtype": "BF16", "shape": [1, 1, 1, 1, 1, 1], "data_offsets": [8, 10]}, + \\ "q9": {"dtype": "Q9_UNKNOWN", "shape": [2], "data_offsets": [10, 12]}} + ; + const h = try parse(arena.allocator(), json, 12); + try std.testing.expectEqual(@as(usize, 1), h.count()); + try std.testing.expect(h.contains("a")); +} diff --git a/zig/src/families/qwen3_5/weights/slicing.zig b/zig/src/families/qwen3_5/weights/slicing.zig new file mode 100644 index 00000000000..9c458f67abd --- /dev/null +++ b/zig/src/families/qwen3_5/weights/slicing.zig @@ -0,0 +1,124 @@ +const std = @import("std"); +const config = @import("config.zig"); +const host = @import("host.zig"); + +const quant = @import("core").quant; +const Allocator = std.mem.Allocator; +const takeRows = quant.slice.takeRows; +const even = quant.slice.even; + +pub const Error = error{ UnevenSplit, KvHeads } || Allocator.Error; + +pub const Rank = quant.Rank; +const Span = quant.Span; + +/// The spec as a rank sees it: its heads and value heads (the vocabulary stays whole; the head's rows are split). +pub fn localSpec(s: config.Spec, r: Rank) Error!config.Spec { + var out = s; + out.heads = try even(s.heads, r.world, "heads"); + out.key_heads = try even(s.key_heads, r.world, "key_heads"); + out.value_heads = try even(s.value_heads, r.world, "value_heads"); + _ = try even(s.vocab, r.world, "vocab"); + out.kv_heads = @max(1, s.kv_heads / r.world); + return out; +} + +/// `_rows`: output rows `spans` of a projection, the share of a column-split one. +fn sliceRows(a: Allocator, p: host.Projection, spans: []const Span) Error!host.Projection { + return quant.sliceRows(a, p, spans); +} + +/// `_cols`: one rank's whole input groups of a row-split projection, whose fp32 outputs the ranks sum. +fn cols(a: Allocator, p: host.Projection, r: Rank, what: []const u8) Error!host.Projection { + return quant.sliceCols(a, p, r, what); +} + +/// This rank's rows of each segment of a concatenated output (q | k | v), each segment split evenly. +fn segments(widths: []const usize, r: Rank, out: []Span, what: []const u8) Error![]const Span { + var base: usize = 0; + for (widths, out[0..widths.len]) |w, *span| { + const part = try even(w, r.world, what); + span.* = .{ .from = base + r.rank * part, .to = base + (r.rank + 1) * part }; + base += w; + } + return out[0..widths.len]; +} + +/// This rank's k or v rows; with fewer KV heads than ranks each head is kept by its query ranks. +fn kvSpan(width: usize, kv_heads: usize, r: Rank, out: []Span) Error![]const Span { + if (kv_heads >= r.world) return segments(&.{width}, r, out, "kv rows"); + if (r.world % kv_heads != 0) return error.KvHeads; + const head = r.rank / (r.world / kv_heads); + const part = width / kv_heads; + out[0] = .{ .from = head * part, .to = (head + 1) * part }; + return out[0..1]; +} + +/// One layer's tensors for rank `r`, cut in place (`l.arena` holds the copies). `s` is the whole model's spec. +pub fn layer(l: *host.Layer, s: config.Spec, r: Rank) Error!void { + const a = l.arena.allocator(); + var buf: [3]Span = undefined; + switch (l.body) { + .full => |*f| { + f.q = try sliceRows(a, f.q, try segments(&.{s.heads * s.head_dim * 2}, r, &buf, "q_proj")); + const kv = s.kv_heads * s.head_dim; + f.k = try sliceRows(a, f.k, try kvSpan(kv, s.kv_heads, r, &buf)); + f.v = try sliceRows(a, f.v, try kvSpan(kv, s.kv_heads, r, &buf)); + f.o = try cols(a, f.o, r, "o_proj groups"); + try mlp(a, &f.mlp, r); + }, + .linear => |*x| { + const qkv = try segments(&.{ s.keyWidth(), s.keyWidth(), s.valueWidth() }, r, &buf, "in_proj_qkv"); + x.qkv = try sliceRows(a, x.qkv, qkv); + x.conv = try takeRows(a, x.conv, qkv); + x.z = try sliceRows(a, x.z, try segments(&.{s.valueWidth()}, r, &buf, "in_proj_z")); + const heads = try segments(&.{s.value_heads}, r, &buf, "value heads"); + x.a = try sliceRows(a, x.a, heads); + x.b = try sliceRows(a, x.b, heads); + x.a_log = try takeRows(a, x.a_log, heads); + x.dt_bias = try takeRows(a, x.dt_bias, heads); + x.out = try cols(a, x.out, r, "out_proj groups"); + try mlp(a, &x.mlp, r); + }, + } +} + +fn mlp(a: Allocator, m: *host.Mlp, r: Rank) Error!void { + switch (m.*) { + .dense => |*d| { + var buf: [1]Span = undefined; + const spans = try segments(&.{d.gate.rows()}, r, &buf, "mlp"); + d.gate = try sliceRows(a, d.gate, spans); + d.up = try sliceRows(a, d.up, spans); + d.down = try cols(a, d.down, r, "mlp.down_proj groups"); + }, + .routed => |*x| try routed(a, x, r), + } +} + +/// A rank's contiguous routed experts, the shared one on rank 0, and the remap to its own ids (-1: another rank's). +fn routed(a: Allocator, x: *host.Routed, r: Rank) Error!void { + const total = x.experts.count - 1; + const part = try even(total, r.world, "experts"); + x.experts.fused = try quant.sliceStack(a, x.experts.fused, r, part); + x.experts.down = try quant.sliceStack(a, x.experts.down, r, part); + x.experts.count = part + @intFromBool(r.rank == 0); + const remap = try a.alloc(i32, total + 1); + @memset(remap, -1); + for (0..part) |i| remap[r.rank * part + i] = @intCast(i); + if (r.rank == 0) remap[total] = @intCast(part); + x.remap = .{ .dtype = .i32, .rank = 1, .shape = .{ total + 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(remap) }; +} + +/// The output head's rows for rank `r`: its share of the vocabulary. +pub fn vocabRows(a: Allocator, p: host.Projection, vocab: usize, r: Rank) Error!host.Projection { + var buf: [1]Span = undefined; + return sliceRows(a, p, try segments(&.{vocab}, r, &buf, "vocab")); +} + +test "a kv head is kept by its query ranks" { + var buf: [1]Span = undefined; + const spans = try kvSpan(256, 2, .{ .rank = 3, .world = 4 }, &buf); + try std.testing.expectEqual(Span{ .from = 128, .to = 256 }, spans[0]); + try std.testing.expectError(error.KvHeads, kvSpan(256, 3, .{ .rank = 0, .world = 4 }, &buf)); +} diff --git a/zig/src/families/qwen3_5/weights/table.zig b/zig/src/families/qwen3_5/weights/table.zig new file mode 100644 index 00000000000..0bb3936a081 --- /dev/null +++ b/zig/src/families/qwen3_5/weights/table.zig @@ -0,0 +1,136 @@ +//! One tensor table over a checkpoint's safetensors files, with the Python loader's `_Shards` key stripping and widths. + +const std = @import("std"); +const Io = std.Io; +const st = @import("core").safetensors; +const formats = @import("core").quant; +const config = @import("config.zig"); + +const Shard = @import("shard.zig").Shard; +pub const Tensor = st.Tensor; +pub const DType = st.DType; +pub const Error = error{ MissingTensor, NoSafetensors } || config.Error || std.mem.Allocator.Error; + +const Where = struct { file: usize, stored: []const u8 }; + +pub const Table = struct { + gpa: std.mem.Allocator, + files: []Shard, + where: std.StringHashMapUnmanaged(Where) = .empty, + /// A key prefix the table drops (`language_model.`), as `_Shards(strip=)`. + strip: []const u8, + quant: formats.Config, + + /// Maps `paths` (later files win a repeated name, as the Python dict does). + pub fn open(gpa: std.mem.Allocator, io: Io, paths: []const []const u8, strip: []const u8, quant: formats.Config) !Table { + const files = try gpa.alloc(Shard, paths.len); + var opened: usize = 0; + errdefer { + for (files[0..opened]) |*f| f.close(io); + gpa.free(files); + } + for (paths) |p| { + files[opened] = try Shard.open(gpa, io, p); + opened += 1; + } + var t: Table = .{ .gpa = gpa, .files = files, .strip = strip, .quant = quant }; + errdefer t.where.deinit(gpa); + for (files, 0..) |*f, i| for (f.names.keys()) |key| { + const short = if (strip.len > 0 and std.mem.startsWith(u8, key, strip)) key[strip.len..] else key; + try t.where.put(gpa, short, .{ .file = i, .stored = key }); + }; + return t; + } + + pub fn close(t: *Table, io: Io) void { + for (t.files) |*f| f.close(io); + t.gpa.free(t.files); + t.where.deinit(t.gpa); + t.* = undefined; + } + + pub fn has(t: *const Table, key: []const u8) bool { + return t.where.contains(key); + } + + /// The tensor under `key`; a missing one is `error.MissingTensor`, logged by name. + pub fn get(t: *const Table, key: []const u8) Error!Tensor { + const w = t.where.get(key) orelse { + std.log.err("checkpoint has no tensor {s}", .{key}); + return error.MissingTensor; + }; + return t.files[w.file].get(w.stored).?; + } + + /// Every key of the table (stripped names). + pub fn keys(t: *const Table) []const []const u8 { + return t.where.keys(); + } + + /// The tensor's own width when the config names it (`key`, then the stripped prefix back on), else the global one. + pub fn width(t: *const Table, key: []const u8) config.Error!formats.mlx.Width { + const q = switch (t.quant) { + .mlx => |m| m, + .dense => return error.UnsupportedQuantization, + }; + if (q.overrides.get(key)) |w| return w orelse error.UnsupportedQuantization; + if (t.strip.len > 0) { + var buf: [512]u8 = undefined; + const full = std.fmt.bufPrint(&buf, "{s}{s}", .{ t.strip, key }) catch return q.global; + if (q.overrides.get(full)) |w| return w orelse error.UnsupportedQuantization; + } + return q.global; + } +}; + +/// The checkpoint's safetensors paths, sorted: the model's own files, and the `mtp*.safetensors` side files. +pub const Files = struct { + arena: std.heap.ArenaAllocator, + model: []const []const u8, + side: []const []const u8, + + pub fn deinit(f: *Files) void { + f.arena.deinit(); + f.* = undefined; + } + + /// `root.glob("*.safetensors")`: a file whose name holds "mtp" is not the model's; `mtp*` ones are the side files. + pub fn list(gpa: std.mem.Allocator, io: Io, dir: []const u8) !Files { + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + var model: std.ArrayList([]const u8) = .empty; + var side: std.ArrayList([]const u8) = .empty; + var d = try Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); + defer d.close(io); + var it = d.iterate(); + while (try it.next(io)) |e| { + if (e.kind != .file and e.kind != .sym_link) continue; + if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; + const path = try std.fs.path.join(a, &.{ dir, e.name }); + if (std.mem.startsWith(u8, e.name, "mtp")) try side.append(a, path); + if (!containsLower(e.name, "mtp")) try model.append(a, path); + } + const less = struct { + fn f(_: void, x: []const u8, y: []const u8) bool { + return std.mem.order(u8, x, y) == .lt; + } + }.f; + std.mem.sort([]const u8, model.items, {}, less); + std.mem.sort([]const u8, side.items, {}, less); + return .{ .arena = arena, .model = model.items, .side = side.items }; + } +}; + +fn containsLower(name: []const u8, needle: []const u8) bool { + var i: usize = 0; + while (i + needle.len <= name.len) : (i += 1) { + if (std.ascii.eqlIgnoreCase(name[i..][0..needle.len], needle)) return true; + } + return false; +} + +test "mtp in a file name keeps it out of the model's files" { + try std.testing.expect(containsLower("Model-MTP-4bit.safetensors", "mtp")); + try std.testing.expect(!containsLower("model-00001-of-00004.safetensors", "mtp")); +} From eb9bd0f6e7a0791ca10b5a93266b10c328b58732 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:07:30 +0200 Subject: [PATCH 08/52] fix(qwen3_5): un-center an MTP head shipped zero-centered mlx-serve's conversions (Qwen3.8-27B-MLX-Serve-4/6/8bit) bake the trunk's `1 + w` into its norms but ship the MTP head's norms zero-centered. Read as gains, the head drafted nothing: 0 of 127 drafts accepted on the 27B. Norms averaging under 0.5 now get the 1 added; the baked heads (9B, 35B, 27B-3bit-mtp) average 1.2 and above and are kept. --- .../families/qwen3_5/weights/checkpoint.zig | 21 +++++- .../qwen3_5/weights/checkpoint_test.zig | 65 ++++++++++++++----- 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/zig/src/families/qwen3_5/weights/checkpoint.zig b/zig/src/families/qwen3_5/weights/checkpoint.zig index bc20b6c640a..62300bb1c2f 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint.zig @@ -188,7 +188,7 @@ fn readMtp(a: std.mem.Allocator, t: *const Table, s: config.Spec) !host.Mtp { const mlp = layer ++ "mlp."; const halves = try projection.halves(a, try projection.projection(a, t, "mtp.fc")); const routed = t.has(mlp ++ "switch_mlp.up_proj.weight") or t.has(mlp ++ "switch_mlp.up_proj.qweight"); - return .{ + var m: host.Mtp = .{ .arena = undefined, .io = undefined, .fc_e_norm = try projection.float(a, t, "mtp.pre_fc_norm_embedding.weight"), @@ -212,4 +212,23 @@ fn readMtp(a: std.mem.Allocator, t: *const Table, s: config.Spec) !host.Mtp { } }, .gated = true, }; + try uncenter(a, &m); + return m; +} + +/// Norms averaging under 0.5 are zero-centered (mlx-serve bakes only the trunk's `1 + w`): add the 1. +fn uncenter(a: std.mem.Allocator, m: *host.Mtp) !void { + const norms = [_]*Tensor{ &m.fc_e_norm, &m.fc_h_norm, &m.q_norm, &m.k_norm, &m.final_norm, &m.input_norm.?, &m.post_norm.? }; + var sum: f64 = 0; + var n: usize = 0; + for (norms) |t| for (std.mem.bytesAsSlice(f32, t.bytes)) |w| { + sum += w; + n += 1; + }; + if (sum >= 0.5 * @as(f64, @floatFromInt(n))) return; + for (norms) |t| { + const out = try a.alloc(f32, t.numel()); + for (out, std.mem.bytesAsSlice(f32, t.bytes)) |*o, w| o.* = w + 1; + t.bytes = std.mem.sliceAsBytes(out); + } } diff --git a/zig/src/families/qwen3_5/weights/checkpoint_test.zig b/zig/src/families/qwen3_5/weights/checkpoint_test.zig index 8a5b3f7397d..a89b1478272 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint_test.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint_test.zig @@ -15,6 +15,8 @@ const Entry = struct { name: []const u8, dtype: []const u8, shape: []const usize const Image = struct { arena: std.heap.ArenaAllocator, entries: std.ArrayList(Entry) = .empty, + /// When set, every bf16 tensor named for a norm holds this value's bits instead of the pattern. + norm: ?u16 = null, fn init() Image { return .{ .arena = .init(gpa) }; @@ -42,6 +44,9 @@ const Image = struct { if (size == 2) for (bytes[1..], 0..) |*b, i| { if (i % 2 == 0) b.* &= 0x3F; }; + if (m.norm) |v| if (size == 2 and std.mem.indexOf(u8, name, "norm") != null) { + for (std.mem.bytesAsSlice(u16, bytes)) |*w| w.* = std.mem.nativeToLittle(u16, v); + }; try m.entries.append(a, .{ .name = try a.dupe(u8, name), .dtype = dtype, .shape = try a.dupe(usize, shape), .bytes = bytes }); } @@ -122,15 +127,10 @@ fn trunk(m: *Image) !void { try m.put(L ++ "norm.weight", "BF16", &.{64}); } -test "a dense model: layers, embedding, tied head and the MTP side file" { - var img = Image.init(); - defer img.deinit(); - var side = Image.init(); - defer side.deinit(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try trunk(&img); - try norms(&img, L ++ "layers.0."); +/// The dense test model: a linear layer, a full one, the vision tower to skip and the MTP head in a side file. +fn denseFiles(img: *Image, side: *Image, dir: std.Io.Dir) !void { + try trunk(img); + try norms(img, L ++ "layers.0."); const lin = L ++ "layers.0.linear_attn."; try img.affine(lin ++ "in_proj_qkv", 96, 64, 4, 32); try img.affine(lin ++ "in_proj_z", 32, 64, 4, 32); @@ -146,23 +146,33 @@ test "a dense model: layers, embedding, tied head and the MTP side file" { try img.affine(L ++ l ++ "mlp.up_proj", 32, 64, 4, 32); try img.affine(L ++ l ++ "mlp.down_proj", 64, 32, 4, 32); } - try norms(&img, L ++ "layers.1."); - try attention(&img, L ++ "layers.1."); + try norms(img, L ++ "layers.1."); + try attention(img, L ++ "layers.1."); try img.put("vision_tower.patch_embed.weight", "BF16", &.{4}); try side.put("mtp.pre_fc_norm_embedding.weight", "BF16", &.{64}); try side.put("mtp.pre_fc_norm_hidden.weight", "BF16", &.{64}); try side.put("mtp.norm.weight", "BF16", &.{64}); try side.affine("mtp.fc", 64, 128, 4, 32); - try norms(&side, "mtp.layers.0."); - try attention(&side, "mtp.layers.0."); + try norms(side, "mtp.layers.0."); + try attention(side, "mtp.layers.0."); try side.affine("mtp.layers.0.mlp.gate_proj", 32, 64, 4, 32); try side.affine("mtp.layers.0.mlp.up_proj", 32, 64, 4, 32); try side.affine("mtp.layers.0.mlp.down_proj", 64, 32, 4, 32); - try img.write(tmp.dir, "model.safetensors"); - try side.write(tmp.dir, "mtp.safetensors"); - try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = dense_config }); + try img.write(dir, "model.safetensors"); + try side.write(dir, "mtp.safetensors"); + try dir.writeFile(io, .{ .sub_path = "config.json", .data = dense_config }); +} + +test "a dense model: layers, embedding, tied head and the MTP side file" { + var img = Image.init(); + defer img.deinit(); + var side = Image.init(); + defer side.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try denseFiles(&img, &side, tmp.dir); const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); defer gpa.free(root); @@ -177,6 +187,7 @@ test "a dense model: layers, embedding, tied head and the MTP side file" { const final = try ck.finalNorm(scratch.allocator()); try std.testing.expectEqual(convert.load(.bf16, img.find(L ++ "norm.weight"), 5), convert.load(.f32, final.bytes, 5)); + const lin = L ++ "layers.0.linear_attn."; var l0 = try ck.layer(0); defer l0.deinit(); const x = l0.body.linear; @@ -281,3 +292,25 @@ test "MoE experts: gate and up fused per expert, the shared expert last, router std.mem.readInt(u16, r.router.bytes[2 * (128 + 5) ..][0..2], .little), ); } + +test "an MTP head shipped zero-centered gets back the 1 the trunk has baked in; a baked head keeps its gains" { + // bf16 0.25 (mlx-serve's zero-centered head) reads as 1.25; bf16 1.25 (baked) stays 1.25 + for ([_]u16{ 0x3E80, 0x3FA0 }) |bits| { + var img = Image.init(); + defer img.deinit(); + var side = Image.init(); + defer side.deinit(); + side.norm = bits; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try denseFiles(&img, &side, tmp.dir); + const root = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(root); + var ck = try checkpoint.Checkpoint.open(gpa, io, root); + defer ck.close(); + var head = (try ck.mtp()).?; + defer head.deinit(); + for ([_]host.Tensor{ head.fc_e_norm, head.fc_h_norm, head.q_norm, head.k_norm, head.final_norm, head.input_norm.?, head.post_norm.? }) |t| + try std.testing.expectEqual(@as(f64, 1.25), convert.load(.f32, t.bytes, 3)); + } +} From 4c231bfc7dbaffef3c5647363e32944fcb92ae00 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:27:35 +0200 Subject: [PATCH 09/52] feat(qwen3_5): the HIP config refuses what the kernels do not compute, and reads layers, mrope and end ids config_checks.zig takes qwen27/config.zig's rules to the HIP geometry: the activation (silu), the attention gate (the swish gate, att * sigmoid(gate), and no bias), the recurrent state type (fp32, under either key), the sizes the kernels index with 32-bit counts, each layer's kind from layer_types in any order, the mrope sections (three, filling half the rotary width, interleaved), max_position_embeddings, and the end ids of config.json and generation_config.json. The Qwen3.8-27B names <|im_end|> only in generation_config.json. 0 and 1 count as false and true, as the 0.8B 2-bit conversion writes them. Co-authored-by: ashhart <71890694+ashhart@users.noreply.github.com> --- zig/src/families/qwen3_5/config.zig | 51 ++-- zig/src/families/qwen3_5/config_checks.zig | 221 ++++++++++++++++++ .../qwen3_5/weights/checkpoint_test.zig | 4 +- zig/src/families/qwen3_5/weights/config.zig | 31 ++- 4 files changed, 283 insertions(+), 24 deletions(-) create mode 100644 zig/src/families/qwen3_5/config_checks.zig diff --git a/zig/src/families/qwen3_5/config.zig b/zig/src/families/qwen3_5/config.zig index aa697ef49c6..7b5cf9e817f 100644 --- a/zig/src/families/qwen3_5/config.zig +++ b/zig/src/families/qwen3_5/config.zig @@ -268,7 +268,9 @@ pub const Error = error{ InvalidMoe, InvalidRotary, InvalidLayerTypes, -} || std.mem.Allocator.Error || std.json.ParseError(std.json.Scanner); +} || checks.Error || std.mem.Allocator.Error || std.json.ParseError(std.json.Scanner); + +pub const checks = @import("config_checks.zig"); /// The Python `Spec`, plus the shared expert's width and the MTP layer count the config declares. pub const Spec = struct { @@ -295,10 +297,14 @@ pub const Spec = struct { moe_width: usize, shared_width: usize, mtp_layers: usize, + /// Each layer's kind, true for full attention (the others are gated delta-net). + full_layers: [checks.max_layers]bool = @splat(false), + mrope: checks.Mrope = .{}, + max_position: usize = 262144, /// Whether layer `index` is full attention (the others are gated delta-net). pub fn full(s: Spec, index: usize) bool { - return (index + 1) % s.full_every == 0; + return s.full_layers[index]; } pub fn keyWidth(s: Spec) usize { @@ -352,7 +358,7 @@ pub fn geometry(tower: std.json.ObjectMap, bits: u8, group_size: u16) Error!Spec if (!(product >= 0 and product <= @as(f64, @floatFromInt(per_head)))) return error.InvalidRotary; const rotary: usize = @intFromFloat(product); const base = try numberOf(rope.get("rope_theta") orelse if (truthy(tower.get("rope_theta"))) tower.get("rope_theta").? else .{ .integer = 10_000_000 }); - const spec: Spec = .{ + var spec: Spec = .{ .hidden = model_width, .intermediate = try optionalInt(tower, "intermediate_size", 0), .n_layers = try requiredInt(tower, "num_hidden_layers"), @@ -379,13 +385,11 @@ pub fn geometry(tower: std.json.ObjectMap, bits: u8, group_size: u16) Error!Spec }; if (rotary % 2 != 0 or rotary == 0 or rotary > per_head) return error.InvalidRotary; if (spec.full_every == 0 or attn_heads == 0) return error.InvalidConfig; - if (tower.get("layer_types")) |kinds| if (kinds != .null) { - if (kinds != .array) return error.InvalidLayerTypes; - for (kinds.array.items, 0..) |item, i| { - const want = if (spec.full(i)) "full_attention" else "linear_attention"; - if (item != .string or !eql(item.string, want)) return error.InvalidLayerTypes; - } - }; + try checks.computes(tower); + try checks.products(.{ .hidden = spec.hidden, .intermediate = spec.intermediate, .vocab = spec.vocab, .heads = spec.heads, .kv_heads = spec.kv_heads, .head_dim = spec.head_dim, .key_heads = spec.key_heads, .value_heads = spec.value_heads, .key_dim = spec.key_dim, .value_dim = spec.value_dim, .conv = spec.conv, .experts = spec.experts, .moe_width = spec.moe_width, .shared_width = spec.shared_width }); + try checks.layers(&spec.full_layers, tower, spec.n_layers, spec.full_every); + spec.mrope = try checks.mrope(rope, rotary); + spec.max_position = try checks.maxPosition(tower); return spec; } @@ -502,6 +506,23 @@ test "a top-level config, the partial rotary default and the MoE fields" { try std.testing.expectEqual(@as(usize, 4), s.full_every); } +test "the geometry refuses what the kernels do not compute and sizes past 32 bits" { + const a = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const cases = [_]struct { []const u8, []const u8, Error }{ + .{ "\"rms_norm_eps\"", "\"hidden_act\": \"gelu\", \"rms_norm_eps\"", error.UnsupportedActivation }, + .{ "\"rms_norm_eps\"", "\"output_gate_type\": \"sigmoid\", \"rms_norm_eps\"", error.UnsupportedAttentionGate }, + .{ "\"rms_norm_eps\"", "\"mamba_ssm_dtype\": \"bfloat16\", \"rms_norm_eps\"", error.UnsupportedStateType }, + .{ "\"vocab_size\": 248320", "\"vocab_size\": 1048576", error.InvalidConfig }, + }; + for (cases) |c| { + const text = try std.mem.replaceOwned(u8, a, sample_text, c[0], c[1]); + defer a.free(text); + try std.testing.expectError(c[2], geometry(try textTower(try declared(arena.allocator(), text)), 4, 64)); + } +} + test "the Python loader's refusals" { const a = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(a); @@ -509,10 +530,14 @@ test "the Python loader's refusals" { const wrong = try std.mem.replaceOwned(u8, a, sample_text, "\"qwen3_5\"", "\"llama\""); defer a.free(wrong); try std.testing.expectError(error.UnsupportedModel, declared(arena.allocator(), wrong)); - const types = try std.mem.replaceOwned(u8, a, sample_text, "\"full_attention\"],", "\"linear_attention\"],"); + // any mix of the two kinds is read as written; another kind is refused + const mixed = try std.mem.replaceOwned(u8, a, sample_text, "\"full_attention\"],", "\"linear_attention\"],"); + defer a.free(mixed); + const s = try geometry(try textTower(try declared(arena.allocator(), mixed)), 4, 64); + try std.testing.expect(s.full(3) and !s.full(7)); + const types = try std.mem.replaceOwned(u8, a, sample_text, "\"full_attention\"],", "\"sliding_attention\"],"); defer a.free(types); - const tower = try textTower(try declared(arena.allocator(), types)); - try std.testing.expectError(error.InvalidLayerTypes, geometry(tower, 4, 64)); + try std.testing.expectError(error.InvalidLayerTypes, geometry(try textTower(try declared(arena.allocator(), types)), 4, 64)); const moe = try std.mem.replaceOwned(u8, a, sample_text, "\"vocab_size\"", "\"num_experts\": 8, \"num_experts_per_tok\": 9, \"vocab_size\""); defer a.free(moe); try std.testing.expectError(error.InvalidMoe, geometry(try textTower(try declared(arena.allocator(), moe)), 4, 64)); diff --git a/zig/src/families/qwen3_5/config_checks.zig b/zig/src/families/qwen3_5/config_checks.zig new file mode 100644 index 00000000000..fa16b918811 --- /dev/null +++ b/zig/src/families/qwen3_5/config_checks.zig @@ -0,0 +1,221 @@ +//! What a Qwen3.5 config must declare for the HIP engine: activation, gate, state, layers, rope, end ids, sizes. + +const std = @import("std"); + +pub const Error = error{ UnsupportedActivation, UnsupportedAttentionGate, UnsupportedStateType, BadEos, TooManyEos, MissingEos, InvalidConfig, InvalidLayerTypes, InvalidRotary }; + +/// The most end ids a checkpoint may declare across config.json and generation_config.json. +pub const max_eos = 8; + +/// The most decoder layers a config may declare. +pub const max_layers = 128; + +/// Each layer's kind (true: full attention), from `layer_types` in any order, else every `interval`-th layer. +pub fn layers(out: *[max_layers]bool, tower: std.json.ObjectMap, count: usize, interval: usize) Error!void { + if (count == 0 or count > max_layers or interval == 0) return error.InvalidConfig; + out.* = @splat(false); + const list = tower.get("layer_types") orelse .null; + if (list == .null) { + for (out[0..count], 0..) |*full, i| full.* = (i + 1) % interval == 0; + return; + } + if (list != .array or list.array.items.len != count) return error.InvalidLayerTypes; + for (list.array.items, out[0..count]) |item, *full| { + if (isString(item, "full_attention")) full.* = true else if (!isString(item, "linear_attention")) return error.InvalidLayerTypes; + } +} + +/// The multimodal rope's three sections and their interleaving: the text and image positions a vision tower feeds. +pub const Mrope = struct { section: [3]usize = .{ 11, 11, 10 }, interleaved: bool = true }; + +/// `rope_parameters`' mrope fields: three sections filling half the rotary width, interleaved (the kernels' layout). +pub fn mrope(rope: std.json.ObjectMap, rotary: usize) Error!Mrope { + var m: Mrope = .{}; + if (rope.get("mrope_interleaved")) |v| if (!isFlag(v, true)) return error.InvalidRotary; + const list = rope.get("mrope_section") orelse return m; + if (list == .null) return m; + if (list != .array or list.array.items.len != 3) return error.InvalidRotary; + var sum: usize = 0; + for (list.array.items, &m.section) |item, *x| { + if (item != .integer or item.integer < 0) return error.InvalidRotary; + x.* = @intCast(item.integer); + sum += x.*; + } + if (sum * 2 != rotary) return error.InvalidRotary; + return m; +} + +/// `max_position_embeddings`: a positive token count, else the family's 262,144. +pub fn maxPosition(tower: std.json.ObjectMap) Error!usize { + const v = tower.get("max_position_embeddings") orelse return 262144; + if (v != .integer or v.integer <= 0 or v.integer > std.math.maxInt(u32)) return error.InvalidConfig; + return @intCast(v.integer); +} + +/// Refuses a tower whose activation, attention gate, attention bias or recurrent state type the kernels do not compute. +pub fn computes(tower: std.json.ObjectMap) Error!void { + if (tower.get("hidden_act")) |v| if (!isString(v, "silu")) return error.UnsupportedActivation; + // "swish" is the gate the kernels apply, att * sigmoid(gate), as the qwen27 family reads it + if (tower.get("output_gate_type")) |v| if (!isString(v, "swish")) return error.UnsupportedAttentionGate; + if (tower.get("attn_output_gate")) |v| if (!isFlag(v, true)) return error.UnsupportedAttentionGate; + if (tower.get("attention_bias")) |v| if (!isFlag(v, false)) return error.UnsupportedAttentionGate; + inline for (.{ "linear_attn_state_dtype", "mamba_ssm_dtype" }) |key| { + if (tower.get(key)) |v| if (!isString(v, "float32")) return error.UnsupportedStateType; + } +} + +/// The sizes the kernels index with 32-bit counts and the host multiplies: every product must fit. +pub const Sizes = struct { + hidden: usize, + intermediate: usize, + vocab: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + key_heads: usize, + value_heads: usize, + key_dim: usize, + value_dim: usize, + conv: usize, + experts: usize, + moe_width: usize, + shared_width: usize, +}; + +pub fn products(s: Sizes) Error!void { + if (s.heads % s.kv_heads != 0 or s.value_heads % s.key_heads != 0) return error.InvalidConfig; + const limit: usize = std.math.maxInt(u32); + const q = try mul(try mul(s.heads, s.head_dim), 2); + const kv = try mul(s.kv_heads, s.head_dim); + const k = try mul(s.key_heads, s.key_dim); + const v = try mul(s.value_heads, s.value_dim); + const conv = try mul(try add(try mul(k, 2), v), s.conv); + const state = try mul(try mul(v, s.key_dim), 4); + const widths = [_]usize{ q, kv, conv, state, try mul(s.hidden, s.intermediate), try mul(s.hidden, s.vocab), try mul(s.hidden, try mul(s.experts, s.moe_width)), try mul(s.hidden, s.shared_width) }; + for (widths) |w| if (w > limit) return error.InvalidConfig; +} + +/// The end ids, config.json's (root, then text tower) and generation_config.json's, each once and below `vocab`. +pub fn eos(out: *[max_eos]u32, root: std.json.ObjectMap, tower: std.json.ObjectMap, generation: ?std.json.ObjectMap, vocab: usize) Error![]const u32 { + var n: usize = 0; + const holders = [_]?std.json.Value{ root.get("eos_token_id"), tower.get("eos_token_id"), if (generation) |g| g.get("eos_token_id") else null }; + for (holders) |h| if (h) |v| try collect(out, &n, v, vocab); + if (n == 0) return error.MissingEos; + return out[0..n]; +} + +fn collect(out: *[max_eos]u32, n: *usize, v: std.json.Value, vocab: usize) Error!void { + switch (v) { + .null => {}, + .array => |list| for (list.items) |item| try collect(out, n, item, vocab), + .integer => |i| { + if (i < 0 or i >= vocab) return error.BadEos; + const id: u32 = @intCast(i); + if (std.mem.indexOfScalar(u32, out[0..n.*], id) != null) return; + if (n.* == max_eos) return error.TooManyEos; + out[n.*] = id; + n.* += 1; + }, + else => return error.BadEos, + } +} + +fn mul(a: usize, b: usize) Error!usize { + return std.math.mul(usize, a, b) catch error.InvalidConfig; +} + +fn add(a: usize, b: usize) Error!usize { + return std.math.add(usize, a, b) catch error.InvalidConfig; +} + +fn isString(v: std.json.Value, want: []const u8) bool { + return v == .string and std.mem.eql(u8, v.string, want); +} + +/// A JSON boolean, or the 0 / 1 some conversions write in its place. +fn isFlag(v: std.json.Value, want: bool) bool { + return switch (v) { + .bool => |b| b == want, + .integer => |i| i == @intFromBool(want), + else => false, + }; +} + +fn parsed(a: std.mem.Allocator, text: []const u8) !std.json.ObjectMap { + return (try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{})).object; +} + +test "the computed parts: silu, the swish gate, no bias, fp32 state; 0 and 1 stand for false and true" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try computes(try parsed(a, "{}")); + try computes(try parsed(a, "{\"hidden_act\":\"silu\",\"output_gate_type\":\"swish\",\"attn_output_gate\":1,\"attention_bias\":0,\"mamba_ssm_dtype\":\"float32\"}")); + try std.testing.expectError(error.UnsupportedActivation, computes(try parsed(a, "{\"hidden_act\":\"gelu\"}"))); + try std.testing.expectError(error.UnsupportedAttentionGate, computes(try parsed(a, "{\"output_gate_type\":\"sigmoid\"}"))); + try std.testing.expectError(error.UnsupportedAttentionGate, computes(try parsed(a, "{\"attn_output_gate\":false}"))); + try std.testing.expectError(error.UnsupportedAttentionGate, computes(try parsed(a, "{\"attention_bias\":true}"))); + try std.testing.expectError(error.UnsupportedStateType, computes(try parsed(a, "{\"mamba_ssm_dtype\":\"bfloat16\"}"))); + try std.testing.expectError(error.UnsupportedStateType, computes(try parsed(a, "{\"linear_attn_state_dtype\":\"float16\"}"))); +} + +test "end ids from config.json and generation_config.json, once each, refused past the vocabulary" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var out: [max_eos]u32 = undefined; + // the 27B: config.json names 248044, generation_config.json adds 248046 + const ids = try eos(&out, try parsed(a, "{}"), try parsed(a, "{\"eos_token_id\":248044}"), try parsed(a, "{\"eos_token_id\":[248046,248044]}"), 248320); + try std.testing.expectEqualSlices(u32, &.{ 248044, 248046 }, ids); + try std.testing.expectError(error.MissingEos, eos(&out, try parsed(a, "{}"), try parsed(a, "{}"), null, 10)); + try std.testing.expectError(error.BadEos, eos(&out, try parsed(a, "{\"eos_token_id\":10}"), try parsed(a, "{}"), null, 10)); + try std.testing.expectError(error.BadEos, eos(&out, try parsed(a, "{\"eos_token_id\":\"2\"}"), try parsed(a, "{}"), null, 10)); + try std.testing.expectError(error.TooManyEos, eos(&out, try parsed(a, "{\"eos_token_id\":[0,1,2,3,4,5,6,7,8]}"), try parsed(a, "{}"), null, 10)); +} + +test "sizes: products past 32 bits and uneven head groups are refused" { + const ok: Sizes = .{ .hidden = 5120, .intermediate = 17408, .vocab = 248320, .heads = 24, .kv_heads = 4, .head_dim = 256, .key_heads = 16, .value_heads = 48, .key_dim = 128, .value_dim = 128, .conv = 4, .experts = 0, .moe_width = 0, .shared_width = 0 }; + try products(ok); + var moe = ok; + moe.experts = 256; + moe.moe_width = 512; + try products(moe); + var wide = ok; + wide.vocab = 1 << 20; + try std.testing.expectError(error.InvalidConfig, products(wide)); + var uneven = ok; + uneven.kv_heads = 5; + try std.testing.expectError(error.InvalidConfig, products(uneven)); + var huge = ok; + huge.hidden = std.math.maxInt(usize) / 2; + try std.testing.expectError(error.InvalidConfig, products(huge)); +} + +test "layer kinds: any order from layer_types, the interval otherwise; wrong length or names refused" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var kinds: [max_layers]bool = undefined; + try layers(&kinds, try parsed(a, "{}"), 8, 4); + try std.testing.expectEqualSlices(bool, &.{ false, false, false, true, false, false, false, true }, kinds[0..8]); + try layers(&kinds, try parsed(a, "{\"layer_types\":[\"full_attention\",\"linear_attention\",\"full_attention\"]}"), 3, 4); + try std.testing.expectEqualSlices(bool, &.{ true, false, true }, kinds[0..3]); + try std.testing.expectError(error.InvalidLayerTypes, layers(&kinds, try parsed(a, "{\"layer_types\":[\"full_attention\"]}"), 3, 4)); + try std.testing.expectError(error.InvalidLayerTypes, layers(&kinds, try parsed(a, "{\"layer_types\":[\"sliding_attention\"]}"), 1, 4)); + try std.testing.expectError(error.InvalidConfig, layers(&kinds, try parsed(a, "{}"), max_layers + 1, 4)); +} + +test "mrope: three sections filling half the rotary width, interleaved; max_position positive" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const m = try mrope(try parsed(a, "{\"mrope_section\":[11,11,10],\"mrope_interleaved\":true}"), 64); + try std.testing.expectEqual([3]usize{ 11, 11, 10 }, m.section); + try std.testing.expectEqual(Mrope{}, try mrope(try parsed(a, "{}"), 64)); + try std.testing.expectError(error.InvalidRotary, mrope(try parsed(a, "{\"mrope_section\":[11,11,11]}"), 64)); + try std.testing.expectError(error.InvalidRotary, mrope(try parsed(a, "{\"mrope_section\":[32,32]}"), 64)); + try std.testing.expectError(error.InvalidRotary, mrope(try parsed(a, "{\"mrope_interleaved\":false}"), 64)); + try std.testing.expectEqual(@as(usize, 262144), try maxPosition(try parsed(a, "{}"))); + try std.testing.expectEqual(@as(usize, 32768), try maxPosition(try parsed(a, "{\"max_position_embeddings\":32768}"))); + try std.testing.expectError(error.InvalidConfig, maxPosition(try parsed(a, "{\"max_position_embeddings\":0}"))); +} diff --git a/zig/src/families/qwen3_5/weights/checkpoint_test.zig b/zig/src/families/qwen3_5/weights/checkpoint_test.zig index a89b1478272..02bc4f44833 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint_test.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint_test.zig @@ -91,7 +91,7 @@ const dense_config = \\ "num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, \\ "linear_num_value_heads": 2, "linear_key_head_dim": 32, "linear_value_head_dim": 16, \\ "linear_conv_kernel_dim": 4, "vocab_size": 16, "full_attention_interval": 2, - \\ "layer_types": ["linear_attention", "full_attention"]}} + \\ "layer_types": ["linear_attention", "full_attention"], "eos_token_id": 1}} ; const moe_config = @@ -103,7 +103,7 @@ const moe_config = \\ "num_key_value_heads": 1, "head_dim": 32, "linear_num_key_heads": 1, "linear_num_value_heads": 2, \\ "linear_key_head_dim": 32, "linear_value_head_dim": 16, "linear_conv_kernel_dim": 4, "vocab_size": 16, \\ "full_attention_interval": 1, "num_experts": 2, "num_experts_per_tok": 1, "moe_intermediate_size": 32, - \\ "shared_expert_intermediate_size": 32}} + \\ "shared_expert_intermediate_size": 32, "eos_token_id": 1}} ; const L = "language_model.model."; diff --git a/zig/src/families/qwen3_5/weights/config.zig b/zig/src/families/qwen3_5/weights/config.zig index 337897c09ac..1161e6eb6c7 100644 --- a/zig/src/families/qwen3_5/weights/config.zig +++ b/zig/src/families/qwen3_5/weights/config.zig @@ -17,6 +17,8 @@ pub const Config = struct { quant: quant.Config, /// `tie_word_embeddings`: the output head is the embedding. tied: bool, + /// The end ids of config.json and generation_config.json. + eos: []const u32, pub fn deinit(c: *Config) void { c.arena.deinit(); @@ -29,11 +31,18 @@ pub const Config = struct { defer gpa.free(path); const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 26)); defer gpa.free(bytes); - return parse(gpa, bytes); + const gen_path = try std.fs.path.join(gpa, &.{ dir, "generation_config.json" }); + defer gpa.free(gen_path); + const generation = std.Io.Dir.cwd().readFileAlloc(io, gen_path, gpa, .limited(1 << 20)) catch |e| switch (e) { + error.FileNotFound => null, + else => return e, + }; + defer if (generation) |g| gpa.free(g); + return parse(gpa, bytes, generation); } - /// `load()`'s reading of config.json: top level or `text_config`, model_type qwen3_5 or qwen3_5_moe. - pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) Error!Config { + /// `load()`'s reading of config.json (root or `text_config`, qwen3_5 or qwen3_5_moe) and generation_config.json. + pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, generation: ?[]const u8) Error!Config { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const a = arena.allocator(); @@ -42,7 +51,11 @@ pub const Config = struct { const table = try quant.detect(a, .{ .root = doc, .quantization = try shared.pickObject(doc, tower, "quantization") }); const width = try table.width(""); const spec = try shared.geometry(tower, width.bits, width.group); - return .{ .arena = arena, .spec = spec, .quant = table, .tied = shared.isTied(doc, tower) }; + const gen = if (generation) |g| (try std.json.parseFromSliceLeaky(std.json.Value, a, g, .{})) else null; + if (gen) |g| if (g != .object) return error.InvalidConfig; + const ids = try a.create([shared.checks.max_eos]u32); + const eos = try shared.checks.eos(ids, doc, tower, if (gen) |g| g.object else null, spec.vocab); + return .{ .arena = arena, .spec = spec, .quant = table, .tied = shared.isTied(doc, tower), .eos = eos }; } }; @@ -55,14 +68,14 @@ const sample = \\ "num_attention_heads": 16, "num_key_value_heads": 4, "head_dim": 256, \\ "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_key_head_dim": 128, \\ "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "vocab_size": 248320, - \\ "rms_norm_eps": 1e-06, "full_attention_interval": 4, "mtp_num_hidden_layers": 1, + \\ "rms_norm_eps": 1e-06, "full_attention_interval": 4, "mtp_num_hidden_layers": 1, "eos_token_id": 248044, \\ "layer_types": ["linear_attention", "linear_attention", "linear_attention", "full_attention", \\ "linear_attention", "linear_attention", "linear_attention", "full_attention"], \\ "rope_parameters": {"rope_theta": 10000000, "partial_rotary_factor": 0.25}}} ; test "the config carries the geometry, the quantization width and the tying" { - var c = try Config.parse(std.testing.allocator, sample); + var c = try Config.parse(std.testing.allocator, sample, null); defer c.deinit(); try std.testing.expectEqual(@as(usize, 4096), c.spec.hidden); try std.testing.expectEqual(@as(u8, 4), c.spec.bits); @@ -71,7 +84,7 @@ test "the config carries the geometry, the quantization width and the tying" { } test "per-tensor widths override the global one, and a bad entry fails only when used" { - var c = try Config.parse(std.testing.allocator, sample); + var c = try Config.parse(std.testing.allocator, sample, null); defer c.deinit(); try std.testing.expectEqual(Width{ .bits = 8, .group = 32 }, try c.quant.width("language_model.model.layers.0.mlp.gate")); try std.testing.expectEqual(Width{ .bits = 4, .group = 64 }, try c.quant.width("language_model.model.layers.1.mlp.gate")); @@ -82,8 +95,8 @@ test "the Python loader's refusals of a quantization" { const a = std.testing.allocator; const bits = try std.mem.replaceOwned(u8, a, sample, "\"bits\": 4,", "\"bits\": 7,"); defer a.free(bits); - try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, bits)); + try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, bits, null)); const gptq = try std.mem.replaceOwned(u8, a, sample, "\"mode\": \"affine\"", "\"mode\": \"gptq\""); defer a.free(gptq); - try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, gptq)); + try std.testing.expectError(error.UnsupportedQuantization, Config.parse(a, gptq, null)); } From 57fadd18bbc55844fee97e5e81f9b052807277a4 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:42:10 +0200 Subject: [PATCH 10/52] feat(hip): the runtime pieces an engine uses beyond #463's model-free set The device count, a context's free and total memory (hipMemGetInfo, looked up on its own so the admission set is unchanged), a buffer's base address, a pinned host buffer's sub-range and typed view, and raw.zig: device copies, fills and pinned transfers on a forward's raw stream handle, none of them on the counting stream. hip-gpu-test checks each on the GPU. --- zig/src/hip/engine_runtime_tests.zig | 52 ++++++++++++++++++++++++++++ zig/src/hip/memory.zig | 16 +++++++++ zig/src/hip/raw.zig | 39 +++++++++++++++++++++ zig/src/hip/runtime.zig | 7 ++++ zig/src/hip/runtime_tests.zig | 4 +++ 5 files changed, 118 insertions(+) create mode 100644 zig/src/hip/engine_runtime_tests.zig create mode 100644 zig/src/hip/raw.zig diff --git a/zig/src/hip/engine_runtime_tests.zig b/zig/src/hip/engine_runtime_tests.zig new file mode 100644 index 00000000000..109d1d52b86 --- /dev/null +++ b/zig/src/hip/engine_runtime_tests.zig @@ -0,0 +1,52 @@ +//! The runtime pieces an engine uses beyond the model-free tests: device count, free memory, addresses, raw copies. +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 HostBuffer = @import("memory.zig").HostBuffer; +const raw = @import("raw.zig"); +const counting = @import("launches/util.zig").counting; + +test "device count and free memory, buffer addresses, pinned views and raw-stream copies and fills" { + var r = try Runtime.open(); + defer r.close(); + try std.testing.expect(try r.deviceCount() >= 1); + var ctx = try Context.init(&r, 0); + defer ctx.deinit(); + const mem = try ctx.memInfo(); + try std.testing.expect(mem.total > 0 and mem.free <= mem.total); + var stream = try Stream.init(&r); + defer stream.deinit(); + const n = 4096; + var a = try DeviceBuffer.alloc(&r, n); + defer a.free(); + var b = try DeviceBuffer.alloc(&r, n); + defer b.free(); + try std.testing.expectEqual(@intFromPtr(a.ptr), a.base()); + var host = try HostBuffer.alloc(&r, 2 * n); + defer host.free(); + for (host.slice(u32), 0..) |*w, i| w.* = @intCast(i); + try std.testing.expectEqual(@as(usize, 2 * n / 4), host.slice(u32).len); + // a view of the second half goes up through the #463 API, comes back through a raw-stream download + try a.uploadAsync(0, host.view(n, 2 * n), stream); + try raw.copy(b, 16, a.base() + 32, n - 32, stream.handle); + try raw.fill8(a, 0xab, stream.handle); + try raw.download(b, 0, host.bytes[0..n], stream.handle); + try stream.synchronize(); + const words = host.slice(u32); + for (words[4 .. n / 4 - 4], n / 4 + 8..) |w, want| try std.testing.expectEqual(@as(u32, @intCast(want)), w); + var back: [n]u8 = undefined; + try a.download(0, &back); + for (back) |x| try std.testing.expectEqual(@as(u8, 0xab), x); + try raw.fill32(a, 0x01020304, stream.handle); + try raw.upload(b, 0, host.bytes[n .. n + 8], stream.handle); + // the counting stream queues nothing + try raw.fill8(a, 0, counting); + try raw.copy(a, 0, b.base(), n, counting); + try stream.synchronize(); + try a.download(0, &back); + for (std.mem.bytesAsSlice(u32, &back)) |w| try std.testing.expectEqual(@as(u32, 0x01020304), w); + try std.testing.expectError(error.Invalid, raw.copy(a, n - 4, b.base(), 8, stream.handle)); + try std.testing.expectError(error.Invalid, raw.upload(a, n, host.bytes[0..1], stream.handle)); +} diff --git a/zig/src/hip/memory.zig b/zig/src/hip/memory.zig index 9c3dd094f41..7857623c9ec 100644 --- a/zig/src/hip/memory.zig +++ b/zig/src/hip/memory.zig @@ -61,6 +61,11 @@ pub const DeviceBuffer = struct { self.* = undefined; } + /// The device address of the first byte, as kernel arguments take it. + pub fn base(self: DeviceBuffer) u64 { + return @intFromPtr(self.ptr); + } + /// The device address `offset` bytes in, as kernel arguments and device copies take it; past the end is refused. pub fn address(self: DeviceBuffer, offset: usize) runtime.Error!u64 { if (offset > self.len) return error.Invalid; @@ -171,6 +176,17 @@ pub const HostBuffer = struct { return @intFromPtr(ptr); } + /// Bytes `from..to` of this buffer, still pinned, for an async copy of part of it. + pub fn view(self: HostBuffer, from: usize, to: usize) HostBuffer { + return .{ .r = self.r, .bytes = self.bytes[from..to] }; + } + + /// The bytes as `T`s, the tail that does not fill one left out. + pub fn slice(self: HostBuffer, comptime T: type) []T { + const whole = self.bytes[0 .. self.bytes.len / @sizeOf(T) * @sizeOf(T)]; + return @alignCast(std.mem.bytesAsSlice(T, @as([]align(@alignOf(T)) u8, @alignCast(whole)))); + } + /// All streams using these bytes must have completed before release. pub fn free(self: *HostBuffer) void { _ = self.r.api.hipHostFree(self.bytes.ptr); diff --git a/zig/src/hip/raw.zig b/zig/src/hip/raw.zig new file mode 100644 index 00000000000..254108c51b5 --- /dev/null +++ b/zig/src/hip/raw.zig @@ -0,0 +1,39 @@ +//! Device copies and fills on a forward's raw stream handle; the counting stream runs none of them. +const abi = @import("abi.zig"); +const runtime = @import("runtime.zig"); +const DeviceBuffer = @import("memory.zig").DeviceBuffer; +const counting = @import("launches/util.zig").counting; + +/// `n` bytes from device address `src` into `dst` at `offset`, queued on `stream`. +pub fn copy(dst: DeviceBuffer, offset: usize, src: u64, n: usize, stream: abi.Stream) runtime.Error!void { + if (offset > dst.len or n > dst.len - offset) return error.Invalid; + if (n == 0 or stream == counting) return; + try runtime.check(dst.r.api.hipMemcpyDtoDAsync(@ptrFromInt(dst.base() + offset), @ptrFromInt(src), n, stream)); +} + +/// Every byte of `b` set to `value`, queued on `stream`. +pub fn fill8(b: DeviceBuffer, value: u8, stream: abi.Stream) runtime.Error!void { + if (b.len == 0 or stream == counting) return; + try runtime.check(b.r.api.hipMemsetAsync(b.ptr, value, b.len, stream)); +} + +/// Every 32-bit word of `b` set to `value`, queued on `stream`. +pub fn fill32(b: DeviceBuffer, value: u32, stream: abi.Stream) runtime.Error!void { + if (b.len % 4 != 0) return error.Invalid; + if (b.len == 0 or stream == counting) return; + try runtime.check(b.r.api.hipMemsetD32Async(b.ptr, @bitCast(value), b.len / 4, stream)); +} + +/// Pinned host `bytes` into `dst` at `offset`, queued on `stream`; they stay unchanged until it completes. +pub fn upload(dst: DeviceBuffer, offset: usize, bytes: []const u8, stream: abi.Stream) runtime.Error!void { + if (offset > dst.len or bytes.len > dst.len - offset) return error.Invalid; + if (bytes.len == 0 or stream == counting) return; + try runtime.check(dst.r.api.hipMemcpyHtoDAsync(@ptrFromInt(dst.base() + offset), bytes.ptr, bytes.len, stream)); +} + +/// `out.len` bytes of `src` from `offset` into pinned host `out`, queued on `stream`. +pub fn download(src: DeviceBuffer, offset: usize, out: []u8, stream: abi.Stream) runtime.Error!void { + if (offset > src.len or out.len > src.len - offset) return error.Invalid; + if (out.len == 0 or stream == counting) return; + try runtime.check(src.r.api.hipMemcpyDtoHAsync(out.ptr, @ptrFromInt(src.base() + offset), out.len, stream)); +} diff --git a/zig/src/hip/runtime.zig b/zig/src/hip/runtime.zig index 8f5527bd844..690665c336c 100644 --- a/zig/src/hip/runtime.zig +++ b/zig/src/hip/runtime.zig @@ -25,6 +25,13 @@ pub const Runtime = struct { return std.mem.span(name); } + /// The GPUs this process sees. + pub fn deviceCount(self: *const Runtime) Error!c_int { + var n: c_int = 0; + try check(self.api.hipGetDeviceCount(&n)); + return n; + } + pub fn close(self: *Runtime) void { self.lib.close(); self.* = undefined; diff --git a/zig/src/hip/runtime_tests.zig b/zig/src/hip/runtime_tests.zig index d4b0ebfc23d..69443e3fbad 100644 --- a/zig/src/hip/runtime_tests.zig +++ b/zig/src/hip/runtime_tests.zig @@ -369,3 +369,7 @@ test "memory info sees a new allocation" { try std.testing.expectEqual(before.total, after.total); try std.testing.expect(after.free + len <= before.free); } + +test { + _ = @import("engine_runtime_tests.zig"); +} From 211ea815f3fe009d469d2fa12c999d64e094ef11 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:22:42 +0200 Subject: [PATCH 11/52] feat(hip): the kernels a tensor-parallel rank and the MTP head add ops/tp.hpp in the ops group, device code only: an activation plus an fp32 rank sum rounded once, a rank's local expert ids and the masks of the experts another rank answers, and a token's softmax probability (MTP's confidence). Zig launches in launches/tp.zig, `Ops.addWide`, `moeLocalize`, `moeForeignItems`, `moeZeroForeign` and `tokenProb`. hip-kernel-test checks each against a host reference. --- zig/build/hip.zig | 12 +-- zig/kernels/hip/ops/ops.hip | 1 + zig/kernels/hip/ops/tp.hpp | 84 +++++++++++++++++++++ zig/src/hip/kernel_tests.zig | 1 + zig/src/hip/kernel_tests/tp.zig | 128 ++++++++++++++++++++++++++++++++ zig/src/hip/launches.zig | 16 ++++ zig/src/hip/launches/tp.zig | 77 +++++++++++++++++++ zig/src/hip/ops/draw.zig | 6 ++ zig/src/hip/ops/ops.zig | 6 ++ zig/src/hip/ops/tp.zig | 31 ++++++++ 10 files changed, 356 insertions(+), 6 deletions(-) create mode 100644 zig/kernels/hip/ops/tp.hpp create mode 100644 zig/src/hip/kernel_tests/tp.zig create mode 100644 zig/src/hip/launches/tp.zig create mode 100644 zig/src/hip/ops/tp.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 91d7017309f..76f608f269d 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -91,12 +91,12 @@ const groups = [_][]const u8{ "ops/ops.hip", "ops/act.hip", "attention/attention /// 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", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", "common/wmma.hpp", - "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", - "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", "tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", - "tiles/plan.hpp", "tiles/stream.hpp", + "attention/attention_fa.hip", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", + "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", + "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", + "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", + "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", "tiles/gemm_kp.hpp", + "tiles/matrix_gemm.hpp", "tiles/plan.hpp", "tiles/stream.hpp", }; /// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20. diff --git a/zig/kernels/hip/ops/ops.hip b/zig/kernels/hip/ops/ops.hip index a5e20960b11..5800c0dde62 100644 --- a/zig/kernels/hip/ops/ops.hip +++ b/zig/kernels/hip/ops/ops.hip @@ -8,3 +8,4 @@ #include "norms.hpp" #include "moe.hpp" #include "draw.hpp" +#include "tp.hpp" diff --git a/zig/kernels/hip/ops/tp.hpp b/zig/kernels/hip/ops/tp.hpp new file mode 100644 index 00000000000..1b72b16a2c0 --- /dev/null +++ b/zig/kernels/hip/ops/tp.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include "common.hpp" +#include "draw.hpp" + +// Tensor-parallel forward ops: residual add of an fp32 sum, expert-share remap and masks; MTP token probability. + +namespace { + +__device__ __forceinline__ long long tp_gid() { return static_cast(blockIdx.x) * blockDim.x + threadIdx.x; } + +constexpr int kProbThreads = 256; + +} // namespace + +// out = round(float(x) + y): the residual of a rank-summed fp32 share. +extern "C" __global__ void tf_add_wide(const void* x, const float* y, void* out, int kind, long long n) { + long long i = tp_gid(); + if (i >= n) return; + if (kind == 1) { + float v = __half2float(static_cast(x)[i]) + y[i]; + static_cast<__half*>(out)[i] = __float2half_rn(v); + } else { + float v = bf16_to_float(static_cast(x)[i]) + y[i]; + static_cast(out)[i] = float_to_bf16(v); + } +} + +// out[i] = the rank's local id of expert pick[i], or `skip` (an id past the rank's experts) when another rank holds it. +extern "C" __global__ void tf_moe_localize(const int* pick, const int* remap, int* out, int n, int skip) { + int i = static_cast(tp_gid()); + if (i >= n) return; + int local = remap[pick[i]]; + out[i] = local >= 0 ? local : skip; +} + +// An item of the skip expert does no work. +extern "C" __global__ void tf_moe_foreign_items(int* items, int count, int skip) { + int i = static_cast(tp_gid()); + if (i < count && items[i * 3] == skip) items[i * 3 + 2] = 0; +} + +// A pair another rank's expert answers has zero rows (selected, not multiplied: the buffer holds anything). +extern "C" __global__ void tf_moe_zero_foreign(float* y, const int* picks, int skip, long long pairs, int d) { + long long i = tp_gid(); + if (i >= pairs * d) return; + if (picks[i / d] == skip) y[i] = 0.f; +} + +// out[r] = softmax(row r)[id[r]], or of the row's largest value when `id` is null; one block a row, a NaN in gives NaN. +extern "C" __global__ void tf_token_prob(const uint16_t* logits, int kind, int n, const int* id, float* out) { + const uint16_t* row = logits + static_cast(blockIdx.x) * n; + __shared__ float shared[kProbThreads]; + float top = -INFINITY; + bool nan = false; + for (int i = threadIdx.x; i < n; i += kProbThreads) { + float v = widen(row[i], kind); + nan |= v != v; + top = fmaxf(top, v); + } + shared[threadIdx.x] = nan ? NAN : top; + __syncthreads(); + for (int stride = kProbThreads / 2; stride > 0; stride >>= 1) { + if (threadIdx.x < stride) { + float a = shared[threadIdx.x], b = shared[threadIdx.x + stride]; + shared[threadIdx.x] = (a != a || b != b) ? NAN : fmaxf(a, b); + } + __syncthreads(); + } + const float peak = shared[0]; + __syncthreads(); + float total = 0.f; + for (int i = threadIdx.x; i < n; i += kProbThreads) total += expf(widen(row[i], kind) - peak); + shared[threadIdx.x] = total; + __syncthreads(); + for (int stride = kProbThreads / 2; stride > 0; stride >>= 1) { + if (threadIdx.x < stride) shared[threadIdx.x] += shared[threadIdx.x + stride]; + __syncthreads(); + } + if (threadIdx.x == 0) { + const float chosen = id ? expf(widen(row[id[blockIdx.x]], kind) - peak) : 1.f; + out[blockIdx.x] = chosen / shared[0]; + } +} diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 27a95da9362..94641edc08e 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -23,6 +23,7 @@ test { _ = @import("kernel_tests/chain.zig"); _ = @import("kernel_tests/attention.zig"); _ = @import("kernel_tests/ops.zig"); + _ = @import("kernel_tests/tp.zig"); _ = @import("kernel_tests/affine/affine.zig"); _ = @import("kernel_tests/affine/rows.zig"); } diff --git a/zig/src/hip/kernel_tests/tp.zig b/zig/src/hip/kernel_tests/tp.zig new file mode 100644 index 00000000000..dd1b80f1f73 --- /dev/null +++ b/zig/src/hip/kernel_tests/tp.zig @@ -0,0 +1,128 @@ +//! A tensor-parallel rank's kernels and MTP's token probability against host references. +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 Kind = ops.Kind; + +fn act(t: *const Rig) Kind { + return if (t.bf16) .bf16 else .f16; +} + +/// The activation's round-to-nearest-even of an fp32 value, as torch rounds. +fn round(t: *const Rig, f: f32) u16 { + 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); +} + +test "a residual plus an fp32 sum rounds once to the activation, and the expert-share remap and masks are exact" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x7B }; + const n = 3000; + const hx = try gpa.alloc(u16, n); + defer gpa.free(hx); + const hy = try gpa.alloc(f32, n); + defer gpa.free(hy); + for (hx, hy) |*x, *y| { + x.* = t.bits(rng.unit() * 6.0 - 3.0); + y.* = rng.unit() * 0.01 - 0.005; + } + var x = try t.upload(hx); + defer x.free(); + var y = try t.upload(hy); + defer y.free(); + var out = try t.alloc(n * 2); + defer out.free(); + try o.addWide(.{ .ptr = at(x), .kind = act(t) }, at(y), .{ .ptr = at(out), .kind = act(t) }, n); + const experts = 16; + const skip = 8; + var remap: [experts]i32 = undefined; + for (&remap, 0..) |*r, e| r.* = if (e % 2 == 0) @intCast(e / 2) else -1; + var picks: [64]i32 = undefined; + for (&picks) |*p| p.* = @intCast(rng.next() % experts); + var dev_remap = try t.upload(&remap); + defer dev_remap.free(); + var dev_picks = try t.upload(&picks); + defer dev_picks.free(); + var local = try t.alloc(picks.len * 4); + defer local.free(); + try o.moeLocalize(at(dev_picks), at(dev_remap), at(local), picks.len, skip); + var items = [_]i32{ 0, 0, 5, skip, 5, 7, 3, 12, 2, skip, 17, 1 }; + var dev_items = try t.upload(&items); + defer dev_items.free(); + try o.moeForeignItems(at(dev_items), items.len / 3, skip); + const d = 33; + const ys = try gpa.alloc(f32, picks.len * d); + defer gpa.free(ys); + for (ys) |*v| v.* = rng.unit() + 1.0; + var dev_ys = try t.upload(ys); + defer dev_ys.free(); + var local_picks: [picks.len]i32 = undefined; + for (&local_picks, picks) |*l, p| l.* = if (remap[@intCast(p)] >= 0) remap[@intCast(p)] else skip; + var dev_local = try t.upload(&local_picks); + defer dev_local.free(); + try o.moeZeroForeign(at(dev_ys), at(dev_local), skip, picks.len, d); + try t.stream.synchronize(); + const got = try rig.download(u16, out); + defer gpa.free(got); + for (got, hx, hy) |g, xb, yv| try std.testing.expectEqual(round(t, @as(f32, @floatCast(t.value(xb))) + yv), g); + const gl = try rig.download(i32, local); + defer gpa.free(gl); + try std.testing.expectEqualSlices(i32, &local_picks, gl); + const gi = try rig.download(i32, dev_items); + defer gpa.free(gi); + for (0..items.len / 3) |k| { + const want: i32 = if (items[3 * k] == skip) 0 else items[3 * k + 2]; + try std.testing.expectEqual(items[3 * k], gi[3 * k]); + try std.testing.expectEqual(want, gi[3 * k + 2]); + } + const gy = try rig.download(f32, dev_ys); + defer gpa.free(gy); + for (gy, ys, 0..) |g, v, k| try std.testing.expectEqual(if (local_picks[k / d] == skip) 0 else v, g); +} + +test "a token's probability is its softmax share of the row, or the largest one's with no ids, within 1e-6 of float64" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x9E1 }; + const rows = 6; + const n = 4099; + const hl = try gpa.alloc(u16, rows * n); + defer gpa.free(hl); + for (hl) |*x| x.* = t.bits(rng.unit() * 16.0 - 8.0); + var ids: [rows]i32 = undefined; + for (&ids) |*id| id.* = @intCast(rng.next() % n); + var logits = try t.upload(hl); + defer logits.free(); + var dev_ids = try t.upload(&ids); + defer dev_ids.free(); + var with_ids = try t.alloc(rows * 4); + defer with_ids.free(); + var largest = try t.alloc(rows * 4); + defer largest.free(); + const l: ops.Tensor = .{ .ptr = at(logits), .kind = act(t) }; + try o.tokenProb(l, rows, n, at(dev_ids), at(with_ids)); + try o.tokenProb(l, rows, n, 0, at(largest)); + try t.stream.synchronize(); + const gw = try rig.download(f32, with_ids); + defer gpa.free(gw); + const gm = try rig.download(f32, largest); + defer gpa.free(gm); + for (0..rows) |r| { + const row = hl[r * n ..][0..n]; + var peak: f64 = -std.math.inf(f64); + for (row) |x| peak = @max(peak, t.value(x)); + var total: f64 = 0; + for (row) |x| total += @exp(t.value(x) - peak); + const want = @exp(t.value(row[@intCast(ids[r])]) - peak) / total; + try std.testing.expectApproxEqAbs(want, gw[r], 1e-6); + try std.testing.expectApproxEqAbs(1.0 / total, gm[r], 1e-6); + } +} diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 2ae4130f343..c82f8311d67 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -37,6 +37,7 @@ const recurrence = @import("launches/recurrence.zig"); const plan = @import("launches/plan.zig"); const elementwise = @import("launches/elementwise.zig"); const draw = @import("launches/draw.zig"); +const tp = @import("launches/tp.zig"); pub const ConvArgs = conv.ConvArgs; pub const PlanArgs = plan.PlanArgs; @@ -127,6 +128,11 @@ pub const Launcher = struct { router_small: [2]Function, rms_rows: Function, qk_rope: Function, + add_wide: Function, + moe_localize: Function, + moe_foreign_items: Function, + moe_zero_foreign: Function, + token_prob: Function, }; /// Which kernels a run takes where two give the same bits; every one defaults on. @@ -191,6 +197,11 @@ pub const Launcher = struct { .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"), + .add_wide = try ops.function("tf_add_wide"), + .moe_localize = try ops.function("tf_moe_localize"), + .moe_foreign_items = try ops.function("tf_moe_foreign_items"), + .moe_zero_foreign = try ops.function("tf_moe_zero_foreign"), + .token_prob = try ops.function("tf_token_prob"), }; const ns = "_ZN2tf4rocm"; l.rms = .{ @@ -286,6 +297,11 @@ pub const Launcher = struct { 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 tf_add_wide = tp.tf_add_wide; + pub const tf_moe_localize = tp.tf_moe_localize; + pub const tf_moe_foreign_items = tp.tf_moe_foreign_items; + pub const tf_moe_zero_foreign = tp.tf_moe_zero_foreign; + pub const tf_token_prob = tp.tf_token_prob; pub const pagedCausal = attention.pagedCausal; pub const tf_gdn_gate = recurrence.tf_gdn_gate; pub const tf_gated_delta = recurrence.tf_gated_delta; diff --git a/zig/src/hip/launches/tp.zig b/zig/src/hip/launches/tp.zig new file mode 100644 index 00000000000..f4f6d85f7b5 --- /dev/null +++ b/zig/src/hip/launches/tp.zig @@ -0,0 +1,77 @@ +//! A tensor-parallel rank's launches (the fp32 sum into a residual, the local expert ids) and MTP's token probability. + +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 F = util.F; +const CF = util.CF; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; + +fn blocks(n: i64, threads: i64) c_int { + return @intCast(@divFloor(n + threads - 1, threads)); +} + +/// out = round(x + y) of `n` values, x and out of `kind` (1 fp16, 2 bf16), y fp32. +pub fn tf_add_wide(l: *const Launcher, x: C, y: CF, out: P, kind: c_int, n: c_longlong, s: S) Error!void { + if (n == 0) return; + 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.go(l.op.add_wide, dim(blocks(n, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// out[i] = remap[pick[i]], or `skip` where it is negative. +pub fn tf_moe_localize(l: *const Launcher, pick: CI, remap: CI, out: I, n: c_int, skip: c_int, s: S) Error!void { + if (n == 0) return; + var a: Args = .{}; + try a.add(ad(pick)); + try a.add(ad(remap)); + try a.add(ad(out)); + try a.add(n); + try a.add(skip); + try l.go(l.op.moe_localize, dim(blocks(n, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Zeroes the pair count of every plan item of the `skip` expert. +pub fn tf_moe_foreign_items(l: *const Launcher, items: I, count: c_int, skip: c_int, s: S) Error!void { + if (count == 0) return; + var a: Args = .{}; + try a.add(ad(items)); + try a.add(count); + try a.add(skip); + try l.go(l.op.moe_foreign_items, dim(blocks(count, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// Zeroes the rows of `y` (pairs, d) fp32 whose pick is `skip`. +pub fn tf_moe_zero_foreign(l: *const Launcher, y: F, picks: CI, skip: c_int, pairs: c_longlong, d: c_int, s: S) Error!void { + if (pairs == 0) return; + var a: Args = .{}; + try a.add(ad(y)); + try a.add(ad(picks)); + try a.add(skip); + try a.add(pairs); + try a.add(d); + try l.go(l.op.moe_zero_foreign, dim(blocks(pairs * d, 256), 1, 1), dim(256, 1, 1), 0, s, &a); +} + +/// out[r] = softmax(row r)[id[r]] of (rows, n) logits of `kind`, or of the row's largest value when `id` is null. +pub fn tf_token_prob(l: *const Launcher, logits: C, kind: c_int, rows: c_int, n: c_int, id: CI, out: F, 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(id)); + try a.add(ad(out)); + try l.go(l.op.token_prob, dim(rows, 1, 1), dim(256, 1, 1), 0, s, &a); +} diff --git a/zig/src/hip/ops/draw.zig b/zig/src/hip/ops/draw.zig index 6e6463acab3..4d7f5005018 100644 --- a/zig/src/hip/ops/draw.zig +++ b/zig/src/hip/ops/draw.zig @@ -15,6 +15,12 @@ pub fn argmaxRows(o: Ops, logits: Tensor, rows: usize, n: usize, out: u64) Error try o.l.tf_argmax_rows(p(logits.ptr), @backingInt(logits.kind), int(rows), int(n), i(out), o.stream); } +/// softmax(row r)[ids[r]] of `rows` logits rows (fp16 or bf16) into fp32 `out`; of the row's largest when `ids` is 0. +pub fn tokenProb(o: Ops, logits: Tensor, rows: usize, n: usize, ids: u64, out: u64) Error!void { + if (logits.kind == .f32) return error.BadShape; + try o.l.tf_token_prob(p(logits.ptr), @backingInt(logits.kind), int(rows), int(n), if (ids == 0) null else @ptrFromInt(ids), f(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; diff --git a/zig/src/hip/ops/ops.zig b/zig/src/hip/ops/ops.zig index 4a78678f720..4add41a935b 100644 --- a/zig/src/hip/ops/ops.zig +++ b/zig/src/hip/ops/ops.zig @@ -12,6 +12,7 @@ const norms = @import("norms.zig"); const elementwise = @import("elementwise.zig"); const moe = @import("moe.zig"); const draw = @import("draw.zig"); +const tp = @import("tp.zig"); pub const Kind = types.Kind; pub const Error = types.Error; @@ -82,6 +83,11 @@ pub const Ops = struct { pub const moeCombine = moe.moeCombine; pub const argmaxRows = draw.argmaxRows; pub const topkRows = draw.topkRows; + pub const tokenProb = draw.tokenProb; + pub const addWide = tp.addWide; + pub const moeLocalize = tp.moeLocalize; + pub const moeForeignItems = tp.moeForeignItems; + pub const moeZeroForeign = tp.moeZeroForeign; }; test "dtype numberings of the three kernel families" { diff --git a/zig/src/hip/ops/tp.zig b/zig/src/hip/ops/tp.zig new file mode 100644 index 00000000000..d3cb31fcf10 --- /dev/null +++ b/zig/src/hip/ops/tp.zig @@ -0,0 +1,31 @@ +//! The launches a tensor-parallel rank adds: the fp32 sum into a residual and the local expert 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; + +/// out = round(x + y): an activation `x` plus an fp32 sum `y`, rounded once to x's kind (a tp residual). +pub fn addWide(o: Ops, x: Tensor, y: u64, out: Tensor, n: usize) Error!void { + if (x.kind == .f32 or x.kind != out.kind) return error.BadShape; + try o.l.tf_add_wide(p(x.ptr), f(y), p(out.ptr), @backingInt(out.kind), @intCast(n), o.stream); +} + +/// out[i] = remap[pick[i]], or `skip` where it is negative: a tp rank's local expert ids. +pub fn moeLocalize(o: Ops, pick: u64, remap: u64, out: u64, n: usize, skip: usize) Error!void { + try o.l.tf_moe_localize(i(pick), i(remap), i(out), int(n), int(skip), o.stream); +} + +/// Zeroes the pair count of every plan item of the `skip` expert. +pub fn moeForeignItems(o: Ops, items: u64, count: usize, skip: usize) Error!void { + try o.l.tf_moe_foreign_items(i(items), int(count), int(skip), o.stream); +} + +/// Zeroes the rows of `y` (pairs, d) fp32 whose pick is `skip`. +pub fn moeZeroForeign(o: Ops, y: u64, picks: u64, skip: usize, pairs: usize, d: usize) Error!void { + try o.l.tf_moe_zero_foreign(f(y), i(picks), int(skip), @intCast(pairs), int(d), o.stream); +} From 42664f95657279db85d65ae894030766435f42af Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:22:42 +0200 Subject: [PATCH 12/52] feat(qwen3_5): the Qwen3.5 / Qwen3.6 engine on HIP, its native server and model checks The HIP branch's engine (#490) on #463's runtime and the kernel launches of #617 and #621: the lane rounds with MTP drafts, the paged attention cache and the radix prompt cache (#625), chunked prompts (#623), CUDA-graph rounds, the memory plan, and tensor parallelism over RCCL (comm/: the library, the rank link, the group). The native server takes it with `zig build native-hip -Dhip-arch=...` and the serve flags it lists (#624); `tf-qwen35-test` runs the model checks on a GPU. `zig build test` compiles both against stub kernels. The engine reads the policy (`--policy`, TF_POLICY) once and hands the kernels `Launcher.Choices`; a GPU other than the one the kernels were built for is refused with both names. round_shape.zig stays in the family: its only reader is the plan. --- build.zig | 2 +- zig/build/hip.zig | 74 ++- .../qwen3_5/backend/hip/engine/draw.zig | 127 +++++ .../qwen3_5/backend/hip/engine/engine.zig | 415 ++++++++++++++ .../backend/hip/engine/graph_cache.zig | 98 ++++ .../qwen3_5/backend/hip/engine/hip_costs.zig | 115 ++++ .../qwen3_5/backend/hip/engine/hip_lanes.zig | 513 ++++++++++++++++++ .../qwen3_5/backend/hip/engine/hip_prefix.zig | 153 ++++++ .../qwen3_5/backend/hip/engine/memory.zig | 36 ++ .../qwen3_5/backend/hip/engine/mtp.zig | 375 +++++++++++++ .../qwen3_5/backend/hip/engine/native.zig | 205 +++++++ .../qwen3_5/backend/hip/engine/prefix.zig | 17 + .../qwen3_5/backend/hip/engine/round.zig | 251 +++++++++ .../backend/hip/engine/round_graphs.zig | 12 + .../qwen3_5/backend/hip/engine/sample.zig | 92 ++++ .../qwen3_5/backend/hip/engine/scratch.zig | 48 ++ .../qwen3_5/backend/hip/engine/worker.zig | 169 ++++++ .../qwen3_5/backend/hip/forward/forward.zig | 187 +++++++ .../qwen3_5/backend/hip/forward/moe.zig | 123 +++++ .../qwen3_5/backend/hip/forward/pages.zig | 216 ++++++++ .../qwen3_5/backend/hip/forward/plan.zig | 141 +++++ .../qwen3_5/backend/hip/forward/reduce.zig | 38 ++ .../backend/hip/forward/round_shape.zig | 37 ++ .../qwen3_5/backend/hip/forward/state.zig | 257 +++++++++ .../qwen3_5/backend/hip/forward/window.zig | 173 ++++++ .../qwen3_5/backend/hip/model/bridge.zig | 87 +++ .../qwen3_5/backend/hip/model/view.zig | 124 +++++ .../qwen3_5/backend/hip/model/weights.zig | 250 +++++++++ zig/src/families/qwen3_5/hip.zig | 56 ++ zig/src/hip/admission.zig | 65 +++ zig/src/hip/comm/group.zig | 36 ++ zig/src/hip/comm/link.zig | 136 +++++ zig/src/hip/comm/rccl.zig | 125 +++++ zig/src/hip/device.zig | 70 +++ zig/src/hip/policy.zig | 248 +++++++++ zig/src/hip/root.zig | 47 ++ zig/src/hip/upload.zig | 26 + zig/src/native/hip.zig | 201 +++++++ zig/tests/hip/args.zig | 121 +++++ zig/tests/qwen35/check.zig | 122 +++++ zig/tests/qwen35/check_accuracy.zig | 34 ++ zig/tests/qwen35/check_ctx.zig | 41 ++ zig/tests/qwen35/check_invariants.zig | 139 +++++ zig/tests/qwen35/check_radix.zig | 260 +++++++++ zig/tests/qwen35/check_report.zig | 33 ++ zig/tests/qwen35/check_speed.zig | 66 +++ zig/tests/qwen35/draw_run.zig | 101 ++++ zig/tests/qwen35/group.zig | 94 ++++ zig/tests/qwen35/ids_file.zig | 61 +++ zig/tests/qwen35/lanes_run.zig | 88 +++ zig/tests/qwen35/lanes_session.zig | 118 ++++ zig/tests/qwen35/layers.zig | 196 +++++++ zig/tests/qwen35/logit_kind.zig | 36 ++ zig/tests/qwen35/logits_run.zig | 120 ++++ zig/tests/qwen35/main.zig | 195 +++++++ zig/tests/qwen35/matrix.sh | 125 +++++ zig/tests/qwen35/prefill_run.zig | 38 ++ zig/tests/qwen35/prompts.json | 1 + zig/tests/qwen35/rows_run.zig | 153 ++++++ zig/tests/qwen35/serve_cancel.py | 50 ++ zig/tests/qwen35/serve_check.py | 95 ++++ zig/tests/qwen35/serve_conc.py | 76 +++ zig/tests/qwen35/serve_prefill.py | 71 +++ zig/tests/qwen35/serve_prefix.py | 61 +++ zig/tests/qwen35/serve_tp.sh | 33 ++ zig/tests/qwen35/truth_score.zig | 211 +++++++ 66 files changed, 8082 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/draw.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/engine.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/memory.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/mtp.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/native.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/prefix.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/round.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/sample.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/scratch.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/engine/worker.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/forward.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/moe.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/pages.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/plan.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/reduce.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/state.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/forward/window.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/model/bridge.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/model/view.zig create mode 100644 zig/src/families/qwen3_5/backend/hip/model/weights.zig create mode 100644 zig/src/families/qwen3_5/hip.zig create mode 100644 zig/src/hip/admission.zig create mode 100644 zig/src/hip/comm/group.zig create mode 100644 zig/src/hip/comm/link.zig create mode 100644 zig/src/hip/comm/rccl.zig create mode 100644 zig/src/hip/device.zig create mode 100644 zig/src/hip/policy.zig create mode 100644 zig/src/hip/root.zig create mode 100644 zig/src/hip/upload.zig create mode 100644 zig/src/native/hip.zig create mode 100644 zig/tests/hip/args.zig create mode 100644 zig/tests/qwen35/check.zig create mode 100644 zig/tests/qwen35/check_accuracy.zig create mode 100644 zig/tests/qwen35/check_ctx.zig create mode 100644 zig/tests/qwen35/check_invariants.zig create mode 100644 zig/tests/qwen35/check_radix.zig create mode 100644 zig/tests/qwen35/check_report.zig create mode 100644 zig/tests/qwen35/check_speed.zig create mode 100644 zig/tests/qwen35/draw_run.zig create mode 100644 zig/tests/qwen35/group.zig create mode 100644 zig/tests/qwen35/ids_file.zig create mode 100644 zig/tests/qwen35/lanes_run.zig create mode 100644 zig/tests/qwen35/lanes_session.zig create mode 100644 zig/tests/qwen35/layers.zig create mode 100644 zig/tests/qwen35/logit_kind.zig create mode 100644 zig/tests/qwen35/logits_run.zig create mode 100644 zig/tests/qwen35/main.zig create mode 100644 zig/tests/qwen35/matrix.sh create mode 100644 zig/tests/qwen35/prefill_run.zig create mode 100644 zig/tests/qwen35/prompts.json create mode 100644 zig/tests/qwen35/rows_run.zig create mode 100644 zig/tests/qwen35/serve_cancel.py create mode 100644 zig/tests/qwen35/serve_check.py create mode 100644 zig/tests/qwen35/serve_conc.py create mode 100644 zig/tests/qwen35/serve_prefill.py create mode 100644 zig/tests/qwen35/serve_prefix.py create mode 100644 zig/tests/qwen35/serve_tp.sh create mode 100644 zig/tests/qwen35/truth_score.zig diff --git a/build.zig b/build.zig index 1ee381f11ca..18ebe4a581e 100644 --- a/build.zig +++ b/build.zig @@ -160,7 +160,7 @@ pub fn build(b: *std.Build) void { const api_mod = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes_mod }} }); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api_mod })).step); } - hip_build.steps(b, target, test_step); + hip_build.steps(b, target, optimize, build_options, test_step); exlr8_build.hostTests(b, target, test_step); const lanes_cpu = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); const disk_cpu = b.addTest(.{ .root_module = b.createModule(.{ diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 76f608f269d..1eb0e8c4e62 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -4,7 +4,7 @@ const std = @import("std"); const caps = @import("../src/hip/caps.zig"); /// hip-host-test (part of `test`), hip-gpu-build and hip-gpu-test, hip-affine-build and hip-affine-test. -pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, build_options: *std.Build.Step.Options, test_step: *std.Build.Step) void { const hip_fixtures = b.addOptions(); for ([_][]const u8{ "success", "failed", "missing" }) |kind| { const fixture_module = b.createModule(.{ .target = b.graph.host, .link_libc = true }); @@ -84,6 +84,78 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu 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); + const stub_kernels = b.createModule(.{ .root_source_file = b.addWriteFiles().add("kernels.zig", stub) }); + const host = engineModules(b, b.graph.host, .Debug, stub_kernels, null); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.hip })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.family })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native })).step); + // the GPU programs compile on any host against stub kernels, so `test` catches what only they reach + test_step.dependOn(&checksExe(b, b.graph.host, .Debug, host).step); + test_step.dependOn(&server(b, b.graph.host, host, build_options).step); + const gpu = engineModules(b, target, optimize, objects, hip_include); + b.step("tf-qwen35-test", "Qwen3.5 / 3.6 model checks on the GPU (-Dhip-arch)").dependOn(&b.addInstallArtifact(checksExe(b, target, optimize, gpu), .{}).step); + const native = server(b, target, gpu, build_options); + b.step("native-hip", "tensorfold-native with the HIP engines into zig-out/native-hip/bin (-Dhip-arch)").dependOn(&b.addInstallArtifact(native, .{ .dest_dir = .{ .override = .{ .custom = "native-hip/bin" } } }).step); +} + +/// `tf-qwen35-test`: the model checks on a real checkpoint and GPU. +fn checksExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, e: Engine) *std.Build.Step.Compile { + return b.addExecutable(.{ .name = "tf-qwen35-test", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/qwen35/main.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = e.hip }, .{ .name = "qwen3_5", .module = e.family }, .{ .name = "lanes", .module = e.lanes }, .{ .name = "npy", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/npy.zig"), .target = target, .optimize = optimize }) } }, + }) }); +} + +const Engine = struct { hip: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, family: *std.Build.Module, native: *std.Build.Module }; + +/// The HIP backend, the Qwen3.5 family over it and the native engines, on `kernels` (a stub on the host). +fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, kernels: *std.Build.Module, hip_include: ?[]const u8) Engine { + const core = coreModule(b, target); + const hip = b.createModule(.{ .root_source_file = b.path("zig/src/hip/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + hip.addImport("core", core); + hip.addImport("hip_kernels", kernels); + hip.addImport("cuda_memory", b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda_memory.zig"), .target = target, .optimize = optimize })); + if (hip_include) |dir| { + hip.addIncludePath(.{ .cwd_relative = dir }); + hip.addCSourceFile(.{ .file = b.path("zig/src/hip/device_arch.c"), .flags = &.{"-D__HIP_PLATFORM_AMD__"} }); + } + const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const family = b.createModule(.{ + .root_source_file = b.path("zig/src/families/qwen3_5/hip.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "core", .module = core }, .{ .name = "lanes", .module = lanes }, .{ .name = "engine_api", .module = api } }, + }); + const native = b.createModule(.{ + .root_source_file = b.path("zig/src/native/hip.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "qwen3_5", .module = family } }, + }); + return .{ .hip = hip, .lanes = lanes, .api = api, .family = family, .native = native }; +} + +/// The server over the HIP engines, as the CUDA build makes it: the HTTP side keeps its safety checks. +fn server(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, build_options: *std.Build.Step.Options) *std.Build.Step.Compile { + const api = e.api; + const engines = e.native; + const tokenizer = e.hip.import_table.get("core").?.import_table.get("tokenizer").?; + const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/server/main.zig"), + .target = target, + .optimize = .ReleaseSafe, + .link_libc = true, + .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{.{ .name = "native_engines", .module = engines }} }) } }, + }) }); + exe.root_module.addOptions("build_options", build_options); + return exe; } /// The model-free kernels' source groups, in zig/src/hip/kernels.zig's Group order. diff --git a/zig/src/families/qwen3_5/backend/hip/engine/draw.zig b/zig/src/families/qwen3_5/backend/hip/engine/draw.zig new file mode 100644 index 00000000000..f9296b76194 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/draw.zig @@ -0,0 +1,127 @@ +//! Tokens from logits rows on the device: argmax per greedy row, top_k + MARGIN candidates per sampled row. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const sample = @import("sample.zig"); + +/// Most candidates a row downloads; wider requests (top_k 0, or past this) download the row and draw on the host. +pub const max_candidates = 512; + +/// One row's draw: its sampling (null is greedy) and the position that keys it. +pub const Request = struct { sampling: ?lanes.Sampling, position: u64 }; + +fn greedy(s: ?lanes.Sampling) bool { + return if (s) |x| x.temperature <= 0.0 else true; +} + +/// Candidates a sampled row asks for, or 0 when it takes the whole row. +fn candidates(s: lanes.Sampling, vocab: usize) usize { + if (s.top_k == 0) return 0; + const n = @min(vocab, @as(usize, s.top_k) + sample.MARGIN); + return if (n > max_candidates) 0 else n; +} + +fn view(comptime T: type, bytes: []u8) []T { + return std.mem.bytesAsSlice(T, @as([]align(@alignOf(T)) u8, @alignCast(bytes))); +} + +pub const Drawer = struct { + gpa: std.mem.Allocator, + d: *const hip.Runtime, + dtype: sample.Dtype, + vocab: usize, + rows: usize, + /// Per row: the candidate count, the argmax, then (rows, stride) candidate ids and value patterns. + host: hip.HostBuffer, + dev: hip.DeviceBuffer, + row: hip.HostBuffer, + + /// Device bytes a drawer of `rows` rows holds: each row's argmax and its sampling candidates. + pub fn deviceBytes(rows: usize) usize { + return rows * (8 + max_candidates * 6); + } + + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, dtype: sample.Dtype, vocab: usize, rows: usize) !Drawer { + const bytes = deviceBytes(rows); + var host = try hip.HostBuffer.alloc(d, bytes); + errdefer host.free(); + var dev = try hip.DeviceBuffer.alloc(d, bytes); + errdefer dev.free(); + return .{ .gpa = gpa, .d = d, .dtype = dtype, .vocab = vocab, .rows = rows, .host = host, .dev = dev, .row = try hip.HostBuffer.alloc(d, vocab * 2) }; + } + + pub fn deinit(w: *Drawer) void { + w.row.free(); + w.dev.free(); + w.host.free(); + } + + /// Row r's offsets into the scratch of `stride` candidates a row, as byte counts: ks, argmax, ids, values. + fn layout(w: *const Drawer, stride: usize) struct { arg: usize, ids: usize, vals: usize, total: usize } { + const arg = w.rows * 4; + const ids = arg + w.rows * 4; + const vals = ids + w.rows * stride * 4; + return .{ .arg = arg, .ids = ids, .vals = vals, .total = vals + w.rows * stride * 2 }; + } + + /// Where the argmax of a logits block's first rows goes on the device (a graph can hold the launch). + pub fn argmaxAt(w: *const Drawer) u64 { + return w.dev.base() + w.layout(0).arg; + } + + /// `out[r]` the token of row r of `logits` per `reqs[r]`, stream synchronized; `argmaxed`: argmax is at `argmaxAt`. + pub fn draw(w: *Drawer, o: hip.ops.Ops, stream: hip.Stream, logits: hip.ops.Tensor, reqs: []const Request, out: []u32, argmaxed: bool) !void { + const rows = reqs.len; + if (rows > w.rows) return error.WindowTooWide; + const ks = w.host.slice(i32)[0..rows]; + var stride: usize = 0; + var any_greedy = false; + for (reqs, ks) |r, *k| { + k.* = 0; + if (greedy(r.sampling)) { + any_greedy = true; + } else { + const n = candidates(r.sampling.?, w.vocab); + k.* = @intCast(n); + stride = @max(stride, n); + } + } + const at = w.layout(stride); + const base = w.dev.base(); + if (any_greedy and !argmaxed) try o.argmaxRows(logits, rows, w.vocab, base + at.arg); + if (stride > 0) { + try hip.raw.upload(w.dev, 0, std.mem.sliceAsBytes(ks), stream.handle); + try o.topkRows(logits, rows, w.vocab, base, stride, base + at.ids, base + at.vals); + } + const host = w.host.bytes; + if (any_greedy) try hip.raw.download(w.dev, at.arg, host[at.arg..][0 .. rows * 4], stream.handle); + if (stride > 0) try hip.raw.download(w.dev, at.ids, host[at.ids..at.total], stream.handle); + try stream.synchronize(); + const arg = view(i32, host[at.arg..][0 .. rows * 4]); + for (reqs, 0..) |r, i| { + if (greedy(r.sampling)) { + out[i] = @intCast(arg[i]); + continue; + } + const s = r.sampling.?; + const n: usize = @intCast(ks[i]); + if (n == 0) { + const bytes = w.vocab * 2; + try hip.runtime.check(w.d.api.hipMemcpyDtoHAsync(w.row.bytes.ptr, @ptrFromInt(logits.ptr + i * bytes), bytes, stream.handle)); + try stream.synchronize(); + out[i] = try sample.draw(w.gpa, w.row.slice(u16)[0..w.vocab], w.dtype, s, r.position); + continue; + } + const ids = view(i32, host[at.ids + i * stride * 4 ..][0 .. n * 4]); + const vals = view(u16, host[at.vals + i * stride * 2 ..][0 .. n * 2]); + var values: [max_candidates]f64 = undefined; + var wide: [max_candidates]u64 = undefined; + for (0..n) |j| { + values[j] = sample.widen(vals, w.dtype, j); + wide[j] = @intCast(ids[j]); + } + out[i] = @intCast(try lanes.sampling.choose(w.gpa, values[0..n], wide[0..n], r.position, s)); + } + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig new file mode 100644 index 00000000000..63874f637ac --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -0,0 +1,415 @@ +//! One loaded model on one HIP device: the kernel library, a stream, scratch and the pinned buffers rounds go through. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const state = @import("../forward/state.zig"); +const pages = @import("../forward/pages.zig"); +const fwd = @import("../forward/forward.zig"); +const weights = @import("../model/weights.zig"); +const bridge = @import("../model/bridge.zig"); +const sample = @import("sample.zig"); +const memory = @import("memory.zig"); +const draw = @import("draw.zig"); +const slicing = @import("../../../weights/slicing.zig"); +const reduce = @import("../forward/reduce.zig"); +const round_graphs = @import("round_graphs.zig"); +const lane_round = @import("round.zig"); +const scratch = @import("scratch.zig"); +const mtp = @import("mtp.zig"); +const admission = hip.admission; +const prefix = @import("prefix.zig"); +const plan = @import("../forward/plan.zig"); + +pub const Options = struct { + /// Most positions a stream's caches hold (its prompt, its reply and a window's rows). + capacity: usize = 0, + /// Pages of the KV pool (0: enough for `default_streams` streams of the capacity and the scratch caches). + pool_pages: usize = 0, + /// Rows a shared forward holds at most. + batch_rows: usize = 32, + /// Filled before the weights load: the pool, the bytes held and the checkpoint's share (refused when too big). + preflight: ?*Preflight = null, + /// Streams the memory plan holds at once (the lanes, or what a check runs together), and linear snapshots beside. + streams: usize = default_streams, + snapshots: usize = 0, + /// Rows one prompt pass takes at most (a longer one is refused): the server's chunk, a check's longest prompt. + prompt_rows: usize = prefix.chunk, + /// The device ordinal among the visible ones. + device: c_int = 0, + /// Positions past a reply a verify writes (the window's rows and one more). + slack: usize = 0, + /// Tensor parallelism: this rank of `world`, `id` being the communicator's unique id, the same on every rank. + rank: usize = 0, + world: usize = 1, + id: ?hip.rccl.UniqueId = null, + /// Replay rounds from captured graphs (the policy's `graphs` turns it off). + graphs: bool = true, + /// What the run may use, resolved once by whoever opens the engine. + policy: hip.Policy = .{}, +}; + +pub const Pick = lane_round.Pick; + +/// Streams the pool of an engine opened without a memory plan holds whole. +pub const default_streams = 12; + +fn gib(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// What `load` found before reading the weights. +pub const Preflight = struct { pool: admission.Pool = undefined, held: u64 = 0, weights: u64 = 0 }; + +pub const Engine = struct { + pub const Rows = lane_round.Rows; + + gpa: std.mem.Allocator, + driver: hip.Runtime, + ctx: hip.Context, + lib: hip.Launcher, + stream: hip.Stream, + weights: weights.Model, + bridge: *bridge.Bridge, + o: Options, + /// The scratch below exists (`size` ran). + sized: bool, + act: view.Kind, + dtype: sample.Dtype, + /// A window's scratch, kept from its verify to its keep (the commit reads the per-row states). + rounds: hip.Arena, + /// A prompt's scratch: its rows, the step's temporaries. + prompts: hip.Arena, + ids: hip.HostBuffer, + ids_dev: hip.DeviceBuffer, + /// The keys and values of every stream and prefix entry. + pool: pages.Pool, + drawer: draw.Drawer, + /// Tensor parallelism: RCCL and this rank's communicator. + rccl: hip.rccl.Rccl = undefined, + comm: hip.rccl.Comm = undefined, + graphs: round_graphs.Graphs, + /// The draft head's batches replay graphs (the head holds no collective, so under tp too unless graphs=off). + head_graphs: bool = true, + /// The lane rounds' plan, graph choice and keep. + round: lane_round.State = undefined, + + /// The model on the device, its scratch not yet sized: `size` takes the capacity the memory plan fits. + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !*Engine { + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.gpa = gpa; + e.o = o; + e.sized = false; + // rounds replay graphs as the policy says; under tensor parallelism only when it is `graphs=on` + e.o.graphs = o.graphs and o.policy.graphsOn(o.world); + e.head_graphs = o.graphs and o.policy.graphsOn(1); + e.graphs = round_graphs.Graphs.init(gpa); + e.driver = try hip.Runtime.open(); + errdefer e.driver.close(); + e.ctx = try hip.Context.init(&e.driver, o.device); + errdefer e.ctx.deinit(); + const caps = try hip.Device.kernelCaps(&e.driver, o.device); + e.lib = try hip.Launcher.load(&e.driver, o.policy.choices(), hip.kernels.images); + errdefer e.lib.unload(); + e.act = if (caps.act == .f16) .f16 else .bf16; + e.dtype = if (caps.act == .f16) .f16 else .bf16; + e.stream = try hip.Stream.init(&e.driver); + errdefer e.stream.deinit(); + const group: ?slicing.Rank = if (o.world > 1) .{ .rank = o.rank, .world = o.world } else null; + if (group != null) { + e.rccl = try hip.rccl.Rccl.open(o.policy.rccl_lib.slice()); + errdefer e.rccl.close(); + e.comm = try hip.rccl.Comm.init(&e.rccl, o.id orelse return error.NoUniqueId, o.rank, o.world); + } + errdefer if (group != null) { + e.comm.deinit(); + e.rccl.close(); + }; + if (o.preflight) |pf| { + // a rank loads its share of the checkpoint, near enough to refuse before reading it + pf.* = .{ .pool = try e.budget(io), .held = hip.usage(false).device, .weights = admission.weightBytes(io, dir) / o.world }; + if (pf.weights > pf.pool.room(pf.held)) return error.WeightsDoNotFit; + } + e.weights = try weights.Model.loadRank(gpa, io, &e.driver, dir, group); + errdefer e.weights.deinit(); + e.bridge = try bridge.Bridge.init(gpa, &e.driver, &e.weights, e.act); + errdefer e.bridge.deinit(); + if (group != null) e.bridge.model.tp = e.comm; + return e; + } + + /// Allocate the scratch for streams of `capacity` positions and a pool of `pool_pages` pages (zero: the default). + pub fn size(e: *Engine, capacity: usize, pool_pages: usize) !void { + const rows = e.o.batch_rows; + const prompt_rows = @min(e.o.prompt_rows, capacity); + const count = if (pool_pages > 0) pool_pages else default_streams * pages.pagesFor(capacity) + pages.pagesFor(rows); + const arenas = try e.arenaBytes(rows, prompt_rows, capacity); + e.o.capacity = capacity; + e.o.prompt_rows = prompt_rows; + const before = hip.usage(false).device; + e.rounds = try hip.Arena.init(&e.driver, arenas[0]); + errdefer e.rounds.deinit(); + e.prompts = try hip.Arena.init(&e.driver, arenas[1]); + errdefer e.prompts.deinit(); + e.ids = try hip.HostBuffer.alloc(&e.driver, prompt_rows * 4); + errdefer e.ids.free(); + e.ids_dev = try hip.DeviceBuffer.alloc(&e.driver, prompt_rows * 4); + errdefer e.ids_dev.free(); + e.drawer = try draw.Drawer.init(e.gpa, &e.driver, e.dtype, e.bridge.model.head.n * e.o.world, rows); + errdefer e.drawer.deinit(); + e.pool = try pages.Pool.init(e.gpa, &e.driver, &e.bridge.model, count, e.o.rank == 0); + errdefer e.pool.deinit(); + e.round = try lane_round.State.init(e); + errdefer e.round.deinit(e); + const held = hip.usage(false).device - before; + const planned = e.sizedBytes(arenas, rows, prompt_rows, count); + if (held != planned) { + std.log.err("sizing held {d} device bytes, the plan says {d}", .{ held, planned }); + return error.SizeMismatch; + } + e.sized = true; + } + + /// The rounds and prompts arenas: the forwards counted at their largest shapes for `rows` and `prompt_rows`. + fn arenaBytes(e: *Engine, rows: usize, prompt_rows: usize, capacity: usize) ![2]usize { + return .{ try scratch.rounds(e, rows, capacity), try scratch.prompts(e, @min(prompt_rows, capacity), capacity) }; + } + + /// Device bytes `size` allocates beside the weights, with the arenas already counted. + fn sizedBytes(e: *const Engine, arenas: [2]usize, rows: usize, prompt_rows: usize, pool_pages: usize) usize { + const m = e.model(); + return arenas[0] + arenas[1] + prompt_rows * 4 + draw.Drawer.deviceBytes(rows) + pages.Pool.deviceBytes(m, pool_pages) + + plan.Buffer.deviceBytes(rows, m.spec.n_layers) + state.Caches.deviceBytes(m, rows); + } + + /// Device bytes `size(capacity, pool_pages)` would allocate with `rows` rows a forward: what admission weighs. + pub fn sizeBytes(e: *Engine, rows: usize, capacity: usize, pool_pages: usize) !usize { + const prompt_rows = @min(e.o.prompt_rows, capacity); + return e.sizedBytes(try e.arenaBytes(rows, prompt_rows, capacity), rows, prompt_rows, pool_pages); + } + + /// The least of each value over the ranks, the same on every rank (a window and a prompt cache they all fit). + pub fn least(e: *Engine, mine: [2]u64) ![2]u64 { + if (e.o.world < 2) return mine; + const world = e.o.world; + var host = try hip.HostBuffer.alloc(&e.driver, 16 * (1 + world)); + defer host.free(); + var send = try hip.DeviceBuffer.alloc(&e.driver, 16); + defer send.free(); + var recv = try hip.DeviceBuffer.alloc(&e.driver, 16 * world); + defer recv.free(); + host.slice(u64)[0..2].* = mine; + try send.uploadAsync(0, host.view(0, 16), e.stream); + try e.comm.allGather(send.base(), recv.base(), 2, .i64, e.stream.handle); + try recv.downloadAsync(0, host.view(16, 16 * (1 + world)), e.stream); + try e.stream.synchronize(); + var out = mine; + for (host.slice(u64)[2 .. 2 * (1 + world)], 0..) |v, i| out[i % 2] = @min(out[i % 2], v); + return out; + } + + /// Device bytes beside the weights: `size`'s scratch and pool, `streams` lanes, `snapshots`, rank 0's head. + pub fn planBytes(e: *Engine, streams: usize, rows: usize, capacity: usize, pool_pages: usize, snapshots: usize) !usize { + const m = e.model(); + const lane = state.Caches.deviceBytes(m, capacity) + m.spec.hidden * m.act.size(); + // under tensor parallelism only rank 0 holds the head + const head = if (e.o.rank > 0) 0 else try mtp.Head.deviceBytes(e.gpa, &e.driver, &e.lib, &e.weights, m, @min(rows, mtp.max_chains)); + return try e.sizeBytes(rows, capacity, pool_pages) + streams * lane + snapshots * memory.linearBytes(m.spec) + head; + } + + /// The memory a plan may take, as the native backends count it: free (host's when integrated), reserve and cap. + pub fn budget(e: *const Engine, io: std.Io) !admission.Pool { + const unified = (try e.ctx.attribute(.integrated)) != 0; + const card = try e.ctx.memInfo(); + const text = if (unified) admission.procText(e.gpa, io, "/proc/meminfo") else null; + defer if (text) |t| e.gpa.free(t); + const counts = admission.counts(unified, .{ .total = card.total, .available = card.free }, text) catch return error.HostMemoryUnavailable; + const reserve = admission.reserveBytes(getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), counts.total, unified) catch return error.BadReserve; + const limit = admission.limitBytes(getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB")) catch return error.BadLimit; + return .{ .free = counts.available, .total = counts.total, .reserve = reserve, .limit = limit, .unified = unified }; + } + + /// Load and size in one: `o.capacity` positions, refused when the plan does not fit the memory. + pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !*Engine { + const held = hip.usage(false).device; + const e = try load(gpa, io, dir, o); + errdefer e.deinit(); + const weights_bytes = hip.usage(false).device - held; + const pool_pages = if (o.pool_pages > 0) o.pool_pages else default_streams * pages.pagesFor(o.capacity) + pages.pagesFor(o.batch_rows); + const need = try e.planBytes(o.streams, o.batch_rows, o.capacity, pool_pages, o.snapshots); + const p = try e.budget(io); + if (need > p.room(weights_bytes)) { + std.log.err("{d} streams at {d} positions with {d} rows a round need {d:.2} GiB beside the model's {d:.2} GiB, and {d:.2} GiB is left after the {d:.1} GiB reserve", .{ o.streams, o.capacity, o.batch_rows, gib(need), gib(weights_bytes), gib(p.room(weights_bytes)), gib(p.reserve) }); + return error.OutOfDeviceMemory; + } + try e.size(o.capacity, pool_pages); + return e; + } + + pub fn deinit(e: *Engine) void { + e.stream.synchronize() catch {}; + if (e.graphs.captured > 0) std.log.info("graphs: {d} captured ({d:.0} ms each), {d} of {d} rounds replayed", .{ e.graphs.captured, @as(f64, @floatFromInt(e.graphs.capture_ns)) / @as(f64, @floatFromInt(e.graphs.captured)) / 1e6, e.graphs.replayed, e.graphs.rounds }); + e.graphs.deinit(); + if (e.sized) { + e.round.deinit(e); + e.drawer.deinit(); + e.ids_dev.free(); + e.ids.free(); + e.prompts.deinit(); + e.rounds.deinit(); + e.pool.deinit(); + } + e.bridge.deinit(); + e.weights.deinit(); + e.stream.deinit(); + e.lib.unload(); + if (e.o.world > 1) { + e.comm.deinit(); + e.rccl.close(); + } + e.ctx.deinit(); + e.driver.close(); + e.gpa.destroy(e); + } + + pub fn model(e: *const Engine) *const view.Model { + return &e.bridge.model; + } + + pub fn ops(e: *Engine, arena: *hip.Arena) hip.ops.Ops { + return .{ .l = &e.lib, .bf16 = e.act == .bf16, .stream = e.stream.handle, .arena = arena }; + } + + /// Caches for `total` positions (at most the capacity) with every page taken. + pub fn newCaches(e: *Engine, total: usize) !state.Caches { + return state.Caches.initFull(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity)); + } + + /// Caches for `total` positions (at most the capacity) with no page yet: a stream takes them as it grows. + pub fn emptyCaches(e: *Engine, total: usize) !state.Caches { + return state.Caches.init(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity)); + } + + /// Whether the draft head's greedy batches replay graphs. + pub fn headGraphs(e: *const Engine) bool { + return if (e.o.world > 1) e.head_graphs else e.o.graphs; + } + + /// Waits for the stream, before caches are freed (a round may still be running on them). + pub fn drain(e: *Engine) void { + e.stream.synchronize() catch {}; + } + + /// The tokens of `rows` final rows at `hidden`: one projection, vocabulary slices joined in rank order. + fn project(e: *Engine, o: hip.ops.Ops, hidden: hip.ops.Tensor, rows: usize, reqs: []const draw.Request, out: []u32) !void { + const y = try o.project(hidden, e.model().head, rows, false); + try e.drawRows(o, y, rows, reqs, out, false); + } + + /// Each of `rows` logits rows drawn per `reqs`, whole rows joined first across ranks; `argmaxed`: greedy rows done. + pub fn drawRows(e: *Engine, o: hip.ops.Ops, y: hip.ops.Tensor, rows: usize, reqs: []const draw.Request, out: []u32, argmaxed: bool) !void { + try e.drawer.draw(o, e.stream, try e.wholeRows(o, y, rows), reqs[0..rows], out, argmaxed); + } + + /// `rows` logits rows whole: this rank's when it holds the whole head, else every rank's slices joined. + pub fn wholeRows(e: *Engine, o: hip.ops.Ops, y: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { + return if (e.model().tp) |c| e.joined(o, c, y, rows) else y; + } + + /// vocab_gather: every rank's slice of `rows` logits rows, joined on the device into whole rows in rank order. + fn joined(e: *Engine, o: hip.ops.Ops, c: hip.rccl.Comm, slice: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { + const width = e.model().head.n; + const n = rows * width; + const size_of = slice.kind.size(); + const parts = try o.arena.take(c.world * n * size_of); + try reduce.gather(o, c, slice, parts, n); + const whole = try o.arena.take(c.world * n * size_of); + for (0..rows) |row| for (0..c.world) |r| { + const to = whole + (row * c.world + r) * width * size_of; + const from = parts + (r * rows + row) * width * size_of; + if (o.stream != hip.counting) try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync(@ptrFromInt(to), @ptrFromInt(from), width * size_of, o.stream)); + }; + return .{ .ptr = whole, .kind = slice.kind }; + } + + /// Asked after each layer of a long prompt (the stream is idle then): true ends the pass with `error.Cancelled`. + pub const Cancel = struct { + ctx: *anyopaque, + check: *const fn (ctx: *anyopaque) bool, + }; + + const Poll = struct { + stream: hip.Stream, + cancel: Cancel, + + fn layer(ctx: *anyopaque, _: usize, _: hip.ops.Tensor, _: usize) anyerror!void { + const p: *Poll = @ptrCast(@alignCast(ctx)); + try p.stream.synchronize(); + if (p.cancel.check(p.cancel.ctx)) return error.Cancelled; + } + }; + + /// The pass over `len` rows polling the cancel after each layer; null where it cannot stop (a short prompt, or tp). + fn poll(e: *Engine, cancel: ?Cancel, len: usize, p: *Poll) ?fwd.Trace { + const c = cancel orelse return null; + if (e.o.world > 1 or len < fwd.SPAN) return null; + p.* = .{ .stream = e.stream, .cancel = c }; + return .{ .ctx = p, .layer = Poll.layer }; + } + + /// Run `prompt[pos0..end]` into `caches`, its logits not read: a cut where the caches are kept. + pub fn advance(e: *Engine, caches: *state.Caches, prompt: []const u32, pos0: usize, end: usize, cancel: ?Cancel) !void { + if (end <= pos0 or end > caches.total or end - pos0 > e.o.prompt_rows) return error.PromptTooLong; + e.prompts.reset(); + const ids = e.ids.slice(u32)[0 .. end - pos0]; + @memcpy(ids, prompt[pos0..end]); + try e.ids_dev.uploadAsync(0, e.ids.view(0, 4 * ids.len), e.stream); + var p: Poll = undefined; + _ = try fwd.span(e.ops(&e.prompts), e.model(), caches, e.ids_dev.base(), end - pos0, pos0, e.poll(cancel, end - pos0, &p)); + try e.stream.synchronize(); + } + + /// Prefill `prompt[pos0..]` into `caches`; the last row's token, its final row copied to `last` (MTP's input). + pub fn prefill(e: *Engine, caches: *state.Caches, prompt: []const u32, pos0: usize, last: ?hip.DeviceBuffer, req: draw.Request, cancel: ?Cancel) !u32 { + const m = e.model(); + const len = prompt.len - pos0; + if (len == 0 or prompt.len > caches.total or len > e.o.prompt_rows) return error.PromptTooLong; + e.prompts.reset(); + const ids = e.ids.slice(u32)[0..len]; + @memcpy(ids, prompt[pos0..]); + try e.ids_dev.uploadAsync(0, e.ids.view(0, 4 * ids.len), e.stream); + const o = e.ops(&e.prompts); + var p: Poll = undefined; + const hidden = try fwd.span(o, m, caches, e.ids_dev.base(), len, pos0, e.poll(cancel, len, &p)); + const row = fwd.at(hidden, (len - 1) * m.spec.hidden); + if (last) |b| try hip.raw.copy(b, 0, row.ptr, m.spec.hidden * m.act.size(), e.stream.handle); + var token: [1]u32 = undefined; + try e.project(o, row, 1, &.{req}, &token); + return token[0]; + } + + /// Every window in one forward: `out` the token of every row; the round's snapshots live until its keeps flush. + pub fn verify(e: *Engine, rows: []const Rows, reqs: []const draw.Request, out: []u32) !lane_round.Verified { + return lane_round.verify(e, rows, reqs, out); + } + + /// The round's graph choice: from the shape's history, or `forced` (rank 0's pick, which a follower obeys). + pub fn choose(e: *Engine, rows: []const Rows, forced: ?Pick) !Pick { + return lane_round.choose(e, rows, forced); + } + + /// Marks a slot of the last verify to keep its first `rows` rows at the next `flush`. + pub fn keep(e: *Engine, slot: usize, rows: usize) void { + lane_round.mark(e, slot, rows); + } + + /// Keeps every marked slot in one launch. + pub fn flush(e: *Engine) !void { + try lane_round.flush(e); + } +}; + +fn getenv(name: [:0]const u8) ?[]const u8 { + return std.mem.span(std.c.getenv(name) orelse return null); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig b/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig new file mode 100644 index 00000000000..9d46c078663 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig @@ -0,0 +1,98 @@ +//! Captured graphs by shape: a launch sequence recorded the second time its shape is met, replayed on every later one. + +const std = @import("std"); +const hip = @import("hip"); + +/// Shapes kept at once; the least recently used one is dropped for a new one. +const max_entries = 64; + +pub const State = enum { seen, ready, failed }; + +/// A cache of graphs keyed by `Key` (plain integers and booleans), each with the `Out` its capture produced. +pub fn Cache(comptime Key: type, comptime Out: type) type { + return struct { + const Self = @This(); + + pub const Entry = struct { + key: Key, + state: State = .seen, + exec: ?hip.graph.Exec = null, + out: Out = undefined, + tick: u64 = 0, + }; + + gpa: std.mem.Allocator, + entries: std.ArrayList(Entry) = .empty, + clock: u64 = 0, + /// Launches run, replayed and captured; the host's nanoseconds from a launch's start to its work queued. + rounds: u64 = 0, + submit_ns: u64 = 0, + /// The host's nanoseconds recording and instantiating graphs. + capture_ns: u64 = 0, + replayed: u64 = 0, + captured: u64 = 0, + + pub fn init(gpa: std.mem.Allocator) Self { + return .{ .gpa = gpa }; + } + + pub fn deinit(g: *Self) void { + for (g.entries.items) |*e| if (e.exec) |*x| x.deinit(); + g.entries.deinit(g.gpa); + } + + /// The entry for `key`, made (state `seen`) if new. + pub fn find(g: *Self, key: Key) !*Entry { + g.clock += 1; + for (g.entries.items) |*e| if (std.meta.eql(e.key, key)) { + e.tick = g.clock; + return e; + }; + if (g.entries.items.len >= max_entries) { + var oldest: usize = 0; + for (g.entries.items, 0..) |e, i| if (e.tick < g.entries.items[oldest].tick) { + oldest = i; + }; + if (g.entries.items[oldest].exec) |*x| x.deinit(); + _ = g.entries.swapRemove(oldest); + } + try g.entries.append(g.gpa, .{ .key = key, .tick = g.clock }); + return &g.entries.items[g.entries.items.len - 1]; + } + + /// Drops a shape's graph (a rank could not capture it): the shape runs eagerly from now on. + pub fn revoke(g: *Self, e: *Entry) void { + if (e.exec) |*x| x.deinit(); + e.exec = null; + e.state = .failed; + if (g.captured > 0) g.captured -= 1; + } + + /// `body(ctx)` recorded on `stream`: its outputs and the graph (nothing ran), or null when the capture failed. + pub fn record(stream: hip.Stream, ctx: anytype, comptime body: fn (@TypeOf(ctx)) anyerror!Out) !?struct { out: Out, graph: hip.graph.Graph } { + hip.graph.beginCapture(stream, .thread_local) catch return null; + const recorded = body(ctx); + const graph = hip.graph.endCapture(stream) catch return null; + const out = recorded catch |err| { + var g = graph; + g.deinit(); + return if (err == error.OutOfDeviceMemory) err else null; + }; + return .{ .out = out, .graph = graph }; + } + + /// Instantiates a capture that just ended, keeps it with its outputs, and uploads it. + pub fn keep(g: *Self, e: *Entry, graph: hip.graph.Graph, stream: hip.Stream, out: Out) !void { + var tmp = graph; + defer tmp.deinit(); + errdefer e.state = .failed; + var exec = try tmp.instantiate(); + errdefer exec.deinit(); + try exec.upload(stream); + e.exec = exec; + e.out = out; + e.state = .ready; + g.captured += 1; + } + }; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig new file mode 100644 index 00000000000..c40170a2694 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig @@ -0,0 +1,115 @@ +//! The HIP lanes backend's own costs, timed at load on scratch streams: what the depth rule weighs drafts against. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const Engine = @import("engine.zig").Engine; +const state = @import("../forward/state.zig"); +const draw = @import("draw.zig"); +const mtp = @import("mtp.zig"); + +const Cost = lanes.config.Cost; + +/// Forwards run before the timed ones (the first captures the shape's graph) and the timed reps. +const warm = 3; +const reps = 5; +/// Rows a stream's window holds in the shared timings, and its position (the caches are scratch). +const window = 4; +const at = 16; +/// The total rows timed in shared forwards. +pub const shared_rows = [_]u32{ 2, 4, 8, 12, 16 }; +pub const most_streams = 8; + +pub const Costs = struct { + window: [16]Cost = undefined, + windows: usize = 0, + shared: [shared_rows.len]Cost = undefined, + shareds: usize = 0, + step_ms: f64 = 0.0, +}; + +pub fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +const Rig = struct { + gpa: std.mem.Allocator, + e: *Engine, + caches: [most_streams]state.Caches = undefined, + made: usize = 0, + tokens: [64]u32 = @splat(1), + reqs: [64]draw.Request = undefined, + out: [64]u32 = undefined, + + fn deinit(r: *Rig) void { + r.e.drain(); + for (r.caches[0..r.made]) |*c| c.deinit(r.gpa); + } + + /// Mean ms of a verify of `streams` windows of the given widths. + fn time(r: *Rig, widths: []const usize) !f64 { + var rows: [most_streams]Engine.Rows = undefined; + var total: usize = 0; + for (widths, 0..) |w, i| { + rows[i] = .{ .caches = &r.caches[i], .pos = at, .tokens = r.tokens[total..][0..w] }; + for (0..w) |j| r.reqs[total + j] = .{ .sampling = null, .position = at + j + 1 }; + total += w; + } + var spent: u64 = 0; + for (0..warm + reps) |i| { + const t0 = nowNs(); + _ = try r.e.verify(rows[0..widths.len], r.reqs[0..total], &r.out); + if (i >= warm) spent += nowNs() - t0; + } + return @as(f64, @floatFromInt(spent)) / reps / 1e6; + } +}; + +/// Time `h`'s forwards and head on scratch caches of its engine (nothing of a stream is touched). +pub fn measure(gpa: std.mem.Allocator, e: *Engine, head: ?*mtp.Head, out: *Costs) !void { + var r: Rig = .{ .gpa = gpa, .e = e }; + defer r.deinit(); + // the rig runs before any request, on the caches of streams the memory plan holds and none uses yet + const streams = @min(most_streams, e.o.streams); + while (r.made < streams) : (r.made += 1) r.caches[r.made] = try e.newCaches(at + 2 * window * 4); + out.windows = 0; + for (1..out.window.len + 1) |w| { + if (w > e.o.batch_rows) break; + out.window[out.windows] = .{ .width = @intCast(w), .ms = try r.time(&.{w}) }; + out.windows += 1; + } + out.shareds = 0; + for (shared_rows) |total| { + if (total > e.o.batch_rows) break; + var widths: [most_streams]usize = undefined; + var n: usize = 0; + var left: usize = total; + while (left > 0 and n < streams) : (n += 1) { + widths[n] = @min(window, left); + left -= widths[n]; + } + if (left > 0) continue; + out.shared[out.shareds] = .{ .width = total, .ms = try r.time(widths[0..n]) }; + out.shareds += 1; + } + if (head) |hd| out.step_ms = try step(e, hd); +} + +/// One chained head step: a lone chain of the deepest depth, over a scratch row. +fn step(e: *Engine, hd: *mtp.Head) !f64 { + const m = e.model(); + var row = try hip.DeviceBuffer.alloc(&e.driver, m.spec.hidden * m.act.size()); + defer row.free(); + try row.fill8(0); + var held: [mtp.max_depth]u32 = undefined; + var spent: u64 = 0; + for (0..warm + reps) |i| { + var jobs = [_]mtp.Job{.{ .hidden = row.base(), .token = 1, .position = at, .depth = mtp.max_depth, .sampling = null, .stop_under = 0.0, .out = &held }}; + const t0 = nowNs(); + try hd.chains(&e.lib, e.stream, &e.drawer, m, &jobs, e.headGraphs()); + if (i >= warm) spent += nowNs() - t0; + } + return @as(f64, @floatFromInt(spent)) / reps / 1e6 / mtp.max_depth; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig new file mode 100644 index 00000000000..b4741382e19 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -0,0 +1,513 @@ +//! The lane core's HIP backend: every stream its own caches, every round's windows verified in one forward. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const Engine = @import("engine.zig").Engine; +const state = @import("../forward/state.zig"); +const draw = @import("draw.zig"); +const mtp = @import("mtp.zig"); +const costs = @import("hip_costs.zig"); +const prefix = @import("prefix.zig"); +const hip_prefix = @import("hip_prefix.zig"); +const radix = @import("engine_api").prompt_radix; +const pages = @import("../forward/pages.zig"); +const worker = @import("worker.zig"); + +const be = lanes.backend; + +/// Drawn tokens a handle names, newest last. +const ring = 1024; + +/// Where a prompt pass stands: the row it has reached, and the cuts it still keeps a state at. +const Fill = struct { at: usize, stops: [16]u32, count: usize, next: usize }; + +/// Most chains one draft request runs (the head batches as many as the engine has rows, up to this). +const max_jobs = mtp.max_chains; + +pub const Lane = struct { + caches: state.Caches, + /// The last kept row's final hidden row: the draft head's input. + hidden: hip.DeviceBuffer, + /// Drafts the head holds for the next window. + held: [mtp.max_depth]u32 = undefined, + held_n: usize = 0, + /// Slots written and kept: the next window starts here. + len: usize, + /// The stream's id on every rank. + id: u32 = 0, + /// The prompt pass in progress, a chunk a call (null once it is in). + fill: ?Fill = null, + /// The last verify's slot and rows: kept whole unless keep drops some first. + pending: ?struct { window: usize, rows: usize } = null, +}; + +/// The engine this thread's HIP calls go to. +threadlocal var bound: ?*Engine = null; + +pub const Hip = struct { + gpa: std.mem.Allocator, + e: *Engine, + lanes: std.AutoHashMapUnmanaged(*const lanes.Stream, *Lane) = .empty, + head: ?*mtp.Head = null, + drawn: [ring]u32 = undefined, + next: u64 = 0, + /// The streams (and rows) marked kept since the last flush, as the other ranks are told. + marked: std.ArrayList([2]u32) = .empty, + order: []*const lanes.Stream, + /// The pages and linear snapshots kept from prompts for later turns (nothing until `keepPrompts`). + prefix: *hip_prefix.Prefix, + /// Scratch: the pages a match took, and the pages a round copied before writing. + matched: std.ArrayList(u32) = .empty, + copied: std.ArrayList([3]u32) = .empty, + /// Tensor parallelism: the other ranks, which get every step before this rank runs it (`worker.follow`). + link: ?*const hip.link.Link = null, + msg: std.ArrayList(u32) = .empty, + /// This engine's forward and head timings, filled by `measure` (none: the rule drafts the deepest it may). + costs: costs.Costs = .{}, + /// Each stream's id on every rank. + ids: std.AutoHashMapUnmanaged(*const lanes.Stream, u32) = .empty, + /// Nanoseconds and calls the backend's verifies, keeps and drafts took; the core's own work is the rest. + spent: [3]u64 = @splat(0), + calls: [3]u64 = @splat(0), + next_id: u32 = 0, + + pub fn init(gpa: std.mem.Allocator, e: *Engine) !*Hip { + const h = try gpa.create(Hip); + errdefer gpa.destroy(h); + const rows = e.o.batch_rows; + h.* = .{ .gpa = gpa, .e = e, .order = undefined, .prefix = try hip_prefix.Prefix.init(gpa, e) }; + errdefer h.prefix.deinit(); + h.order = try gpa.alloc(*const lanes.Stream, rows); + errdefer gpa.free(h.order); + // under tensor parallelism only rank 0 holds the head (whole): drafts only choose the rows every rank verifies + h.head = try mtp.Head.init(gpa, &e.driver, &e.lib, &e.weights, e.model(), @min(rows, max_jobs)); + return h; + } + + /// Time the forwards and the head on scratch caches, for the depth rule; before `facts`, on a lone rank. + pub fn measure(h: *Hip) void { + costs.measure(h.gpa, h.e, h.head, &h.costs) catch |err| { + std.log.warn("lane costs not timed: {s}", .{@errorName(err)}); + h.costs = .{}; + }; + } + + /// Keep up to `slots` snapshots and the pages the rest of `budget` bytes buys in the prefix tree (none: off). + pub fn keepPrompts(h: *Hip, slots: usize, budget: usize) void { + h.prefix.keepPrompts(slots, budget); + } + + /// The prefix tree may hold `max_pages` pages and `snaps` snapshots. + pub fn keepPages(h: *Hip, max_pages: usize, snaps: usize) void { + h.prefix.keepPages(max_pages, snaps); + } + + /// Rank 0 of a tensor-parallel group: every step also goes to the ranks behind `link`. + pub fn withLink(h: *Hip, link: *const hip.link.Link) void { + h.link = link; + h.prefix.link = link; + } + + fn send(h: *Hip, words: []const u32) !void { + if (h.link) |l| try l.send(words); + } + + /// A stream's id on every rank. + fn idOf(h: *Hip, s: *const lanes.Stream) !u32 { + const gop = try h.ids.getOrPut(h.gpa, s); + if (!gop.found_existing) { + gop.value_ptr.* = h.next_id; + h.next_id += 1; + } + return gop.value_ptr.*; + } + + fn timed(h: *Hip, which: usize, began: u64) void { + h.spent[which] += costs.nowNs() - began; + h.calls[which] += 1; + } + + pub fn deinit(h: *Hip) void { + const names = [_][]const u8{ "verify", "keep", "draft" }; + for (names, h.spent, h.calls) |name, ns, n| if (n > 0) std.log.info("backend {s}: {d} calls, {d:.0} us each", .{ name, n, @as(f64, @floatFromInt(ns)) / @as(f64, @floatFromInt(n)) / 1e3 }); + if (h.link != null) h.send(&.{@backingInt(worker.Op.stop)}) catch {}; + h.ids.deinit(h.gpa); + h.marked.deinit(h.gpa); + h.msg.deinit(h.gpa); + h.e.stream.synchronize() catch {}; + h.matched.deinit(h.gpa); + h.copied.deinit(h.gpa); + var it = h.lanes.valueIterator(); + while (it.next()) |l| h.free(l.*); + if (h.head) |hd| { + if (hd.graphs.captured > 0) std.log.info("head graphs: {d} captured, {d} of {d} batches replayed", .{ hd.graphs.captured, hd.graphs.replayed, hd.graphs.rounds }); + hd.deinit(); + } + h.lanes.deinit(h.gpa); + h.prefix.deinit(); + h.gpa.free(h.order); + h.gpa.destroy(h); + } + + pub fn backend(h: *Hip) be.Backend { + return .{ .ptr = h, .vtable = &.{ + .prefill = prefillFn, + .prefill_step = prefillStepFn, + .first = firstFn, + .queue = queueFn, + .read = readFn, + .verify = verifyFn, + .keep = keepFn, + .draft = draftFn, + .tree = heldFn, + .release = releaseFn, + } }; + } + + /// Rows a window holds: every width keeps a row's bits (the window forward), drafts come from the core. + pub const max_window = 16; + + /// The facts the round loop reads at setup: shared rounds of exact windows, and the MTP head's batched chains. + pub fn facts(h: *const Hip) lanes.Model { + const drafting = h.head != null and h.e.o.policy.mtp.drafts > 0; + // plain rounds compete with drafted ones once the forwards are timed + const plain_guard = drafting and h.costs.windows > 0; + return .{ + .exact_width = max_window, + .gpu_tokens = false, + .mtp = drafting, + .speculate = drafting, + .speculate_early = false, + .drafts = @min(mtp.max_depth, h.e.o.policy.mtp.drafts), + .hidden_rows = true, + .batch_rows = @intCast(h.e.o.batch_rows), + .max_streams = @intCast(h.e.o.batch_rows), + .draft_streams = drafting, + .plain_guard = plain_guard, + .window_costs = h.costs.window[0..h.costs.windows], + .shared_costs = h.costs.shared[0..h.costs.shareds], + .mtp_step_ms = h.costs.step_ms, + }; + } + + fn free(h: *Hip, l: *Lane) void { + h.e.drain(); + l.caches.deinit(h.gpa); + l.hidden.free(); + h.gpa.destroy(l); + } + + /// The backend behind `ptr`, the calling thread bound to its GPU (the lane thread did not open it). + fn of(ptr: *anyopaque) *Hip { + const h: *Hip = @ptrCast(@alignCast(ptr)); + if (bound != h.e) { + h.e.ctx.makeCurrent() catch |err| std.log.err("hipSetDevice on the lane thread: {s}", .{@errorName(err)}); + bound = h.e; + } + return h; + } + + fn take(h: *Hip, token: u32) u64 { + const at = h.next; + h.drawn[at % ring] = token; + h.next += 1; + return at; + } + + /// A verify the round loop did not trim keeps every row (the core keeps only on drops). + fn settle(h: *Hip, lane: *Lane) !void { + const p = lane.pending orelse return; + try h.mark(lane, p.rows); + } + + /// Marks the pending window's first `rows` rows kept (the stream's length moves on); `flush` lands them. + fn mark(h: *Hip, lane: *Lane, rows: usize) !void { + const p = lane.pending.?; + try h.marked.append(h.gpa, .{ lane.id, @intCast(rows) }); + h.e.keep(p.window, rows); + lane.len += rows; + lane.pending = null; + } + + /// Lands the marked keeps in one launch: linear states after the kept rows, the last kept final row for the head. + fn flush(h: *Hip) !void { + if (h.marked.items.len == 0) return; + if (h.link != null) { + h.msg.clearRetainingCapacity(); + try h.msg.appendSlice(h.gpa, &.{ @backingInt(worker.Op.keep), @intCast(h.marked.items.len) }); + for (h.marked.items) |k| try h.msg.appendSlice(h.gpa, &k); + try h.send(h.msg.items); + } + h.marked.clearRetainingCapacity(); + try h.e.flush(); + } + + fn sampling(s: *const lanes.Stream) ?lanes.Sampling { + return s.sampling; + } + + /// Pages for the stream's positions up to `upto`, each its own to write: the other ranks are told what changed. + fn ensure(h: *Hip, lane: *Lane, upto: usize) !void { + const before = lane.caches.table.items.len; + const grown = try lane.caches.grow(h.gpa, upto); + if (grown.len > 0) try h.prefix.sendPages(lane.id, before, grown); + h.copied.clearRetainingCapacity(); + try lane.caches.writable(&h.copied, h.gpa, lane.len, upto, h.e.stream.handle); + for (h.copied.items) |c| { + try h.send(&.{ @backingInt(worker.Op.copy), c[1], c[2] }); + try h.prefix.sendPages(lane.id, c[0], &.{c[2]}); + } + } + + /// The whole prompt pass, chunk by chunk (a driver of its own, with no rounds between). + fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + while (!try prefillStepFn(ptr, s)) {} + } + + /// The stream's lane and prompt pass begun: its pages, the resume from a snapshot, the cuts, the other ranks told. + fn begin(h: *Hip, s: *lanes.Stream) !*Lane { + const prompt = s.prompt(); + if (prompt.len == 0 or prompt.len + s.max_new + 1 > h.e.o.capacity) return error.PromptTooLong; + const gop = try h.lanes.getOrPut(h.gpa, s); + if (gop.found_existing) h.free(gop.value_ptr.*); + errdefer h.lanes.removeByPtr(gop.key_ptr); + const total = prompt.len + s.max_new + max_window + 1; + const lane = blk: { + var caches = try h.e.emptyCaches(total); + errdefer caches.deinit(h.gpa); + var hidden = try hip.DeviceBuffer.alloc(&h.e.driver, h.e.model().spec.hidden * h.e.model().act.size()); + errdefer hidden.free(); + try caches.setHidden(hidden.base()); + const l = try h.gpa.create(Lane); + l.* = .{ .caches = caches, .hidden = hidden, .len = prompt.len }; + break :blk l; + }; + errdefer h.free(lane); + gop.value_ptr.* = lane; + lane.id = try h.idOf(s); + // a drafted request resumes from the deepest shared snapshot and keeps its own marks; a serial one does neither + var owner: hip_prefix.Owner = .{ .caches = &lane.caches, .id = lane.id }; + h.matched.clearRetainingCapacity(); + var plan: radix.Plan = .{}; + h.prefix.restored = worker.no_snapshot; + if (s.drafts) plan = try h.prefix.begin(prompt, s.history_len, s.shared_prefixes, &owner, &h.matched); + defer if (s.drafts) h.gpa.free(plan.marks); + errdefer for (h.matched.items) |id| h.e.pool.release(id); + const at: usize = plan.from; + const adopted = h.matched.items.len; + try lane.caches.set(h.gpa, 0, h.matched.items); + h.matched.clearRetainingCapacity(); + // pages for the whole request are promised now, so no round runs out of them + const need = pages.pagesFor(lane.caches.total) - adopted; + if (!h.prefix.store.reclaim(need)) return error.OutOfPages; + lane.caches.promised = need; + h.e.pool.ids.reserved += need; + _ = try lane.caches.grow(h.gpa, prompt.len); + s.cached = @intCast(at); + var fill: Fill = .{ .at = at, .stops = undefined, .count = @min(plan.marks.len, 16), .next = 0 }; + @memcpy(fill.stops[0..fill.count], plan.marks[0..fill.count]); + lane.fill = fill; + if (h.link != null) { + // the other ranks get the stream's pages and where it resumed and cuts + h.msg.clearRetainingCapacity(); + const held = lane.caches.table.items; + try h.msg.appendSlice(h.gpa, &.{ @backingInt(worker.Op.prefill), lane.id, @intCast(lane.caches.total), @intCast(prompt.len), @intCast(at), @intCast(fill.count), h.prefix.restored, @intCast(held.len) }); + try h.msg.appendSlice(h.gpa, held); + try h.msg.appendSlice(h.gpa, fill.stops[0..fill.count]); + try h.msg.appendSlice(h.gpa, prompt); + try h.send(h.msg.items); + } + return lane; + } + + /// One chunk of the prompt pass, ending on the next cut or the prompt's end; the last draws the first token. + fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!bool { + const h = of(ptr); + if (s.isCancelled()) return error.Cancelled; + const lane = if (h.lanes.get(s)) |l| (if (l.fill != null) l else try h.begin(s)) else try h.begin(s); + const prompt = s.prompt(); + const f = &lane.fill.?; + const limit: usize = if (f.next < f.count) f.stops[f.next] else prompt.len; + const to = prefix.chunkEnd(f.at, limit); + if (h.link != null) try h.send(&.{ @backingInt(worker.Op.fill), lane.id, @intCast(to) }); + if (to == prompt.len) { + _ = h.take(try h.e.prefill(&lane.caches, prompt, f.at, lane.hidden, .{ .sampling = sampling(s), .position = prompt.len }, null)); + lane.fill = null; + return true; + } + try h.e.advance(&lane.caches, prompt, f.at, to, null); + f.at = to; + if (f.next < f.count and to == f.stops[f.next]) { + var owner: hip_prefix.Owner = .{ .caches = &lane.caches, .id = lane.id }; + h.prefix.keep(&owner, prompt, to) catch |err| std.log.warn("prefix not kept: {s}", .{@errorName(err)}); + f.next += 1; + } + return false; + } + + fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const h = of(ptr); + if (position != s.prompt_len) { + std.log.err("first draw at {d}, the prompt has {d} tokens", .{ position, s.prompt_len }); + return error.PositionMismatch; + } + return h.next - 1; + } + + fn queueFn(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + _ = ptr; + _ = s; + _ = feed; + _ = position; + return error.NotPipelined; + } + + fn readFn(ptr: *anyopaque, handle: u64) anyerror!u32 { + const h = of(ptr); + if (handle >= h.next or h.next - handle > ring) return error.NoSuchToken; + return h.drawn[handle % ring]; + } + + /// Each stream's window from its kept length: the pending token, then the host's drafts; one forward for all. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const h = of(ptr); + const began = costs.nowNs(); + defer h.timed(0, began); + if (windows.len > h.order.len) return error.WindowTooWide; + // windows the round loop did not trim keep every row before this round's plan replaces theirs + for (windows) |w| try h.settle(h.lanes.get(w.stream) orelse return error.UnknownStream); + try h.flush(); + for (windows) |w| { + const lane = h.lanes.get(w.stream).?; + try h.ensure(lane, lane.len + w.rows()); + } + var rows: [64]Engine.Rows = undefined; + var tokens: [64][16]u32 = undefined; + if (windows.len > rows.len) return error.WindowTooWide; + for (windows, 0..) |w, i| { + if (w.parents != null) return error.TreesNotBuilt; + const lane = h.lanes.get(w.stream) orelse return error.UnknownStream; + if (w.held > lane.held_n or (w.held > 0 and w.tokens.len > 0)) return error.NoHeldDrafts; + const n = w.rows(); + if (n > tokens[i].len) return error.WindowTooWide; + for (w.positions, 0..) |p, r| if (p != lane.len + 1 + r) { + std.log.err("row {d} keyed at {d}, the stream holds {d} slots", .{ r, p, lane.len }); + return error.PositionMismatch; + }; + tokens[i][0] = w.pending; + if (w.held > 0) @memcpy(tokens[i][1..n], lane.held[0..w.held]) else @memcpy(tokens[i][1..n], w.tokens); + rows[i] = .{ .caches = &lane.caches, .pos = lane.len, .tokens = tokens[i][0..n] }; + h.order[i] = w.stream; + } + var reqs: [256]draw.Request = undefined; + var drawn: [256]u32 = undefined; + var total: usize = 0; + for (windows) |w| { + if (total + w.positions.len > reqs.len) return error.WindowTooWide; + for (w.positions) |p| { + reqs[total] = .{ .sampling = sampling(w.stream), .position = p }; + total += 1; + } + } + // the graph choice is rank 0's, and goes with the round + const pick = try h.e.choose(rows[0..windows.len], null); + if (h.link != null) { + h.msg.clearRetainingCapacity(); + try h.msg.appendSlice(h.gpa, &.{ @backingInt(worker.Op.verify), @backingInt(pick), @intCast(windows.len) }); + for (windows, rows[0..windows.len]) |w, r| { + try h.msg.appendSlice(h.gpa, &.{ h.lanes.get(w.stream).?.id, @intCast(r.tokens.len) }); + try h.msg.appendSlice(h.gpa, r.tokens); + } + try h.send(h.msg.items); + } + _ = try h.e.verify(rows[0..windows.len], reqs[0..total], &drawn); + var at: usize = 0; + for (windows, out, 0..) |w, *o, i| { + @memcpy(o.sampled, drawn[at..][0..o.sampled.len]); + const lane = h.lanes.get(w.stream).?; + @memcpy(o.drafts, if (w.held > 0) lane.held[0..w.held] else w.tokens); + lane.held_n = 0; + lane.pending = .{ .window = i, .rows = w.rows() }; + at += w.rows(); + } + } + + /// Keep each stream's accepted prefix: lengths, and the linear states of its last kept row. + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const h = of(ptr); + const began = costs.nowNs(); + defer h.timed(1, began); + for (windows, paths) |w, path| { + const lane = h.lanes.get(w.stream) orelse return error.UnknownStream; + for (path, 0..) |r, j| if (r != j) return error.TreesNotBuilt; + // the draft request of the same round may have kept these rows already + if (lane.pending == null) continue; + try h.mark(lane, path.len); + } + try h.flush(); + } + + /// The head drafts `depth` from each stream's last kept row and its pending token, one head forward a step for all. + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + const h = of(ptr); + const began = costs.nowNs(); + defer h.timed(2, began); + const head = h.head orelse return error.NoDraftHead; + const m = h.e.model(); + var jobs: [max_jobs]mtp.Job = undefined; + var chained: [max_jobs]*Lane = undefined; + var n: usize = 0; + // a shared round asks for drafts before its keep: the request names the kept rows + for (requests) |r| { + const lane = h.lanes.get(r.stream) orelse return error.UnknownStream; + if (lane.pending != null) { + if (r.rows) |kept| try h.mark(lane, kept.len) else try h.settle(lane); + } + } + try h.flush(); + for (requests) |r| { + const lane = h.lanes.get(r.stream) orelse return error.UnknownStream; + if (r.position != lane.len + 1) { + std.log.err("draft for {s} at {d}, the stream holds {d} slots (rows {any}, depth {d})", .{ r.stream.id, r.position, lane.len, r.rows, r.depth }); + return error.PositionMismatch; + } + const token: u32 = if (r.rows != null) r.follow[r.follow.len - 1] else switch (r.first orelse return error.NoFirstToken) { + .handle => |at| h.drawn[at % ring], + .value => |v| v, + }; + lane.held_n = 0; + if (r.depth == 0) continue; + if (n == max_jobs) return error.WindowTooWide; + // a chain ends after a draft the head gives under the confidence; the first drafts run whole + const stop_under: f64 = if (r.rows != null) h.e.o.policy.mtp.confidence else 0.0; + jobs[n] = .{ .hidden = lane.hidden.base(), .token = token, .position = lane.len, .depth = r.depth, .sampling = sampling(r.stream), .stop_under = stop_under, .out = &lane.held }; + chained[n] = lane; + n += 1; + } + try head.chains(&h.e.lib, h.e.stream, &h.e.drawer, m, jobs[0..n], h.e.headGraphs()); + var k: usize = 0; + for (requests) |r| { + if (r.depth == 0) continue; + const lane = chained[k]; + lane.held_n = jobs[k].kept; + k += 1; + if (lane.held_n > r.depth or (lane.held_n < r.depth and r.rows == null)) return error.ShortChain; + } + } + + /// The drafts the head holds for the stream after its last chain: fewer than asked when a draft cut it. + fn heldFn(ptr: *anyopaque, s: *lanes.Stream, _: std.mem.Allocator) anyerror!?lanes.stream.Held { + const lane = of(ptr).lanes.get(s) orelse return error.UnknownStream; + return .{ .count = @intCast(lane.held_n) }; + } + + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { + const h = of(ptr); + const kv = h.lanes.fetchRemove(s) orelse return; + if (h.link != null) h.send(&.{ @backingInt(worker.Op.release), kv.value.id }) catch {}; + _ = h.ids.remove(s); + h.e.stream.synchronize() catch {}; + h.free(kv.value); + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig new file mode 100644 index 00000000000..99175fa6788 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig @@ -0,0 +1,153 @@ +//! The prompt cache's HIP side: pages and snapshots for core/prompt_radix.zig; rank 0 decides, other ranks apply. + +const std = @import("std"); +const hip = @import("hip"); +const radix = @import("engine_api").prompt_radix; +const memory = @import("memory.zig"); +const worker = @import("worker.zig"); +const state = @import("../forward/state.zig"); +const pages = @import("../forward/pages.zig"); +const Engine = @import("engine.zig").Engine; +const Allocator = std.mem.Allocator; + +/// What a stream gives the prompt cache: its caches and the id the other ranks know it by. +pub const Owner = struct { caches: *state.Caches, id: u32 }; + +pub const Prefix = struct { + gpa: Allocator, + e: *Engine, + store: radix.Store, + snaps: state.Snapshots, + /// Snapshot slots in use. + used: std.ArrayList(bool) = .empty, + /// The other ranks, when this is rank 0 of a group. + link: ?*const hip.link.Link = null, + msg: std.ArrayList(u32) = .empty, + /// The slot the last restore copied from (reset as a pass begins): the message that begins the pass names it. + restored: u32 = worker.no_snapshot, + + pub fn init(gpa: Allocator, e: *Engine) !*Prefix { + const p = try gpa.create(Prefix); + errdefer gpa.destroy(p); + const rules: radix.Rules = .{ .page = pages.tokens, .min_gap = @import("prefix.zig").min_gap, .min_prompt = 0, .tail = true }; + p.* = .{ .gpa = gpa, .e = e, .store = try radix.Store.init(gpa, .{ .ptr = p, .vtable = &family }, .{ .ptr = &e.pool, .vtable = &pool_pages, .bytes = e.pool.pageBytes() }, rules), .snaps = state.Snapshots.init(gpa, &e.driver) }; + return p; + } + + pub fn deinit(p: *Prefix) void { + p.store.deinit(); + p.snaps.deinit(); + p.used.deinit(p.gpa); + p.msg.deinit(p.gpa); + p.gpa.destroy(p); + } + + /// Keep up to `slots` snapshots and the pages the rest of `budget` bytes buys, a budget the memory plan granted. + pub fn keepPrompts(p: *Prefix, slots: usize, budget: usize) void { + const m = p.e.model(); + const room = memory.cache(m.spec, m.act.size(), budget, slots); + p.keepPages(@min(room.pages, p.e.pool.count), room.snaps); + } + + /// The tree may hold `max_pages` pages and `snaps` snapshots. + pub fn keepPages(p: *Prefix, max_pages: usize, snaps: usize) void { + p.store.limit(.{ .pages = max_pages, .snaps = snaps }); + if (p.store.tree.snaps == 0) p.snaps.clear(); + } + + pub fn send(p: *Prefix, words: []const u32) !void { + if (p.link) |l| try l.send(words); + } + + /// Tells the other ranks that the stream's pages from page `first` on are `ids`. + pub fn sendPages(p: *Prefix, id: u32, first: usize, ids: []const u32) !void { + if (p.link == null) return; + p.msg.clearRetainingCapacity(); + try p.msg.appendSlice(p.gpa, &.{ @backingInt(worker.Op.pages), id, @intCast(first), @intCast(ids.len) }); + try p.msg.appendSlice(p.gpa, ids); + try p.send(p.msg.items); + } + + /// Before a prompt pass: the longest resumable state restored into the stream, its pages in `adopt`, the marks. + pub fn begin(p: *Prefix, prompt: []const u32, history_len: u32, shared: []const u32, owner: *Owner, adopt: *std.ArrayList(u32)) !radix.Plan { + return p.store.begin(p.gpa, prompt, history_len, shared, owner, adopt); + } + + /// At `at` the tree takes the pages it lacks and the linear state; the stream swaps in the pages the tree had. + pub fn keep(p: *Prefix, owner: *Owner, prompt: []const u32, at: usize) !void { + if (!p.store.on()) return; + const n = at / pages.tokens; + const path = try p.gpa.alloc(u32, n); + defer p.gpa.free(path); + const caches = owner.caches; + const kept = p.store.keep(prompt, @intCast(at), owner, caches.table.items[0..n], path); + const own = path[0..kept.shared]; + if (!std.mem.eql(u32, own, caches.table.items[0..kept.shared])) { + for (own) |id| p.e.pool.retain(id); + try caches.set(p.gpa, 0, own); + try p.sendPages(owner.id, 0, own); + } + } + + fn slotOf(saved: radix.Saved) u32 { + return @intCast(@intFromPtr(saved) - 1); + } + + fn of(ptr: *anyopaque) *Prefix { + return @ptrCast(@alignCast(ptr)); + } + + fn snapBytes(ptr: *anyopaque, _: u32) u64 { + return memory.linearBytes(of(ptr).e.model().spec); + } + + fn save(ptr: *anyopaque, owner: ?*anyopaque, _: u32) anyerror!radix.Saved { + const p = of(ptr); + const o: *Owner = @ptrCast(@alignCast(owner.?)); + const slot: u32 = for (p.used.items, 0..) |u, i| { + if (!u) break @intCast(i); + } else blk: { + try p.used.append(p.gpa, false); + break :blk @intCast(p.used.items.len - 1); + }; + try p.snaps.take(slot, o.caches, p.e.stream.handle); + p.used.items[slot] = true; + try p.send(&.{ @backingInt(worker.Op.snap), o.id, slot }); + return @ptrFromInt(@as(usize, slot) + 1); + } + + fn restore(ptr: *anyopaque, owner: ?*anyopaque, saved: radix.Saved) anyerror!void { + const p = of(ptr); + const o: *Owner = @ptrCast(@alignCast(owner.?)); + try p.snaps.put(slotOf(saved), o.caches, p.e.stream.handle); + p.restored = slotOf(saved); + } + + fn dropSaved(ptr: *anyopaque, saved: radix.Saved) void { + of(ptr).used.items[slotOf(saved)] = false; + } + + const family: radix.Snapshots.VTable = .{ .bytes = snapBytes, .save = save, .restore = restore, .drop = dropSaved }; + + fn pool(ptr: *anyopaque) *pages.Pool { + return @ptrCast(@alignCast(ptr)); + } + + fn retain(ptr: *anyopaque, id: u32) void { + pool(ptr).retain(id); + } + + fn release(ptr: *anyopaque, id: u32) void { + pool(ptr).release(id); + } + + fn holders(ptr: *anyopaque, id: u32) u32 { + return pool(ptr).ids.refs[id]; + } + + fn available(ptr: *anyopaque) usize { + return pool(ptr).ids.available(); + } + + const pool_pages: radix.Pages.VTable = .{ .retain = retain, .release = release, .holders = holders, .available = available }; +}; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/memory.zig b/zig/src/families/qwen3_5/backend/hip/engine/memory.zig new file mode 100644 index 00000000000..3b24a8060d9 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/memory.zig @@ -0,0 +1,36 @@ +//! Bytes of a stream's state and of the prompt cache: pages of keys and values, and the linear layers' state. + +const config = @import("../../../weights/config.zig"); +const pages = @import("../forward/pages.zig"); + +/// Bytes of one page of the pool: the keys and values of 64 positions in every attention layer. +pub fn pageBytes(s: config.Spec, act_bytes: usize) usize { + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + return full * 2 * s.kv_heads * s.head_dim * act_bytes * pages.tokens; +} + +/// One stream's (or one snapshot's) linear state: the conv window and the recurrent state of every linear layer. +pub fn linearBytes(s: config.Spec) usize { + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + const conv = (s.keyWidth() * 2 + s.valueWidth()) * (s.conv - 1) * 4; + const recurrent = s.value_heads * s.value_dim * s.key_dim * 4; + return (s.n_layers - full) * (conv + recurrent); +} + +/// Bytes one stream's caches hold at `tokens` positions: attention keys and values plus the linear layers' state. +pub fn stateBytes(s: config.Spec, act_bytes: usize, tokens: usize) usize { + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + return full * 2 * s.kv_heads * s.head_dim * act_bytes * tokens + linearBytes(s); +} + +/// What `budget` bytes of prompt cache hold: at most `slots` snapshots, up to half of it, and pages for the rest. +pub const Cache = struct { pages: usize, snaps: usize }; + +pub fn cache(s: config.Spec, act_bytes: usize, budget: usize, slots: usize) Cache { + const snap = @max(linearBytes(s), 1); + const snaps = @min(slots, budget / 2 / snap); + return .{ .pages = (budget - snaps * snap) / @max(pageBytes(s, act_bytes), 1), .snaps = snaps }; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig new file mode 100644 index 00000000000..605d9bfaa84 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig @@ -0,0 +1,375 @@ +//! The MTP head drafting chains: one head forward a step over a row each; a round costs one chain's steps, one sync. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const view = @import("../model/view.zig"); +const weights = @import("../model/weights.zig"); +const bridge = @import("../model/bridge.zig"); +const fwd = @import("../forward/forward.zig"); +const draw = @import("draw.zig"); +const plan = @import("../forward/plan.zig"); +const graph_cache = @import("graph_cache.zig"); + +const pops = hip.plan_ops; +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; + +/// Most drafts a chain (the Python engine's depth). +pub const max_depth = 3; + +/// One stream's chain: its last kept final row, the token after it and its slot, the drafts asked for and their draw. +pub const Job = struct { + hidden: u64, + token: u32, + position: usize, + depth: usize, + sampling: ?lanes.Sampling, + stop_under: f64, + out: []u32, + kept: usize = 0, +}; + +/// What a greedy batch's launches depend on: its chain bucket, drafts per chain, whether the confidence cut runs. +const ChainKey = struct { rows: u32, most: u32, cut: bool }; + +/// A greedy chain reads the head over the first ids of the vocabulary alone (the common tokens): a draft only guesses. +const draft_vocab = 65536; + +/// Most chains one batch runs; a head serving `rows` rows a round holds caches for this many at most. +pub const max_chains = 64; + +pub const Head = struct { + gpa: std.mem.Allocator, + d: *const hip.Runtime, + w: *const weights.MtpHead, + heads: usize, + kv_heads: usize, + mlp: ?view.Mlp, + logits_head: view.Projection, + /// The same weights over the first `draft_vocab` ids. + draft_head: view.Projection, + /// Most chains a batch runs together; each has its own cache of `max_depth + 1` slots. + cap: usize, + cache_bytes: usize, + k: hip.DeviceBuffer, + v: hip.DeviceBuffer, + arena: hip.Arena, + /// The chains' last kept final rows gathered, (cap, hidden). + rows: hip.DeviceBuffer, + /// A row of zeros: the padding chains' input. + zero: hip.DeviceBuffer, + scalars: hip.HostBuffer, // `Layout`'s words, pinned + scalars_dev: hip.DeviceBuffer, + last: u64 = 0, // the last step's final rows, the next step's hidden input + /// Greedy batches captured by shape: the head's launches over the scalars alone, replayed. + graphs: graph_cache.Cache(ChainKey, void), + + /// The head of `m` with no device memory yet, or null when the checkpoint has none: what `deviceBytes` counts. + fn describe(gpa: std.mem.Allocator, d: *const hip.Runtime, m: *const weights.Model, model: *const view.Model, cap: usize) !?Head { + const w = if (m.mtp) |*x| x else return null; + const s = m.spec; + const qa = try bridge.projection(w.q); + const ka = try bridge.projection(w.k); + const kv_heads = ka.n / s.head_dim; + const full = if (w.head) |hp| try bridge.projection(hp) else model.head; + var narrow = full; + narrow.n = @min(full.n, draft_vocab); + const none: hip.DeviceBuffer = .{ .r = d, .ptr = null, .len = 0 }; + return .{ + .gpa = gpa, + .d = d, + .w = w, + .heads = qa.n / s.head_dim / @as(usize, if (w.gated) 2 else 1), + .kv_heads = kv_heads, + .mlp = if (w.mlp) |x| try bridge.mlpView(x, false) else null, + .logits_head = full, + .draft_head = narrow, + .cap = cap, + .cache_bytes = kv_heads * (max_depth + 1) * s.head_dim * model.act.size(), + .k = none, + .v = none, + .arena = hip.Arena.counting(), + .rows = none, + .zero = none, + .graphs = graph_cache.Cache(ChainKey, void).init(gpa), + .scalars = undefined, + .scalars_dev = none, + }; + } + + /// Device bytes the head of `m` holds for `cap` chains (0 without one): caches, rows, scalars and its arena. + pub fn deviceBytes(gpa: std.mem.Allocator, d: *const hip.Runtime, lib: *const hip.Launcher, m: *const weights.Model, model: *const view.Model, cap: usize) !usize { + var h = (try describe(gpa, d, m, model, cap)) orelse return 0; + defer h.graphs.deinit(); + const row = m.spec.hidden * model.act.size(); + return 2 * h.cache_bytes * cap + cap * row + row + h.layout().total + try h.scratch(lib, model); + } + + /// The head of `m`, or null when the checkpoint has none; `cap` chains at most run in one batch. + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, lib: *const hip.Launcher, m: *const weights.Model, model: *const view.Model, cap: usize) !?*Head { + const described = (try describe(gpa, d, m, model, cap)) orelse return null; + const s = m.spec; + const h = try gpa.create(Head); + errdefer gpa.destroy(h); + h.* = described; + errdefer h.graphs.deinit(); + h.k = try hip.DeviceBuffer.alloc(d, h.cache_bytes * cap); + errdefer h.k.free(); + h.v = try hip.DeviceBuffer.alloc(d, h.cache_bytes * cap); + errdefer h.v.free(); + h.rows = try hip.DeviceBuffer.alloc(d, cap * s.hidden * model.act.size()); + errdefer h.rows.free(); + h.zero = try hip.DeviceBuffer.alloc(d, s.hidden * model.act.size()); + errdefer h.zero.free(); + try h.zero.fill8(0); + h.scalars = try hip.HostBuffer.alloc(d, h.layout().total); + errdefer h.scalars.free(); + h.scalars_dev = try hip.DeviceBuffer.alloc(d, h.layout().total); + errdefer h.scalars_dev.free(); + h.arena = try hip.Arena.init(d, try h.scratch(lib, model)); + return h; + } + + /// The arena a batch of `cap` chains takes at full depth, greedy or sampled, counted on the counting stream. + fn scratch(h: *Head, lib: *const hip.Launcher, m: *const view.Model) !usize { + var most: usize = 0; + for ([_]view.Projection{ h.draft_head, h.logits_head }) |head| { + var arena = hip.Arena.counting(); + const o: Ops = .{ .l = lib, .bf16 = m.act == .bf16, .stream = hip.counting, .arena = &arena }; + try h.steps(o, m, head, h.cap, max_depth, true); + most = @max(most, arena.peak); + } + return most; + } + + pub fn deinit(h: *Head) void { + h.graphs.deinit(); + h.scalars_dev.free(); + h.scalars.free(); + h.zero.free(); + h.rows.free(); + h.arena.deinit(); + h.v.free(); + h.k.free(); + h.gpa.destroy(h); + } + + /// Scalar byte offsets: uploads (tokens, slots, positions, input row addresses), then downloads (drafts, probs). + const Layout = struct { slots: usize, pos: usize, ptrs: usize, drafts: usize, probs: usize, total: usize }; + + fn layout(h: *const Head) Layout { + const slots = 4 * h.cap; + const pos = slots + 4 * max_depth; + const ptrs = std.mem.alignForward(usize, pos + 4 * max_depth * h.cap, 8); + const drafts = ptrs + 8 * h.cap; + const probs = drafts + 4 * max_depth * h.cap; + return .{ .slots = slots, .pos = pos, .ptrs = ptrs, .drafts = drafts, .probs = probs, .total = probs + 4 * max_depth * h.cap }; + } + + /// A projection of the head in whichever format: an unquantized fp32 weight an MTP fc may keep, or a quantized one. + fn project(o: Ops, p: weights.Projection, x: Tensor, rows: usize) !Tensor { + return o.project(x, try bridge.projection(p), rows, false); + } + + /// Every job's chain, `cap` at a time, up to `depth` drafts each, cut after a draft under `stop_under` (0: never). + pub fn chains(h: *Head, lib: *const hip.Launcher, stream: hip.Stream, drawer: *draw.Drawer, m: *const view.Model, jobs: []Job, graphs: bool) !void { + var at: usize = 0; + while (at < jobs.len) : (at += h.cap) try h.batch(lib, stream, drawer, m, jobs[at..][0..@min(h.cap, jobs.len - at)], graphs); + } + + fn batch(h: *Head, lib: *const hip.Launcher, stream: hip.Stream, drawer: *draw.Drawer, m: *const view.Model, jobs: []Job, graphs: bool) !void { + const o: Ops = .{ .l = lib, .bf16 = m.act == .bf16, .stream = stream.handle, .arena = &h.arena }; + h.arena.reset(); + const rows = jobs.len; + const at = h.layout(); + const width = m.spec.hidden * m.act.size(); + var most: usize = 0; + var greedy = true; + var cut = false; + for (jobs) |j| { + most = @max(most, @min(j.depth, max_depth, j.out.len)); + if (j.sampling) |s| greedy = greedy and s.temperature <= 0.0; + cut = cut or j.stop_under > 0.0; + } + const sc = h.scalars.slice(i32); + const srcs = h.scalars.slice(u64); + // greedy chains run in a bucket of rows, the padding ones over zeros, so one graph serves any streams + const run = if (greedy) plan.bucketOf(rows, h.cap) else rows; + for (0..max_depth) |n| sc[h.cap + n] = @intCast(n); + for (0..run) |r| { + const real = r < jobs.len; + sc[r] = if (real) @intCast(jobs[r].token) else 0; + for (0..max_depth) |n| sc[at.pos / 4 + n * h.cap + r] = @intCast(n + if (real) jobs[r].position else 0); + srcs[at.ptrs / 8 + r] = if (real) jobs[r].hidden else h.zero.base(); + } + try hip.raw.upload(h.scalars_dev, 0, h.scalars.bytes[0..at.drafts], o.stream); + const dev = h.scalars_dev.base(); + if (greedy) { + try h.chain(stream, o, m, .{ .rows = @intCast(run), .most = @intCast(most), .cut = cut }, graphs); + } else { + try pops.gather(o, dev + at.ptrs, h.rows.base(), width / 4, rows); + var cur: Tensor = .{ .ptr = h.rows.base(), .kind = m.act }; + var reqs: [64]draw.Request = undefined; + var drawn: [64]u32 = undefined; + for (0..most) |n| { + const logits = try h.step(o, m, h.logits_head, cur, dev, rows, dev + at.slots + 4 * n, dev + at.pos + 4 * h.cap * n, n); + for (jobs, 0..) |j, r| reqs[r] = .{ .sampling = j.sampling, .position = j.position + n + 1 }; + try drawer.draw(o, stream, logits, reqs[0..rows], drawn[0..rows], false); + for (jobs, 0..) |j, r| if (n < j.out.len) { + j.out[n] = drawn[r]; + }; + if (n + 1 < most) { + for (0..rows) |r| sc[r] = @intCast(drawn[r]); + try hip.raw.upload(h.scalars_dev, 0, h.scalars.bytes[0 .. 4 * rows], o.stream); + if (cut) try o.tokenProb(logits, rows, h.logits_head.n, dev, dev + at.probs + 4 * h.cap * n); + } + cur = .{ .ptr = h.last, .kind = m.act }; + } + } + if (greedy or cut) { + try hip.raw.download(h.scalars_dev, at.drafts, h.scalars.bytes[at.drafts..at.total], o.stream); + try stream.synchronize(); + } + const words = h.scalars.slice(u32); + const chance = h.scalars.slice(f32); + for (jobs, 0..) |*j, r| { + const count = @min(j.depth, max_depth, j.out.len); + if (greedy) for (0..count) |n| { + j.out[n] = words[at.drafts / 4 + n * h.cap + r]; + }; + j.kept = count; + if (j.stop_under > 0.0) for (0..count -| 1) |n| if (chance[at.probs / 4 + n * h.cap + r] < j.stop_under) { + j.kept = n + 1; + break; + }; + } + } + + const Recording = struct { h: *Head, o: Ops, m: *const view.Model, key: ChainKey }; + + fn record(c: Recording) anyerror!void { + try c.h.launches(c.o, c.m, c.key); + } + + /// A greedy batch's launches: replayed from the shape's graph, captured the first time it is met, or eager. + fn chain(h: *Head, stream: hip.Stream, o: Ops, m: *const view.Model, key: ChainKey, graphs: bool) !void { + h.graphs.rounds += 1; + const entry = if (graphs) try h.graphs.find(key) else null; + if (entry) |e| switch (e.state) { + .ready => { + try e.exec.?.launchOn(stream); + h.graphs.replayed += 1; + return; + }, + .seen => { + if (try graph_cache.Cache(ChainKey, void).record(stream, Recording{ .h = h, .o = o, .m = m, .key = key }, record)) |rec| { + if (h.graphs.keep(e, rec.graph, stream, {})) { + try e.exec.?.launchOn(stream); + return; + } else |_| {} + } + e.state = .failed; + h.arena.reset(); + }, + .failed => {}, + }; + try h.launches(o, m, key); + } + + /// The chains' input rows gathered, then every step. + fn launches(h: *Head, o: Ops, m: *const view.Model, key: ChainKey) !void { + try pops.gather(o, h.scalars_dev.base() + h.layout().ptrs, h.rows.base(), m.spec.hidden * m.act.size() / 4, key.rows); + try h.steps(o, m, h.draft_head, key.rows, key.most, key.cut); + } + + /// The greedy chains' steps on the device alone: each step's drafts feed the next, with probabilities for the cut. + fn steps(h: *Head, o: Ops, m: *const view.Model, head: view.Projection, rows: usize, most: usize, cut: bool) !void { + const at = h.layout(); + const dev = h.scalars_dev.base(); + var cur: Tensor = .{ .ptr = h.rows.base(), .kind = m.act }; + for (0..most) |n| { + const drafts = dev + at.drafts + 4 * h.cap * n; + const ids = if (n == 0) dev else drafts - 4 * h.cap; + const logits = try h.step(o, m, head, cur, ids, rows, dev + at.slots + 4 * n, dev + at.pos + 4 * h.cap * n, n); + try o.argmaxRows(logits, rows, head.n, drafts); + if (cut and n + 1 < most) try o.tokenProb(logits, rows, head.n, 0, dev + at.probs + 4 * h.cap * n); + cur = .{ .ptr = h.last, .kind = m.act }; + } + } + + /// One head step over `rows` chains at their rope positions, writing each chain's slot; the logits rows come back. + fn step(h: *Head, o: Ops, m: *const view.Model, head: view.Projection, hidden: Tensor, ids: u64, rows: usize, slot_at: u64, pos: u64, slot: usize) !Tensor { + const s = m.spec; + const w = h.w; + const eps: f32 = @floatCast(s.eps); + const hd = s.head_dim; + const emb = try fwd.take(o, m.act, rows * s.hidden); + try o.embedRows(m.embed, ids, rows, emb); + const emb_e = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(emb, w.fc_e_norm.ptr, emb_e, rows, s.hidden, eps); + const emb_h = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(hidden, w.fc_h_norm.ptr, emb_h, rows, s.hidden, eps); + const e_proj = try project(o, w.fc_e, emb_e, rows); + const h_proj = try project(o, w.fc_h, emb_h, rows); + const x = try fwd.take(o, m.act, rows * s.hidden); + try o.add(e_proj, h_proj, x, rows * s.hidden); + var normed = x; + if (w.input_norm) |n| { + normed = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(x, n.ptr, normed, rows, s.hidden, eps); + } + // the head's gated attention over each chain's cache (slots 0 .. slot), rope at the chain's position + const qg = try project(o, w.q, normed, rows); + const keys = try project(o, w.k, normed, rows); + const values = try project(o, w.v, normed, rows); + const qc = try fwd.take(o, m.act, rows * h.heads * hd); + try o.copyCols(qg, if (w.gated) 2 * hd else hd, 0, qc.ptr, rows * h.heads, hd); + const qn = try fwd.take(o, m.act, rows * h.heads * hd); + try o.rms(qc, w.q_norm.ptr, qn, rows * h.heads, hd, eps); + const kn = try fwd.take(o, m.act, rows * h.kv_heads * hd); + try o.rms(keys, w.k_norm.ptr, kn, rows * h.kv_heads, hd, eps); + const q32 = try ropeRows(o, m, qn, rows, h.heads, pos); + const k32 = try ropeRows(o, m, kn, rows, h.kv_heads, pos); + const kr = try fwd.take(o, m.act, rows * h.kv_heads * hd); + try o.cast(.{ .ptr = k32, .kind = .f32 }, kr, rows * h.kv_heads * hd); + const att = try o.arena.of(f32, rows * h.heads * hd); + for (0..rows) |r| { + const c: Ops.Cache = .{ .k = h.k.base() + r * h.cache_bytes, .v = h.v.base() + r * h.cache_bytes, .kind = m.act, .kv_heads = h.kv_heads, .total = max_depth + 1, .d = hd }; + try o.kvWrite(fwd.at(kr, r * h.kv_heads * hd), c.k, 1, h.kv_heads, hd, c.total, slot); + try o.kvWrite(fwd.at(values, r * h.kv_heads * hd), c.v, 1, h.kv_heads, hd, c.total, slot); + try o.causalAt(q32 + r * h.heads * hd * 4, c, att + r * h.heads * hd * 4, 1, h.heads, fwd.scaleOf(hd), slot_at); + } + const gated = try fwd.take(o, m.act, rows * h.heads * hd); + if (w.gated) { + try o.attnGate(att, qg, gated, rows, h.heads, hd, true); + } else try o.cast(.{ .ptr = att, .kind = .f32 }, gated, rows * h.heads * hd); + const attn_out = try project(o, w.o, gated, rows); + try o.add(x, attn_out, x, rows * s.hidden); + if (w.post_norm) |pn| if (h.mlp) |mlp| { + const xn = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(x, pn.ptr, xn, rows, s.hidden, eps); + const y = try fwd.mlpRows(o, m, mlp, xn, rows, false); + try o.add(x, y, x, rows * s.hidden); + }; + const residual = try fwd.take(o, m.act, rows * s.hidden); + try o.rms(x, w.final_norm.ptr, residual, rows, s.hidden, eps); + h.last = residual.ptr; + return o.project(residual, head, rows, false); + } +}; + +/// The decode RoPE of `rows` rows of `heads` heads, each at its device position, in the activation dtype. +fn ropeRows(o: Ops, m: *const view.Model, x: Tensor, rows: usize, heads: usize, pos: u64) !u64 { + const s = m.spec; + const n = rows * heads * s.head_dim; + const wide = try o.arena.of(f32, n); + try o.cast(x, .{ .ptr = wide, .kind = .f32 }, n); + const turned = try o.arena.of(f32, n); + try o.ropeDecode(wide, turned, rows * heads, s.head_dim, s.rotary_dim, 0, @floatCast(s.rope_theta), pos, heads); + const narrow = try fwd.take(o, m.act, n); + try o.cast(.{ .ptr = turned, .kind = .f32 }, narrow, n); + const back = try o.arena.of(f32, n); + try o.cast(narrow, .{ .ptr = back, .kind = .f32 }, n); + return back; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig new file mode 100644 index 00000000000..7a1a3c7a1a4 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -0,0 +1,205 @@ +//! Qwen3.5 / Qwen3.6 for the native server on HIP: the engine sized to GPU memory and the lane backend over it. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const engine = @import("engine.zig"); +const Engine = engine.Engine; +const memory = @import("memory.zig"); +const mtp = @import("mtp.zig"); +const prefix = @import("prefix.zig"); +const pages = @import("../forward/pages.zig"); +const state = @import("../forward/state.zig"); +const worker = @import("worker.zig"); +const hip_lanes = @import("hip_lanes.zig"); + +/// The MLX affine widths the family loads. +const mlx_formats: []const []const u8 = &.{ "mlx-q2", "mlx-q3", "mlx-q4", "mlx-q5", "mlx-q6", "mlx-q8" }; + +/// The dense and the sparse checkpoints are two registry entries over one engine. +pub fn Native(comptime type_name: []const u8) type { + return struct { + pub const model_type = type_name; + pub const formats = mlx_formats; + /// Positions a stream holds when neither --context nor the checkpoint's config names a window. + pub const default_context: i64 = 32768; + /// The engine cuts prompts itself. + pub const prefill_step: u32 = 0; + pub const open = openEngine; + pub const follow = followRank; + }; +} + +/// What the serve flags ask of the engine, as the host read them. +pub const Options = struct { + /// Prompt plus reply tokens a request may use: --context, or the family default within the model's window. + window: usize, + /// Streams asked for at once; `fixed` when --parallel named the number, which then fits or is refused. + streams: usize, + fixed: bool = false, + /// This process is `rank` of `world`. + rank: u32 = 0, + world: u32 = 1, + /// Bytes kept prompt states may hold (null: the policy's, else what the streams leave) and their snapshot slots. + cache_gib: ?f64 = null, + /// A --prompt-cache-gib past what the streams leave is kept, not refused. + cache_over_cap: bool = false, +}; + +/// What the native server drives: the lane backend, the facts its round loop reads, and how to free it. +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + /// The streams admitted at once, and the server's startup line (the memory plan). + streams: usize, + startup: []const u8, +}; + +/// A flag or a resource the engine cannot take: `problem` says why. +pub const Refused = error{Refused}; + +fn refuse(a: std.mem.Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { + problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; + return error.Refused; +} + +fn gibs(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// One rank's loaded and sized engine: the streams and prompt cache every rank agreed on. +const Prepared = struct { + e: *Engine, + streams: usize, + /// What the prompt cache holds: pages of the pool and linear snapshots (none when it is off). + cache: memory.Cache, + startup: []const u8, +}; + +/// Device bytes of `streams` lanes at `capacity` beside the weights; the prompt cache takes what is left. +fn served(e: *Engine, streams: usize, capacity: usize) !usize { + const rows = streams * hip_lanes.Hip.max_window; + return e.planBytes(streams, rows, capacity, streams * pages.pagesFor(capacity) + pages.pagesFor(rows), 0); +} + +/// Loads this rank's share of the model, admits the streams its memory holds (with the other ranks) and sizes them. +fn prepare(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: Options, problem: *[]const u8) (Refused || std.mem.Allocator.Error)!Prepared { + const rows = hip_lanes.Hip.max_window; + const held = hip.usage(false).device; + var pf: engine.Preflight = .{}; + const e = Engine.load(gpa, io, dir, .{ + .preflight = &pf, + .slack = rows + 1, + .device = dev.index, + .policy = dev.policy, + .rank = o.rank, + .world = o.world, + .id = if (dev.group) |g| g.id else null, + }) catch |err| return switch (err) { + error.WeightsDoNotFit => refuse(a, problem, "the checkpoint's {d:.1} GiB of weights do not fit the {d:.1} GiB the HIP memory budget grants ({d:.1} GiB free less a {d:.1} GiB reserve{s}); free device memory or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_HIP_MEMORY_LIMIT_GB", .{ gibs(pf.weights), gibs(pf.pool.room(pf.held)), gibs(pf.pool.free), gibs(pf.pool.reserve), if (pf.pool.limit != null) ", under TENSORFOLD_HIP_MEMORY_LIMIT_GB" else "" }), + error.BadReserve => refuse(a, problem, "TENSORFOLD_MEMORY_RESERVE_GIB: a number of GiB from 2 to the memory's size", .{}), + error.BadLimit => refuse(a, problem, "TENSORFOLD_HIP_MEMORY_LIMIT_GB: a positive number of GiB whose byte count fits in a 64-bit size", .{}), + error.HostMemoryUnavailable => refuse(a, problem, "cannot read or parse /proc/meminfo's MemTotal and MemAvailable; refusing HIP unified-memory admission", .{}), + else => refuse(a, problem, "the native HIP engine cannot load {s} ({s})", .{ dir, @errorName(err) }), + }; + errdefer e.deinit(); + const model = hip.usage(false).device - held; + const after = e.budget(io) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)}); + const room = after.room(model); + const reserve = after.reserve; + const capacity = o.window + rows + 1; + // the most streams up to the ones asked whose bytes fit, then the least of that over the ranks + var streams = o.streams; + while (streams > 0) : (streams -= 1) { + if ((served(e, streams, capacity) catch |err| return refuse(a, problem, "the native HIP engine cannot count its scratch ({s})", .{@errorName(err)})) <= room) break; + } + if (o.world > 1) streams = (e.least(.{ streams, 0 }) catch |err| return refuse(a, problem, "the ranks could not agree on the streams ({s})", .{@errorName(err)}))[0]; + if (streams == 0) { + const one = served(e, 1, capacity) catch 0; + return refuse(a, problem, "the HIP memory budget fits no stream: one at a {d}-token window takes {d:.2} GiB, and {d:.2} GiB is left after the model's {d:.2} GiB and the {d:.1} GiB reserve; lower --context, add ranks (--tp), or free device memory", .{ o.window, gibs(one), gibs(room), gibs(model), gibs(reserve) }); + } + if (streams < o.streams and o.fixed) { + const asked = served(e, o.streams, capacity) catch 0; + return refuse(a, problem, "--parallel {d} needs {d:.2} GiB at a {d}-token window, and the HIP memory budget leaves {d:.2} GiB: serve --parallel {d}, or lower --context", .{ o.streams, gibs(asked), o.window, gibs(room), streams }); + } + const need = served(e, streams, capacity) catch |err| return refuse(a, problem, "the native HIP engine cannot count its scratch ({s})", .{@errorName(err)}); + // the prompt cache: --prompt-cache-gib, else what the streams leave + const left = room - need; + const policy = dev.policy; + const keep: usize = policy.slots; + var budget: usize = if (o.cache_gib) |g| @intFromFloat(g * (1 << 30)) else left; + if (budget > left and !o.cache_over_cap) { + return refuse(a, problem, "a {d:.2} GiB prompt cache does not fit the {d:.2} GiB the streams leave; lower --prompt-cache-gib, or --prompt-cache-over-cap to keep it", .{ gibs(budget), gibs(left) }); + } + if (keep == 0) budget = 0; + var cache = memory.cache(e.weights.spec, e.act.size(), budget, keep); + if (o.world > 1) { + const fit = e.least(.{ cache.pages, cache.snaps }) catch |err| return refuse(a, problem, "the ranks could not agree on a prompt cache ({s})", .{@errorName(err)}); + cache = .{ .pages = fit[0], .snaps = fit[1] }; + } + e.o.batch_rows = streams * rows; + e.o.streams = streams; + e.size(capacity, streams * pages.pagesFor(capacity) + pages.pagesFor(e.o.batch_rows) + cache.pages) catch |err| + return refuse(a, problem, "the native HIP engine cannot allocate its scratch and pages ({s})", .{@errorName(err)}); + const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size())); + const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompt cache {d:.2} GiB ({d} pages, {d} snapshots); prompts in {d}-row chunks", .{ + hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), streams, if (streams == 1) "" else "s", lane, o.window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, + }); + return .{ .e = e, .streams = streams, .cache = cache, .startup = startup }; +} + +const Owned = struct { + gpa: std.mem.Allocator, + e: *Engine, + backend: *hip_lanes.Hip, + startup: []const u8, +}; + +fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + // the other ranks hear that the rounds are over, then every rank frees its share + own.backend.deinit(); + own.e.deinit(); + own.gpa.free(own.startup); + own.gpa.destroy(own); +} + +/// The engine for `dir` on `dev`; under tensor parallelism this is rank 0, which serves. +fn openEngine(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: Options, problem: *[]const u8) anyerror!Loaded { + const p = try prepare(a, gpa, io, dev, dir, o, problem); + errdefer p.e.deinit(); + errdefer gpa.free(p.startup); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + const before = hip.usage(false).device; + own.* = .{ .gpa = gpa, .e = p.e, .backend = try hip_lanes.Hip.init(gpa, p.e), .startup = p.startup }; + errdefer own.backend.deinit(); + // the head is the one allocation of the plan made here: it holds what the plan counted for it + const head = mtp.Head.deviceBytes(gpa, &p.e.driver, &p.e.lib, &p.e.weights, p.e.model(), @min(p.e.o.batch_rows, mtp.max_chains)) catch 0; + if (hip.usage(false).device - before != head) return refuse(a, problem, "the draft head holds {d} device bytes, the plan says {d}", .{ hip.usage(false).device - before, head }); + if (p.cache.pages > 0) own.backend.keepPages(p.cache.pages, p.cache.snaps); + // a lone rank times its forwards for the depth rule; the ranks of a group draft without costs + if (dev.group) |g| own.backend.withLink(&g.link) else own.backend.measure(); + return .{ + .backend = own.backend.backend(), + .facts = own.backend.facts(), + .rows = hip_lanes.Hip.max_window, + .ctx = own, + .deinit = release, + .streams = p.streams, + .startup = p.startup, + }; +} + +/// A rank above 0: holds its share of the model and runs rank 0's steps until rank 0 stops. +fn followRank(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: Options, problem: *[]const u8) anyerror!void { + const p = try prepare(a, gpa, io, dev, dir, o, problem); + defer p.e.deinit(); + defer gpa.free(p.startup); + var w = try worker.Worker.init(gpa, p.e); + defer w.deinit(); + try w.follow(&dev.group.?.link); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig b/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig new file mode 100644 index 00000000000..a0619770a8e --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig @@ -0,0 +1,17 @@ +//! The chunks a prompt pass runs in, and the gap between the snapshots it keeps. + +const pages = @import("../forward/pages.zig"); + +/// A snapshot this close to the prompt's end saves too little to keep next to the one before it. +pub const min_gap = 256; + +/// Cuts sit on page edges, multiples of the recurrence's chunk, so a resumed span chunks as a fresh prompt does. +pub const step = pages.tokens; + +/// Rows a prompt pass advances between two rounds; its steps end on multiples of this, so a prompt is cut the same way. +pub const chunk = 1024; + +/// Where the step from `at` ends: the next multiple of `chunk`, or `limit` when that comes first. +pub fn chunkEnd(at: usize, limit: usize) usize { + return @min(limit, (at / chunk + 1) * chunk); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round.zig b/zig/src/families/qwen3_5/backend/hip/engine/round.zig new file mode 100644 index 00000000000..10be7123eef --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/round.zig @@ -0,0 +1,251 @@ +//! A lane round on the engine: its device plan, its forward (replayed, captured or eager), its draws and its keep. + +const std = @import("std"); +const hip = @import("hip"); +const state = @import("../forward/state.zig"); +const win = @import("../forward/window.zig"); +const fwd = @import("../forward/forward.zig"); +const plan = @import("../forward/plan.zig"); +const view = @import("../model/view.zig"); +const draw = @import("draw.zig"); +const round_graphs = @import("round_graphs.zig"); +const Engine = @import("engine.zig").Engine; + +/// What a round does with its shape's graph: run eagerly, replay it, or capture it (every rank does the same). +pub const Pick = enum(u32) { eager, replay, capture }; + +/// What a verify hands back: the round's final rows, padding included. +pub const Verified = struct { hidden: hip.ops.Tensor }; + +/// One stream's rows of a round: tokens (the pending one, then drafts) from slot `pos` over its caches. +pub const Rows = struct { caches: *state.Caches, pos: usize, tokens: []const u32 }; + +const Chosen = struct { pick: Pick, entry: ?*round_graphs.Entry, shape: plan.Shape }; + +/// The slots a keep names and the plan they index. +const Last = struct { plan: hip.plan_ops.Plan, keep_at: usize, hidden: u64 }; + +/// Keep lists in flight: a flush's pinned words stay until its copy has run, which a later round's sync guarantees. +const keep_ring = 4; + +pub const State = struct { + buffer: plan.Buffer, + /// The caches the padding rows run in. + scratch: state.Caches, + /// Each linear layer's snapshots of the round in flight. + snaps: [][2]u64, + wins: []plan.Window, + /// The rows each slot keeps at the next flush (negative: not listed), and the pinned words they go up in. + staging: []i32, + keeps: hip.HostBuffer, + ring: usize = 0, + /// For checks: a layer-by-layer trace of the forward (graphs off), and a least bucket of rows. + trace: ?fwd.Trace = null, + pad_to: usize = 0, + chosen: ?Chosen = null, + last: ?Last = null, + /// The layout of the plan in flight, for the copy a round starts with. + layout: plan.Layout = undefined, + + pub fn init(e: *Engine) !State { + const m = e.model(); + if (!win.supported(e.ops(&e.rounds), m)) return error.RoundsUnsupported; + const rows = e.o.batch_rows; + var buffer = try plan.Buffer.init(&e.driver, rows, m.spec.n_layers, e.pool.count); + errdefer buffer.deinit(); + var scratch = try state.Caches.initFull(e.gpa, &e.pool, m, rows); + errdefer scratch.deinit(e.gpa); + const snaps = try e.gpa.alloc([2]u64, m.spec.n_layers); + errdefer e.gpa.free(snaps); + const wins = try e.gpa.alloc(plan.Window, rows); + errdefer e.gpa.free(wins); + const staging = try e.gpa.alloc(i32, rows + 1); + errdefer e.gpa.free(staging); + @memset(staging, -1); + return .{ .buffer = buffer, .scratch = scratch, .snaps = snaps, .wins = wins, .staging = staging, .keeps = try hip.HostBuffer.alloc(&e.driver, keep_ring * 4 * (rows + 1)) }; + } + + pub fn deinit(s: *State, e: *Engine) void { + s.keeps.free(); + e.gpa.free(s.staging); + e.gpa.free(s.wins); + e.gpa.free(s.snaps); + s.scratch.deinit(e.gpa); + s.buffer.deinit(); + } +}; + +/// The shape of a round of `rows`: its bucket of rows, its slots and the keys its walk covers. +pub fn shapeOf(e: *Engine, rows: []const Rows) !plan.Shape { + var total: usize = 0; + var visible: usize = 0; + for (rows) |r| { + total += r.tokens.len; + visible = @max(visible, r.pos + r.tokens.len); + } + if (rows.len == 0 or total == 0 or total > e.o.batch_rows) return error.WindowTooWide; + const cap = std.mem.alignForward(usize, e.o.capacity, plan.min_span); + const bucket = plan.bucketOf(@max(total, e.round.pad_to), e.o.batch_rows); + const slots = plan.bucketOf(rows.len + 1, e.o.batch_rows + 1); + return .{ .rows = @intCast(bucket), .slots = @intCast(slots), .span = @intCast(@min(plan.spanOf(visible), cap)) }; +} + +/// The round's graph choice: from the shape's history, or `forced` (rank 0's pick, which a follower obeys). +pub fn choose(e: *Engine, rows: []const Rows, forced: ?Pick) !Pick { + const st = &e.round; + const shape = try shapeOf(e, rows); + st.chosen = .{ .pick = .eager, .entry = null, .shape = shape }; + if (!e.o.graphs) { + if ((forced orelse .eager) != .eager) return error.GraphsDisagree; + return .eager; + } + const entry = try e.graphs.find(shape); + const mine: Pick = switch (entry.state) { + .failed => .eager, + .ready => .replay, + .seen => .capture, + }; + const pick = forced orelse mine; + if (pick == .replay and entry.state != .ready) return error.GraphsDisagree; + st.chosen = .{ .pick = pick, .entry = entry, .shape = shape }; + return pick; +} + +fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +/// Every window in one forward: `out` the token of every row per `reqs`; snapshots live until the next round's `keep`. +pub fn verify(e: *Engine, rows: []const Rows, reqs: []const draw.Request, out: []u32) !Verified { + const st = &e.round; + const m = e.model(); + const began = nowNs(); + if (st.chosen == null) _ = try choose(e, rows, null); + const c = st.chosen.?; + defer st.chosen = null; + var total: usize = 0; + for (rows, 0..) |r, i| { + if (r.pos + r.tokens.len > r.caches.covered()) return error.ContextFull; + st.wins[i] = .{ .desc = r.caches.desc.base(), .pos = r.pos, .tokens = r.tokens }; + total += r.tokens.len; + } + e.rounds.reset(); + const o = e.ops(&e.rounds); + try win.kept(o, m, c.shape.rows, st.snaps); + const l = plan.Layout.of(c.shape.rows, c.shape.slots, m.spec.n_layers); + st.buffer.fill(l, c.shape, st.wins[0..rows.len], st.scratch.desc.base(), st.snaps); + st.layout = l; + const p: hip.plan_ops.Plan = .{ .args = st.buffer.args(l), .rows = c.shape.rows, .slots = c.shape.slots }; + const r: win.Round = .{ .plan = p, .tokens = st.buffer.dev.base() + 4 * l.tokens, .span = c.shape.span, .inputs = st.snaps }; + const done = try run(e, c, r); + e.graphs.rounds += 1; + e.graphs.submit_ns += nowNs() - began; + try e.drawRows(o, done.y, total, reqs, out, m.tp == null); + st.last = .{ .plan = p, .keep_at = 4 * l.keep, .hidden = done.hidden.ptr }; + return .{ .hidden = done.hidden }; +} + +/// The forward and its logits projection, and the greedy draw of every row when this rank holds the whole head. +fn body(e: *Engine, r: win.Round) !round_graphs.Out { + // the plan goes up first, inside the graph + try e.round.buffer.send(e.stream.handle, e.round.layout); + return forwardOn(e.ops(&e.rounds), e.model(), r, e.round.trace, e.drawer.argmaxAt()); +} + +/// `body` after the plan's copy, on `o`: on the counting stream it measures what a round takes. +pub fn forwardOn(ops: hip.ops.Ops, m: *const view.Model, r: win.Round, trace: ?fwd.Trace, argmax_at: u64) !round_graphs.Out { + var o = ops; + // a round's rows keep their decode kernels however many share it + o.window = true; + const hidden = try win.forward(o, m, r, trace); + const y = try o.project(hidden, m.head, r.plan.rows, false); + if (m.tp == null) try o.argmaxRows(y, r.plan.rows, m.head.n, argmax_at); + return .{ .hidden = hidden, .y = y, .used = o.arena.used }; +} + +/// One round's forward as `choose` picked: replayed from the shape's graph, captured, or eager. +fn run(e: *Engine, c: Chosen, r: win.Round) !round_graphs.Out { + const entry = c.entry orelse return body(e, r); + switch (c.pick) { + .eager => return body(e, r), + .replay => { + e.rounds.used = entry.out.used; + try entry.exec.?.launchOn(e.stream); + e.graphs.replayed += 1; + return entry.out; + }, + .capture => return capture(e, entry, r), + } +} + +const Recording = struct { e: *Engine, r: win.Round }; + +fn record(ctx: Recording) anyerror!round_graphs.Out { + return body(ctx.e, ctx.r); +} + +/// Records the round into a graph and launches it; a capture that fails on any rank runs eagerly on every rank. +fn capture(e: *Engine, entry: *round_graphs.Entry, r: win.Round) !round_graphs.Out { + var kept = false; + var out: round_graphs.Out = undefined; + const at = e.rounds.mark(); + const began = nowNs(); + if (try round_graphs.Graphs.record(e.stream, Recording{ .e = e, .r = r }, record)) |rec| { + out = rec.out; + kept = if (e.graphs.keep(entry, rec.graph, e.stream, rec.out)) true else |_| false; + } + // the policy's `graph_fail` makes that rank's capture fail, to check that every rank falls back + if (e.o.policy.graph_fail >= 0 and @as(usize, @intCast(e.o.policy.graph_fail)) == e.o.rank) kept = false; + e.graphs.capture_ns += nowNs() - began; + const all = if (e.o.world > 1) try agreed(e, kept) else kept; + if (!all) { + e.graphs.revoke(entry); + e.rounds.release(at); + return body(e, r); + } + try entry.exec.?.launchOn(e.stream); + return out; +} + +/// Whether every rank says yes (an all-gather of one word each). +fn agreed(e: *Engine, yes: bool) !bool { + const world = e.o.world; + var host = try hip.HostBuffer.alloc(&e.driver, 8 * (1 + world)); + defer host.free(); + var send = try hip.DeviceBuffer.alloc(&e.driver, 8); + defer send.free(); + var recv = try hip.DeviceBuffer.alloc(&e.driver, 8 * world); + defer recv.free(); + host.slice(u64)[0] = @intFromBool(yes); + try hip.raw.upload(send, 0, host.bytes[0..8], e.stream.handle); + try e.comm.allGather(send.base(), recv.base(), 1, .i64, e.stream.handle); + try hip.raw.download(recv, 0, host.bytes[8 .. 8 * (1 + world)], e.stream.handle); + try e.stream.synchronize(); + for (host.slice(u64)[1 .. 1 + world]) |v| if (v == 0) return false; + return true; +} + +/// Marks slot `slot` of the last verify to keep its first `rows` rows at the next `flush`. +pub fn mark(e: *Engine, slot: usize, rows: usize) void { + e.round.staging[slot] = @intCast(rows); +} + +/// Keeps every marked slot of the last verify in one launch: linear states after the kept rows, last kept final rows. +pub fn flush(e: *Engine) !void { + const st = &e.round; + const last = st.last orelse return; + const slots = last.plan.slots; + var any = false; + for (st.staging[0..slots]) |k| any = any or k >= 0; + if (!any) return; + const per = e.o.batch_rows + 1; + const from = 4 * st.ring * per; + const words = st.keeps.slice(i32)[st.ring * per ..][0..slots]; + st.ring = (st.ring + 1) % keep_ring; + @memcpy(words, st.staging[0..slots]); + @memset(st.staging[0..slots], -1); + try st.buffer.dev.uploadAsync(last.keep_at, st.keeps.view(from, from + 4 * slots), e.stream); + try win.keep(e.ops(&e.rounds), e.model(), last.plan, st.buffer.dev.base() + last.keep_at, last.hidden); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig new file mode 100644 index 00000000000..4228302d0bf --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig @@ -0,0 +1,12 @@ +//! Captured lane rounds: a round's forward recorded once per plan shape and replayed on any later round of it. + +const hip = @import("hip"); +const plan = @import("../forward/plan.zig"); +const graph_cache = @import("graph_cache.zig"); + +/// What a replay hands back: the forward's outputs and where the arena stands after it. +pub const Out = struct { hidden: hip.ops.Tensor, y: hip.ops.Tensor, used: usize }; + +pub const Graphs = graph_cache.Cache(plan.Shape, Out); + +pub const Entry = Graphs.Entry; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/sample.zig b/zig/src/families/qwen3_5/backend/hip/engine/sample.zig new file mode 100644 index 00000000000..602d503555b --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/sample.zig @@ -0,0 +1,92 @@ +//! A row's token from its logits: argmax for greedy, else the keyed draw over top_k + MARGIN candidates. + +const std = @import("std"); +const lanes = @import("lanes"); +const Allocator = std.mem.Allocator; + +/// exact_sampling.MARGIN: candidates past top_k, so ties resolve by id on the host. +pub const MARGIN = 8; + +pub const Dtype = enum { f16, bf16 }; + +pub fn widen(row: []const u16, dtype: Dtype, i: usize) f32 { + return switch (dtype) { + .f16 => @floatCast(@as(f16, @bitCast(row[i]))), + .bf16 => @bitCast(@as(u32, row[i]) << 16), + }; +} + +/// torch.argmax over the widened row: the first index of the largest value (a NaN wins, as torch's). +pub fn argmax(row: []const u16, dtype: Dtype) u32 { + var best: usize = 0; + var top = widen(row, dtype, 0); + for (1..row.len) |i| { + const v = widen(row, dtype, i); + if (std.math.isNan(top)) break; + if (std.math.isNan(v) or v > top) { + best = i; + top = v; + } + } + return @intCast(best); +} + +const Candidate = struct { value: f32, id: u32 }; + +fn larger(_: void, a: Candidate, b: Candidate) bool { + return a.value > b.value or (a.value == b.value and a.id < b.id); +} + +/// draw(): greedy (no sampling or temperature <= 0) is the argmax; else `choose` at `position` over the candidates. +pub fn draw(gpa: Allocator, row: []const u16, dtype: Dtype, sampling: ?lanes.Sampling, position: u64) !u32 { + const s = sampling orelse return argmax(row, dtype); + if (s.temperature <= 0.0) return argmax(row, dtype); + const width = row.len; + const count = if (s.top_k != 0) @min(width, @as(usize, s.top_k) + MARGIN) else width; + const best = try gpa.alloc(Candidate, count); + defer gpa.free(best); + var filled: usize = 0; + // the whole row when top_k is 0 (choose orders it), else the top `count` by value then id in one pass + if (count == width) { + for (best, 0..) |*c, i| c.* = .{ .value = widen(row, dtype, i), .id = @intCast(i) }; + filled = width; + } else for (0..width) |i| { + const c: Candidate = .{ .value = widen(row, dtype, i), .id = @intCast(i) }; + if (filled == count and !larger({}, c, best[count - 1])) continue; + var at = if (filled < count) filled else count - 1; + if (filled < count) filled += 1; + while (at > 0 and larger({}, c, best[at - 1])) : (at -= 1) best[at] = best[at - 1]; + best[at] = c; + } + const values = try gpa.alloc(f64, count); + defer gpa.free(values); + const ids = try gpa.alloc(u64, count); + defer gpa.free(ids); + for (best, values, ids) |c, *v, *id| { + v.* = c.value; + id.* = c.id; + } + return @intCast(try lanes.sampling.choose(gpa, values, ids, position, s)); +} + +/// The softmax probability of `id` in the widened row (the MTP chain's confidence cut), in double. +pub fn probability(row: []const u16, dtype: Dtype, id: u32) f64 { + var top: f64 = -std.math.inf(f64); + for (0..row.len) |i| top = @max(top, widen(row, dtype, i)); + var total: f64 = 0; + for (0..row.len) |i| total += @exp(@as(f64, widen(row, dtype, i)) - top); + return @exp(@as(f64, widen(row, dtype, id)) - top) / total; +} + +test "argmax keeps the first of equal values; bf16 and fp16 widen exactly" { + const one_bf16: u16 = 0x3f80; + const row = [_]u16{ 0, one_bf16, one_bf16, 0 }; + try std.testing.expectEqual(@as(u32, 1), argmax(&row, .bf16)); + const one_f16: u16 = 0x3c00; + try std.testing.expectEqual(@as(f32, 1.0), widen(&.{one_f16}, .f16, 0)); +} + +test "greedy draws the argmax" { + const row = [_]u16{ 0x3c00, 0x4000, 0x3e00 }; + try std.testing.expectEqual(@as(u32, 1), try draw(std.testing.allocator, &row, .f16, null, 0)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig b/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig new file mode 100644 index 00000000000..83117340c65 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/scratch.zig @@ -0,0 +1,48 @@ +//! The scratch each arena needs: the forwards themselves run on the counting stream at their largest shapes. + +const std = @import("std"); +const hip = @import("hip"); +const fwd = @import("../forward/forward.zig"); +const win = @import("../forward/window.zig"); +const pages = @import("../forward/pages.zig"); +const state = @import("../forward/state.zig"); +const plan = @import("../forward/plan.zig"); +const round = @import("round.zig"); +const Engine = @import("engine.zig").Engine; + +/// A prompt pass of `rows` rows ending at the last of `capacity` positions, then the head over its last row. +pub fn prompts(e: *Engine, rows: usize, capacity: usize) !usize { + const m = e.model(); + var pool = try pages.Pool.init(e.gpa, &e.driver, m, 1, false); + defer pool.deinit(); + var caches = try state.Caches.init(e.gpa, &pool, m, capacity); + defer caches.deinit(e.gpa); + var arena = hip.Arena.counting(); + const o = counting(e, &arena); + // every take grows with the rows and the keys walked, so the last chunk of a full window is the largest + const hidden = try fwd.span(o, m, &caches, 0, rows, capacity - rows, null); + const y = try o.project(fwd.at(hidden, (rows - 1) * m.spec.hidden), m.head, 1, false); + _ = try e.wholeRows(o, y, 1); + return arena.peak; +} + +/// A round of `rows` rows whose attention walks every position of `capacity`: snapshots, forward, whole logits. +pub fn rounds(e: *Engine, rows: usize, capacity: usize) !usize { + const m = e.model(); + const table = try e.gpa.alloc([2]u64, m.spec.n_layers); + defer e.gpa.free(table); + var arena = hip.Arena.counting(); + const o = counting(e, &arena); + try win.kept(o, m, rows, table); + const p: hip.plan_ops.Plan = .{ .args = std.mem.zeroes(@FieldType(hip.plan_ops.Plan, "args")), .rows = rows, .slots = rows + 1 }; + const r: win.Round = .{ .plan = p, .tokens = 0, .span = std.mem.alignForward(usize, capacity, plan.min_span), .inputs = table }; + const out = try round.forwardOn(o, m, r, null, 0); + _ = try e.wholeRows(o, out.y, rows); + return arena.peak; +} + +fn counting(e: *Engine, arena: *hip.Arena) hip.ops.Ops { + var o = e.ops(arena); + o.stream = hip.counting; + return o; +} diff --git a/zig/src/families/qwen3_5/backend/hip/engine/worker.zig b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig new file mode 100644 index 00000000000..c69699c93cd --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig @@ -0,0 +1,169 @@ +//! A tensor-parallel rank above 0: runs the steps rank 0 sends in the same order, so the collectives pair up. + +const std = @import("std"); +const hip = @import("hip"); +const Engine = @import("engine.zig").Engine; +const Pick = @import("engine.zig").Pick; +const state = @import("../forward/state.zig"); +const draw = @import("draw.zig"); + +/// A message's first word: rank 0 decides every match, eviction, page and slot, and a rank only applies it. +pub const Op = enum(u32) { stop, prefill, verify, keep, release, fill, pages, snap, copy }; + +/// The prefill message's snapshot slot when the pass starts from nothing. +pub const no_snapshot: u32 = std.math.maxInt(u32); + +/// Windows a round holds at most. +const max_windows = 128; + +const Fill = struct { prompt: []u32, at: usize }; + +const Lane = struct { + caches: state.Caches, + /// Slots written and kept: the next window starts here. + len: usize, + /// The prompt pass in progress: the prompt and the row it has reached. + fill: ?Fill = null, + /// The last verify's slot and rows, until rank 0's keep. + pending: ?struct { window: usize, rows: usize } = null, +}; + +pub const Worker = struct { + gpa: std.mem.Allocator, + e: *Engine, + lanes: std.AutoHashMapUnmanaged(u32, *Lane) = .empty, + reqs: []draw.Request, + out: []u32, + /// The linear snapshots of rank 0's prefix tree, in the slots it names. + snaps: state.Snapshots, + + pub fn init(gpa: std.mem.Allocator, e: *Engine) !Worker { + const rows = e.o.batch_rows; + const reqs = try gpa.alloc(draw.Request, rows); + errdefer gpa.free(reqs); + // a follower's draws are greedy and unread: the forward and its collectives are what it shares + @memset(reqs, .{ .sampling = null, .position = 0 }); + return .{ .gpa = gpa, .e = e, .reqs = reqs, .out = try gpa.alloc(u32, rows), .snaps = state.Snapshots.init(gpa, &e.driver) }; + } + + pub fn deinit(w: *Worker) void { + w.e.stream.synchronize() catch {}; + w.snaps.deinit(); + var it = w.lanes.valueIterator(); + while (it.next()) |l| w.destroy(l.*); + w.lanes.deinit(w.gpa); + w.gpa.free(w.out); + w.gpa.free(w.reqs); + } + + fn destroy(w: *Worker, l: *Lane) void { + if (l.fill) |f| w.gpa.free(f.prompt); + w.e.drain(); + l.caches.deinit(w.gpa); + w.gpa.destroy(l); + } + + fn prefill(w: *Worker, id: u32, total: usize, prompt: []const u32, at: usize, snap: ?u32, held: []const u32) !void { + const gop = try w.lanes.getOrPut(w.gpa, id); + if (gop.found_existing) w.destroy(gop.value_ptr.*); + errdefer w.lanes.removeByPtr(gop.key_ptr); + const lane = try w.gpa.create(Lane); + errdefer w.gpa.destroy(lane); + lane.* = .{ .caches = try w.e.emptyCaches(total), .len = prompt.len }; + errdefer lane.caches.deinit(w.gpa); + try lane.caches.set(w.gpa, 0, held); + if (snap) |slot| try w.snaps.put(slot, &lane.caches, w.e.stream.handle); + lane.fill = .{ .prompt = try w.gpa.dupe(u32, prompt), .at = at }; + gop.value_ptr.* = lane; + } + + /// The next chunk of a prompt pass, to row `to`: rank 0's cuts and chunk ends, run the same way. + fn fill(w: *Worker, id: u32, to: usize) !void { + const lane = w.lanes.get(id) orelse return error.UnknownStream; + const f = &(lane.fill orelse return error.NoPromptPass); + if (to == f.prompt.len) { + _ = try w.e.prefill(&lane.caches, f.prompt, f.at, null, w.reqs[0], null); + w.gpa.free(f.prompt); + lane.fill = null; + return; + } + try w.e.advance(&lane.caches, f.prompt, f.at, to, null); + f.at = to; + } + + fn laneOf(w: *Worker, id: u32) !*Lane { + return w.lanes.get(id) orelse error.UnknownStream; + } + + fn verify(w: *Worker, ids: []const u32, rows: []const Engine.Rows, pick: Pick) !void { + var total: usize = 0; + for (rows) |r| total += r.tokens.len; + _ = try w.e.choose(rows, pick); + _ = try w.e.verify(rows, w.reqs[0..total], w.out[0..total]); + for (ids, 0..) |id, i| w.lanes.get(id).?.pending = .{ .window = i, .rows = rows[i].tokens.len }; + } + + fn keep(w: *Worker, id: u32, rows: usize) !void { + const lane = w.lanes.get(id) orelse return error.UnknownStream; + const p = lane.pending orelse return error.NothingToKeep; + w.e.keep(p.window, rows); + lane.len += rows; + lane.pending = null; + } + + fn release(w: *Worker, id: u32) void { + const kv = w.lanes.fetchRemove(id) orelse return; + w.e.stream.synchronize() catch {}; + w.destroy(kv.value); + } + + /// Runs rank 0's steps until it says stop. + pub fn follow(w: *Worker, link: *const hip.link.Link) !void { + var msg: std.ArrayList(u32) = .empty; + defer msg.deinit(w.gpa); + var ids: [max_windows]u32 = undefined; + var rows: [max_windows]Engine.Rows = undefined; + while (true) { + try link.recv(w.gpa, &msg); + const m = msg.items; + switch (@as(Op, @fromBackingInt(@as(u32, @intCast(m[0]))))) { + .stop => return, + // prefill: id, positions, prompt len, resumed at, cut count, snapshot slot, page count, then the pages + .prefill => { + const held = m[8..][0..m[7]]; + // the cuts sit between the pages and the prompt + const prompt = m[8 + m[7] + m[5] ..][0..m[3]]; + try w.prefill(m[1], m[2], prompt, m[4], if (m[6] == no_snapshot) null else m[6], held); + }, + // verify: graph pick, count, then id, rows, tokens each; every rank derives the plan shape from them + .verify => { + const pick: Pick = @fromBackingInt(m[1]); + const n = m[2]; + if (n > max_windows) return error.WindowTooWide; + var at: usize = 3; + for (0..n) |i| { + const lane = w.lanes.get(m[at]) orelse return error.UnknownStream; + ids[i] = m[at]; + rows[i] = .{ .caches = &lane.caches, .pos = lane.len, .tokens = m[at + 2 ..][0..m[at + 1]] }; + at += 2 + m[at + 1]; + } + try w.verify(ids[0..n], rows[0..n], pick); + }, + // keep: count, then id and rows each + .keep => { + for (0..m[1]) |i| try w.keep(m[2 + 2 * i], m[3 + 2 * i]); + try w.e.flush(); + }, + .release => w.release(m[1]), + // fill: id, end of the prompt pass's next chunk + .fill => try w.fill(m[1], m[2]), + // pages: id, first page index, count, then the stream's table from that index on + .pages => try (try w.laneOf(m[1])).caches.set(w.gpa, m[2], m[4..][0..m[3]]), + // snap: id, slot that keeps the stream's linear state + .snap => try w.snaps.take(m[2], &(try w.laneOf(m[1])).caches, w.e.stream.handle), + // copy: from, to; page `to` becomes a copy of page `from` + .copy => try w.e.pool.copyPage(m[1], m[2], w.e.stream.handle), + } + } + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig new file mode 100644 index 00000000000..6205c2b7525 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig @@ -0,0 +1,187 @@ +//! A prompt span through every layer in steps of SPAN rows, on the prefill formulas. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const state = @import("state.zig"); +const moe = @import("moe.zig"); +const reduce = @import("reduce.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const Kind = hip.ops.Kind; + +/// Rows of one prefill step (qwen_math.SPAN). +pub const SPAN = 2048; + +pub const Error = reduce.Error || error{Cancelled}; + +pub const residual = reduce.residual; + +/// A device buffer of `n` values of `kind` from the arena. +pub fn take(o: Ops, kind: Kind, n: usize) Error!Tensor { + return .{ .ptr = try o.arena.take(n * kind.size()), .kind = kind }; +} + +/// `t` advanced by `n` values. +pub fn at(t: Tensor, n: usize) Tensor { + return .{ .ptr = t.ptr + n * t.kind.size(), .kind = t.kind }; +} + +/// Called after each layer with the residual rows (a check reads them; the forward does not wait for it). +pub const Trace = struct { + ctx: *anyopaque, + layer: *const fn (ctx: *anyopaque, index: usize, x: Tensor, rows: usize) anyerror!void, +}; + +/// The span's final-normed rows (len, hidden) in the activation dtype; `ids` are int32 token ids on the device. +pub fn span(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, len: usize, pos0: usize, trace: ?Trace) Error!Tensor { + // prefill's kernels at any row count: a prompt's rows have the same bits fresh, resumed or in steps + var o = ops; + o.prefill = true; + const s = m.spec; + const x = try take(o, m.act, len * s.hidden); + var start: usize = 0; + while (start < len) : (start += SPAN) { + const rows = @min(SPAN, len - start); + try o.embedRows(m.embed, ids + start * 4, rows, at(x, start * s.hidden)); + } + for (m.layers, 0..) |layer, index| { + start = 0; + while (start < len) : (start += SPAN) { + const rows = @min(SPAN, len - start); + const mark = o.arena.mark(); + defer o.arena.release(mark); + const xs = at(x, start * s.hidden); + const input_norm, const post_norm, const mlp = switch (layer) { + .full => |f| .{ f.input_norm, f.post_norm, f.mlp }, + .linear => |l| .{ l.input_norm, l.post_norm, l.mlp }, + }; + const normed = try take(o, m.act, rows * s.hidden); + try o.rms(xs, input_norm, normed, rows, s.hidden, @floatCast(s.eps)); + const y = switch (layer) { + .full => |f| try attention(o, m, f, caches, index, normed, rows, pos0 + start), + .linear => |l| try linear(o, m, l, caches, index, normed, rows), + }; + try residual(o, m, xs, y, rows * s.hidden); + try o.rms(xs, post_norm, normed, rows, s.hidden, @floatCast(s.eps)); + const z = try mlpRows(o, m, mlp, normed, rows, true); + try residual(o, m, xs, z, rows * s.hidden); + } + if (trace) |t| t.layer(t.ctx, index, x, len) catch |err| return if (err == error.Cancelled) error.Cancelled else error.HipFailed; + } + const out = try take(o, m.act, len * s.hidden); + try o.rms(x, m.final_norm, out, len, s.hidden, @floatCast(s.eps)); + return out; +} + +/// The attention scale, head_dim ** -0.5 in double as Python has it, passed as fp32. +pub fn scaleOf(head_dim: usize) f32 { + return @floatCast(std.math.pow(f64, @floatFromInt(head_dim), -0.5)); +} + +/// Full attention on `rows` normed rows at `pos`: q and its gate, k, v, norms, RoPE, cache write, prefill tile, o. +fn attention(o: Ops, m: *const view.Model, f: view.Full, caches: *state.Caches, index: usize, x: Tensor, rows: usize, pos: usize) Error!Tensor { + const s = m.spec; + const hd = s.head_dim; + const qg = try o.project(x, f.q, rows, false); + const keys = try o.project(x, f.k, rows, false); + const values = try o.project(x, f.v, rows, false); + const q_rows = rows * s.heads; + const qc = try take(o, m.act, q_rows * hd); + try o.copyCols(qg, 2 * hd, 0, qc.ptr, q_rows, hd); + const qn = try take(o, m.act, q_rows * hd); + try o.rms(qc, f.q_norm, qn, q_rows, hd, @floatCast(s.eps)); + const kn = try take(o, m.act, rows * s.kv_heads * hd); + try o.rms(keys, f.k_norm, kn, rows * s.kv_heads, hd, @floatCast(s.eps)); + const theta: f32 = @floatCast(s.rope_theta); + const q32 = try o.arena.of(f32, q_rows * hd); + // q rounded to the activation dtype by apply_rope, then widened for the kernel: (heads, rows, d) fp32 + try o.ropePrefill(qn, .{ .ptr = q32, .kind = .f32 }, rows * hd, hd, rows, s.heads, hd, s.rotary_dim, pos, theta); + const c = caches.paged(m, index); + // k rotated and rounded to the activation dtype as (kv_heads, rows, d), then with v into the pages from slot pos + const kr = try take(o, m.act, rows * s.kv_heads * hd); + try o.ropePrefill(kn, kr, rows * hd, hd, rows, s.kv_heads, hd, s.rotary_dim, pos, theta); + try o.pageWrite(kr.ptr, c.k, c.table, rows, s.kv_heads, hd, rows * hd, hd, pos, c.count); + try o.pageWrite(values.ptr, c.v, c.table, rows, s.kv_heads, hd, hd, s.kv_heads * hd, pos, c.count); + const att = try o.arena.of(f32, q_rows * hd); + try o.causalPaged(q32, c, att, rows, pos + rows, s.heads, scaleOf(hd), pos); + const gated = try take(o, m.act, q_rows * hd); + try o.attnGate(att, qg, gated, rows, s.heads, hd, false); + return o.project(gated, f.o, rows, f.o.partial); +} + +/// Linear attention: qkv, z, a, b, the conv over [state | rows], norms, gate, recurrence and the gated norm. +fn linear(o: Ops, m: *const view.Model, l: view.Linear, caches: *state.Caches, index: usize, x: Tensor, rows: usize) Error!Tensor { + const s = m.spec; + const qkv = try o.project(x, l.qkv, rows, false); + const z = try o.project(x, l.z, rows, false); + const a = try o.project(x, l.a, rows, false); + const b = try o.project(x, l.b, rows, false); + const cache = caches.layers[index].linear; + const ch = view.convChannels(s); + const mixed = try o.arena.of(f32, rows * ch); + // the new window lands beside the old one (every row reads the old), then replaces it + const conv_bytes = (s.conv - 1) * ch * 4; + const window = try o.arena.take(conv_bytes); + try o.convPrefill(qkv, l.conv, cache.conv.base(), mixed, window, rows, ch, s.conv); + try hip.raw.copy(cache.conv, 0, window, conv_bytes, o.stream); + const q, const k, const v = try splitQkv(o, m, .{ .ptr = mixed, .kind = .f32 }, rows); + const gate = try o.arena.of(f32, rows * s.value_heads); + const beta = try o.arena.of(f32, rows * s.value_heads); + try o.gdnGatePrefill(a, b, l.a_log, l.dt_bias, gate, beta, rows, s.value_heads); + const y = try o.arena.of(f32, rows * s.valueWidth()); + try o.gatedDelta(q, k, v, gate, beta, cache.state.base(), y, rows, s.key_heads, s.value_heads, s.key_dim, s.value_dim, null); + return gatedOut(o, m, l, y, z, rows); +} + +/// The conv output's q and k, normalized (fp32, contiguous), and v (fp32, contiguous). +pub fn splitQkv(o: Ops, m: *const view.Model, mixed: Tensor, rows: usize) Error!struct { u64, u64, u64 } { + const s = m.spec; + const kw = s.keyWidth(); + const ch = view.convChannels(s); + const qc = try o.arena.of(f32, rows * kw); + const kc = try o.arena.of(f32, rows * kw); + const v = try o.arena.of(f32, rows * s.valueWidth()); + try o.copyCols(mixed, ch, 0, qc, rows, kw); + try o.copyCols(mixed, ch, kw, kc, rows, kw); + try o.copyCols(mixed, ch, 2 * kw, v, rows, s.valueWidth()); + const q = try o.arena.of(f32, rows * kw); + const k = try o.arena.of(f32, rows * kw); + const heads = rows * s.key_heads; + try o.rms(.{ .ptr = qc, .kind = .f32 }, m.qk.q_weight, .{ .ptr = q, .kind = .f32 }, heads, s.key_dim, m.qk.eps); + try o.rms(.{ .ptr = kc, .kind = .f32 }, m.qk.k_weight, .{ .ptr = k, .kind = .f32 }, heads, s.key_dim, m.qk.eps); + return .{ q, k, v }; +} + +/// rms_norm(y, gnorm) * silu(z), rounded to the activation dtype, then the out projection. +pub fn gatedOut(o: Ops, m: *const view.Model, l: view.Linear, y: u64, z: Tensor, rows: usize) Error!Tensor { + const s = m.spec; + const n = rows * s.valueWidth(); + const out = try take(o, m.act, n); + if (o.fused() and s.value_dim <= 1024 and z.kind == m.act) { + try o.gnormOut(y, l.gnorm, z, out, rows * s.value_heads, s.value_dim, @floatCast(s.eps)); + } else { + const yn = try o.arena.of(f32, n); + try o.rms(.{ .ptr = y, .kind = .f32 }, l.gnorm, .{ .ptr = yn, .kind = .f32 }, rows * s.value_heads, s.value_dim, @floatCast(s.eps)); + try o.gnormSilu(yn, z, out, n); + } + return o.project(out, l.out, rows, l.out.partial); +} + +/// _mlp: gate and up, silu(gate) * up, down; or the routed experts (`prefill` is the span's length above one). +pub fn mlpRows(o: Ops, m: *const view.Model, mlp: view.Mlp, x: Tensor, rows: usize, prefill: bool) Error!Tensor { + switch (mlp) { + .moe => |r| return moe.run(o, m, r, x, rows, prefill and rows > 1), + .dense => |d| { + var outs: [4]Tensor = undefined; + const gate, const up = if (try o.projectGroup(x, &.{ d.gate, d.up }, rows, &outs)) + .{ outs[0], outs[1] } + else + .{ try o.project(x, d.gate, rows, false), try o.project(x, d.up, rows, false) }; + const act = try take(o, m.act, rows * d.gate.n); + try o.siluMul(gate, up, act, rows * d.gate.n); + return o.project(act, d.down, rows, d.down.partial); + }, + } +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/moe.zig b/zig/src/families/qwen3_5/backend/hip/forward/moe.zig new file mode 100644 index 00000000000..4825f72089c --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/moe.zig @@ -0,0 +1,123 @@ +//! The routed MoE of MLX affine experts: router, pick rule, plan, gate and up, activation, down, slots summed in order. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; + +/// experts.py: the decode tile's most rows, the GEMM tile's rows and where it starts, items' pair cap. +const LANE_ROWS = 8; +const BLOCK_ROWS = 128; +const BLOCK_FROM = 64; +const TILE = 16; + +/// MoEBuffers' size for `rows` rows: the next power of two from 16. +pub fn bucket(rows: usize) usize { + const bits = if (rows <= 1) 0 else std.math.log2_int_ceil(usize, rows); + return @as(usize, 1) << @intCast(@max(4, bits)); +} + +/// max_items(pairs, experts, min(TILE, LANE_ROWS)): an item a used expert plus one a tile of pairs past its first. +pub fn capacity(pairs: usize, experts: usize) usize { + return @min(pairs, experts) + pairs / @min(TILE, LANE_ROWS); +} + +/// tile_for: the decode tile below BLOCK_FROM rows, the GEMM tile from there; a lane round's rows keep the decode tile. +fn tileFor(o: Ops, rows: usize) usize { + return if (rows < BLOCK_FROM or o.window) LANE_ROWS else BLOCK_ROWS; +} + +/// `x` (rows, D) to (rows, D) in its dtype: the top-k experts plus the shared one; a tp rank returns its fp32 share. +pub fn run(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, prefill: bool) hip.ops.Error!Tensor { + _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tile comes from tile_for) + const ex = r.experts; + const slots = r.top_k + 1; + const size = bucket(rows); + const pairs = rows * slots; + const cap = capacity(size * slots, r.rows); + const logits = try o.arena.of(f32, rows * r.rows); + const pick = try o.arena.of(i32, size * slots); + const wts = try o.arena.of(f32, size * slots); + const items = try o.arena.of(i32, cap * 3); + const members = try o.arena.of(i32, size * slots); + try o.moeRouter(x, r.rows32, logits, rows, ex.dims, r.rows); + const count: usize = cap; + var tile: usize = undefined; + if (r.remap != 0) { + // every rank picks the same pairs, runs the ones it holds (the others group under an id past its experts) + try o.moeSelect(logits, pick, wts, null, 0, rows, r.count(), r.top_k); + const local = try o.arena.of(i32, size * slots); + try o.moeLocalize(pick, r.remap, local, pairs, ex.count); + tile = tileFor(o, rows); + try o.moeRoute(local, pairs, r.rows, tile, members, items, cap); + try o.moeForeignItems(items, cap, ex.count); + const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows)); + const act = try o.arena.take(pairs * ex.width * m.act.size()); + const act_t: Tensor = .{ .ptr = act, .kind = m.act }; + try o.moeAct(both, act_t, pairs, ex.width, ex.limit); + const y = try o.projectRouted(act_t, ex.down, items, count, members, pairs, 1, @min(tile, rows)); + try o.moeZeroForeign(y, local, ex.count, pairs, ex.dims); + const share = try o.arena.of(f32, rows * ex.dims); + try o.moeCombine(y, wts, .{ .ptr = share, .kind = .f32 }, rows, slots, ex.dims); + return .{ .ptr = share, .kind = .f32 }; + } + const p = try expertParts(o, m, r, x, rows, logits, pick, wts, items, members, cap); + const out = try o.arena.take(rows * ex.dims * m.act.size()); + try o.moeCombine(p.y, wts, .{ .ptr = out, .kind = m.act }, rows, slots, ex.dims); + return .{ .ptr = out, .kind = m.act }; +} + +/// The routed slots a row (fp32) and their weights before the sum: a single rank only. +pub const Parts = struct { y: u64, wts: u64, slots: usize }; + +pub fn parts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize) hip.ops.Error!Parts { + const slots = r.top_k + 1; + const size = bucket(rows); + const cap = capacity(size * slots, r.rows); + const logits = try o.arena.of(f32, rows * r.rows); + const pick = try o.arena.of(i32, size * slots); + const wts = try o.arena.of(f32, size * slots); + const items = try o.arena.of(i32, cap * 3); + const members = try o.arena.of(i32, size * slots); + try o.moeRouter(x, r.rows32, logits, rows, r.experts.dims, r.rows); + const p = try expertParts(o, m, r, x, rows, logits, pick, wts, items, members, cap); + return .{ .y = p.y, .wts = wts, .slots = slots }; +} + +/// Select, plan, gate and up, the activation and down: the rows' slots before the combine. +fn expertParts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, logits: u64, pick: u64, wts: u64, items: u64, members: u64, cap: usize) hip.ops.Error!struct { y: u64 } { + const ex = r.experts; + const slots = r.top_k + 1; + const pairs = rows * slots; + var count: usize = cap; + var tile: usize = undefined; + if (rows == 1) { + try o.moeSelect(logits, pick, wts, .{ .items = items, .members = members }, cap, 1, r.count(), r.top_k); + tile = 1; + count = slots; + } else { + try o.moeSelect(logits, pick, wts, null, 0, rows, r.count(), r.top_k); + tile = tileFor(o, rows); + try o.moeRoute(pick, pairs, r.rows, tile, members, items, cap); + } + // the gate and up's activation is the launch's epilogue when the tile takes the shape + const act_t: Tensor = if (try o.projectRoutedAct(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows), ex.limit)) |t| t else blk: { + const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows)); + const act = try o.arena.take(pairs * ex.width * m.act.size()); + const t: Tensor = .{ .ptr = act, .kind = m.act }; + try o.moeAct(both, t, pairs, ex.width, ex.limit); + break :blk t; + }; + const y = try o.projectRouted(act_t, ex.down, items, count, members, pairs, 1, @min(tile, rows)); + return .{ .y = y }; +} + +test "buffer sizes follow moe.run and max_items" { + try std.testing.expectEqual(@as(usize, 16), bucket(1)); + try std.testing.expectEqual(@as(usize, 16), bucket(16)); + try std.testing.expectEqual(@as(usize, 32), bucket(17)); + try std.testing.expectEqual(@as(usize, 2048), bucket(2048)); + try std.testing.expectEqual(@as(usize, 129 + 16 * 9 / 8), capacity(16 * 9, 129)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/pages.zig b/zig/src/families/qwen3_5/backend/hip/forward/pages.zig new file mode 100644 index 00000000000..5866102974f --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/pages.zig @@ -0,0 +1,216 @@ +//! Paged KV: attention keys and values in a pool of reference-counted pages, so streams and the prefix tree share them. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const Allocator = std.mem.Allocator; + +/// Positions a page holds: the chunk of the recurrence, so a page edge is a chunk edge. +pub const tokens = 64; + +/// Pages that hold `n` positions. +pub fn pagesFor(n: usize) usize { + return (n + tokens - 1) / tokens; +} + +/// Which page ids are free and how many holders each has: host bookkeeping only. +pub const Ids = struct { + refs: []u32, + free: std.ArrayList(u32) = .empty, + /// Pages promised to streams that have not taken them yet. + reserved: usize = 0, + + pub fn init(gpa: Allocator, count: usize) !Ids { + const refs = try gpa.alloc(u32, count); + errdefer gpa.free(refs); + @memset(refs, 0); + var ids: Ids = .{ .refs = refs }; + errdefer ids.free.deinit(gpa); + try ids.free.ensureTotalCapacity(gpa, count); + // the lowest id is taken first + var i: u32 = @intCast(count); + while (i > 0) { + i -= 1; + ids.free.appendAssumeCapacity(i); + } + return ids; + } + + pub fn deinit(ids: *Ids, gpa: Allocator) void { + ids.free.deinit(gpa); + gpa.free(ids.refs); + } + + /// A free page, now held once; null when none is free. + pub fn take(ids: *Ids) ?u32 { + const id = ids.free.pop() orelse return null; + ids.refs[id] = 1; + return id; + } + + pub fn retain(ids: *Ids, id: u32) void { + std.debug.assert(ids.refs[id] > 0); + ids.refs[id] += 1; + } + + /// One holder less; the page is free again when none is left. + pub fn release(ids: *Ids, id: u32) void { + std.debug.assert(ids.refs[id] > 0); + ids.refs[id] -= 1; + if (ids.refs[id] == 0) ids.free.appendAssumeCapacity(id); + } + + /// Pages free and not promised. + pub fn available(ids: *const Ids) usize { + return ids.free.items.len -| ids.reserved; + } + + pub fn used(ids: *const Ids) usize { + return ids.refs.len - ids.free.items.len; + } +}; + +/// Each attention layer's key and value pools and their ids: `kv_heads` runs of `count` pages, contiguous in order. +pub const Pool = struct { + gpa: Allocator, + d: *const hip.Runtime, + count: usize, + kv_heads: usize, + head_dim: usize, + act_bytes: usize, + /// A layer's keys and values: empty buffers for a linear layer. + keys: []hip.DeviceBuffer, + values: []hip.DeviceBuffer, + ids: Ids, + /// Whether this holder hands pages out (rank 0 and a lone rank); a follower is told which pages to use. + managed: bool, + + /// Device bytes a pool of `count` pages holds: keys and values of every attention layer. + pub fn deviceBytes(m: *const view.Model, count: usize) usize { + const s = m.spec; + var full: usize = 0; + for (0..s.n_layers) |i| full += @intFromBool(s.full(i)); + return 2 * full * count * s.kv_heads * tokens * s.head_dim * m.act.size(); + } + + pub fn init(gpa: Allocator, d: *const hip.Runtime, m: *const view.Model, count: usize, managed: bool) !Pool { + const s = m.spec; + const keys = try gpa.alloc(hip.DeviceBuffer, s.n_layers); + errdefer gpa.free(keys); + const values = try gpa.alloc(hip.DeviceBuffer, s.n_layers); + errdefer gpa.free(values); + var made: usize = 0; + errdefer for (0..made) |i| { + keys[i].free(); + values[i].free(); + }; + const per_layer = count * s.kv_heads * tokens * s.head_dim * m.act.size(); + for (0..s.n_layers) |i| { + const bytes = if (s.full(i)) per_layer else 0; + keys[i] = try hip.DeviceBuffer.alloc(d, bytes); + errdefer keys[i].free(); + values[i] = try hip.DeviceBuffer.alloc(d, bytes); + made += 1; + } + return .{ .gpa = gpa, .d = d, .count = count, .kv_heads = s.kv_heads, .head_dim = s.head_dim, .act_bytes = m.act.size(), .keys = keys, .values = values, .ids = try Ids.init(gpa, count), .managed = managed }; + } + + pub fn deinit(p: *Pool) void { + p.ids.deinit(p.gpa); + for (p.keys, p.values) |*k, *v| { + k.free(); + v.free(); + } + p.gpa.free(p.keys); + p.gpa.free(p.values); + } + + /// Bytes of one position's keys and values of a layer. + fn rowBytes(p: *const Pool) usize { + return p.head_dim * p.act_bytes; + } + + /// Bytes of one head's share of a page of one layer's keys (or values). + fn headBytes(p: *const Pool) usize { + return tokens * p.rowBytes(); + } + + /// Bytes of one page of one layer's keys (or values), over its heads. + pub fn layerBytes(p: *const Pool) usize { + return p.kv_heads * p.headBytes(); + } + + /// Bytes of a page over every attention layer, keys and values. + pub fn pageBytes(p: *const Pool) usize { + var layers: usize = 0; + for (p.keys) |k| layers += @intFromBool(k.len > 0); + return 2 * layers * p.layerBytes(); + } + + /// A page for one holder, or null when the pool has none. + pub fn take(p: *Pool) ?u32 { + return p.ids.take(); + } + + pub fn retain(p: *Pool, id: u32) void { + if (p.managed) p.ids.retain(id); + } + + pub fn release(p: *Pool, id: u32) void { + if (p.managed) p.ids.release(id); + } + + /// Copies page `from` into page `to` in every layer. + pub fn copyPage(p: *Pool, from: u32, to: u32, stream: hip.abi.Stream) !void { + if (from >= p.count or to >= p.count) return error.BadPage; + const n = p.headBytes(); + for (p.keys, p.values) |k, v| { + if (k.len == 0) continue; + for (0..p.kv_heads) |h| { + const run = h * p.count * n; + try hip.raw.copy(k, run + to * n, k.base() + run + from * n, n, stream); + try hip.raw.copy(v, run + to * n, v.base() + run + from * n, n, stream); + } + } + } + + /// Page `id`'s keys of layer `layer` read back, then its values, each head after head: for checks. + pub fn read(p: *const Pool, layer: usize, id: u32, out: []u8) !void { + const n = p.headBytes(); + std.debug.assert(out.len == 2 * p.layerBytes()); + for (0..p.kv_heads) |h| { + try p.keys[layer].download((h * p.count + id) * n, out[h * n ..][0..n]); + try p.values[layer].download((h * p.count + id) * n, out[(p.kv_heads + h) * n ..][0..n]); + } + } +}; + +test "ids hand out the lowest page and free it when its last holder lets go" { + var ids = try Ids.init(std.testing.allocator, 3); + defer ids.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(?u32, 0), ids.take()); + try std.testing.expectEqual(@as(?u32, 1), ids.take()); + ids.retain(0); + ids.release(0); + try std.testing.expectEqual(@as(usize, 1), ids.available()); + ids.release(0); + try std.testing.expectEqual(@as(usize, 2), ids.available()); + try std.testing.expectEqual(@as(?u32, 0), ids.take()); + try std.testing.expectEqual(@as(?u32, 2), ids.take()); + try std.testing.expectEqual(@as(?u32, null), ids.take()); +} + +test "reserved pages are not available" { + var ids = try Ids.init(std.testing.allocator, 4); + defer ids.deinit(std.testing.allocator); + ids.reserved = 3; + try std.testing.expectEqual(@as(usize, 1), ids.available()); + ids.reserved = 9; + try std.testing.expectEqual(@as(usize, 0), ids.available()); +} + +test "pages cover positions by 64" { + try std.testing.expectEqual(@as(usize, 0), pagesFor(0)); + try std.testing.expectEqual(@as(usize, 1), pagesFor(64)); + try std.testing.expectEqual(@as(usize, 2), pagesFor(65)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/plan.zig b/zig/src/families/qwen3_5/backend/hip/forward/plan.zig new file mode 100644 index 00000000000..a73a1b17733 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/plan.zig @@ -0,0 +1,141 @@ +//! A lane round's plan on the device; launches depend only on its `Shape`, so one graph serves any streams and caches. + +const std = @import("std"); +const hip = @import("hip"); +const state = @import("state.zig"); + +const round_shape = @import("round_shape.zig"); + +pub const buckets = round_shape.buckets; +pub const min_span = round_shape.min_span; +pub const bucketOf = round_shape.bucketOf; +pub const spanOf = round_shape.spanOf; +pub const Shape = round_shape.Shape; + +/// Where each array sits in the plan buffer, in 4-byte words (the 8-byte arrays on even words). +pub const Layout = struct { + layers: usize, + tokens: usize, + pos: usize, + slot: usize, + first: usize, + count: usize, + keep: usize, + desc: usize, + snaps: usize, + words: usize, + + pub fn of(rows: usize, slots: usize, layers: usize) Layout { + var l: Layout = undefined; + l.layers = layers; + l.tokens = 0; + l.pos = rows; + l.slot = 2 * rows; + l.first = 3 * rows; + l.count = l.first + slots; + l.keep = l.count + slots; + l.desc = std.mem.alignForward(usize, l.keep + slots, 2); + l.snaps = l.desc + 2 * slots; + l.words = l.snaps + 4 * layers; + return l; + } +}; + +fn put64(w: []u32, v: u64) void { + w[0] = @truncate(v); + w[1] = @truncate(v >> 32); +} + +/// One stream's window of a round: its descriptor, the slot its first row takes, its tokens. +pub const Window = struct { desc: u64, pos: usize, tokens: []const u32 }; + +/// The plan buffer of one engine, as large as its biggest round, and the pinned words a round is written in. +pub const Buffer = struct { + host: hip.HostBuffer, + dev: hip.DeviceBuffer, + /// Pages a head of a layer's pool holds: the kernels find a page's keys and values with it. + pool_pages: u32, + + /// Device bytes a plan of `rows` rows over `layers` layers holds. + pub fn deviceBytes(rows: usize, layers: usize) usize { + return 4 * Layout.of(rows, rows + 1, layers).words; + } + + pub fn init(d: *const hip.Runtime, rows: usize, layers: usize, pool_pages: usize) !Buffer { + const bytes = deviceBytes(rows, layers); + var host = try hip.HostBuffer.alloc(d, bytes); + errdefer host.free(); + return .{ .host = host, .dev = try hip.DeviceBuffer.alloc(d, bytes), .pool_pages = @intCast(pool_pages) }; + } + + pub fn deinit(b: *Buffer) void { + b.dev.free(); + b.host.free(); + } + + /// The device words of `shape` as launches read them. + pub fn args(b: *const Buffer, l: Layout) hip.plan_ops.Args { + const at = b.dev.base(); + return .{ + .pos = at + 4 * l.pos, + .slot = at + 4 * l.slot, + .first = at + 4 * l.first, + .count = at + 4 * l.count, + .desc = at + 4 * l.desc, + .snaps = at + 4 * l.snaps, + .pages = @intCast(state.header_words + 2 * l.layers), + .pool = b.pool_pages, + }; + } + + /// Writes the round into the pinned words: windows, the scratch slot's `pad` rows, each linear layer's snapshots. + pub fn fill(b: *Buffer, l: Layout, shape: Shape, windows: []const Window, scratch: u64, snaps: []const [2]u64) void { + const w = b.host.slice(u32); + const slots: usize = shape.slots; + var at: usize = 0; + for (windows, 0..) |win, s| { + w[l.first + s] = @intCast(at); + w[l.count + s] = @intCast(win.tokens.len); + w[l.keep + s] = std.math.maxInt(u32); + put64(w[l.desc + 2 * s ..], win.desc); + for (win.tokens, 0..) |t, i| { + w[l.tokens + at + i] = t; + w[l.pos + at + i] = @intCast(win.pos + i); + w[l.slot + at + i] = @intCast(s); + } + at += win.tokens.len; + } + // slots past the streams' are empty and the last is the scratch slot, where padding rows run from its start + for (windows.len..slots - 1) |s| { + w[l.first + s] = 0; + w[l.count + s] = 0; + w[l.keep + s] = std.math.maxInt(u32); + put64(w[l.desc + 2 * s ..], 0); + } + const pad = shape.rows - at; + w[l.first + slots - 1] = @intCast(at); + w[l.count + slots - 1] = @intCast(pad); + w[l.keep + slots - 1] = std.math.maxInt(u32); + put64(w[l.desc + 2 * (slots - 1) ..], scratch); + for (0..pad) |i| { + w[l.tokens + at + i] = 0; + w[l.pos + at + i] = @intCast(i); + w[l.slot + at + i] = @intCast(slots - 1); + } + for (snaps, 0..) |pair, i| { + put64(w[l.snaps + 4 * i ..], pair[0]); + put64(w[l.snaps + 4 * i + 2 ..], pair[1]); + } + } + + /// The filled words up to the device in one copy (a graph holds the copy: it runs from the same pinned words). + pub fn send(b: *const Buffer, stream: hip.abi.Stream, l: Layout) !void { + try hip.raw.upload(b.dev, 0, b.host.bytes[0 .. 4 * l.words], stream); + } +}; + +test "layout keeps the eight-byte arrays on even words" { + const l = Layout.of(5, 4, 3); + try std.testing.expect(l.desc % 2 == 0 and l.snaps % 2 == 0); + try std.testing.expect(l.words >= l.snaps + 12); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig b/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig new file mode 100644 index 00000000000..62a57811dc9 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig @@ -0,0 +1,38 @@ +//! The tensor-parallel reduce: ranks' fp32 shares summed before each residual add, logits slices joined in rank order. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; + +pub const Error = hip.ops.Error || hip.rccl.Error; + +/// `n` fp32 values summed over the ranks in rank order, so a row's sum does not depend on the rows sharing the call. +pub fn sum(o: Ops, c: hip.rccl.Comm, y: u64, n: usize) Error!u64 { + const out = try o.arena.of(f32, n); + if (c.world == 2) { + try c.allReduce(y, out, n, .f32, o.stream); + return out; + } + const parts = try o.arena.of(f32, c.world * n); + try c.allGather(y, parts, n, .f32, o.stream); + const part = n * 4; + try o.add(.{ .ptr = parts, .kind = .f32 }, .{ .ptr = parts + part, .kind = .f32 }, .{ .ptr = out, .kind = .f32 }, n); + for (2..c.world) |r| try o.add(.{ .ptr = out, .kind = .f32 }, .{ .ptr = parts + r * part, .kind = .f32 }, .{ .ptr = out, .kind = .f32 }, n); + return out; +} + +/// x += y on the residual rows: an activation-dtype `y` as one rank adds it, an fp32 share summed over the ranks first. +pub fn residual(o: Ops, m: *const view.Model, x: Tensor, y: Tensor, n: usize) Error!void { + if (y.kind != .f32) return o.add(x, y, x, n); + const total = try sum(o, m.tp.?, y.ptr, n); + try o.addWide(x, total, x, n); +} + +/// The ranks' logits slices (world, rows, width) of the activation dtype, gathered into `out`. +pub fn gather(o: Ops, c: hip.rccl.Comm, slice: Tensor, out: u64, n: usize) Error!void { + const dtype: hip.rccl.Dtype = if (slice.kind == .f16) .f16 else .bf16; + try c.allGather(slice.ptr, out, n, dtype, o.stream); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig b/zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig new file mode 100644 index 00000000000..6e11bd93cbb --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/round_shape.zig @@ -0,0 +1,37 @@ +//! What a lane round's launches depend on, so a graph captured for a shape replays for any streams of that shape. + +const std = @import("std"); + +/// Rows a round runs are padded up to one of these (and the limit), so the shapes stay few. +pub const buckets = [_]usize{ 1, 2, 4, 8, 16, 32, 64 }; + +/// Shortest span the attention walk covers; spans double from here. +pub const min_span = 128; + +/// The rows a round of `rows` real rows runs: the smallest bucket that holds them, the limit past the last bucket. +pub fn bucketOf(rows: usize, limit: usize) usize { + for (buckets) |b| if (b >= rows) return @min(b, limit); + return limit; +} + +/// The keys the attention walk covers when the longest row sees `visible`: min_span doubled until it holds them. +pub fn spanOf(visible: usize) usize { + var span: usize = min_span; + while (span < visible) span *= 2; + return span; +} + +/// A round's rows (padding included), slots (streams', empties to a bucket, then the padding's scratch slot) and keys. +pub const Shape = struct { + rows: u32, + slots: u32, + span: u32, +}; + +test "buckets round up and the span doubles" { + try std.testing.expectEqual(@as(usize, 4), bucketOf(3, 64)); + try std.testing.expectEqual(@as(usize, 32), bucketOf(17, 32)); + try std.testing.expectEqual(@as(usize, 6), bucketOf(5, 6)); + try std.testing.expectEqual(@as(usize, 128), spanOf(1)); + try std.testing.expectEqual(@as(usize, 512), spanOf(300)); +} diff --git a/zig/src/families/qwen3_5/backend/hip/forward/state.zig b/zig/src/families/qwen3_5/backend/hip/forward/state.zig new file mode 100644 index 00000000000..e3afdd1c88e --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/state.zig @@ -0,0 +1,257 @@ +//! A stream's device caches: its page table over the attention pools, and each linear layer's conv window and state. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const pages = @import("pages.zig"); +const Allocator = std.mem.Allocator; + +pub const LayerCache = union(enum) { + /// The keys and values are in the pool's pages. + full, + linear: struct { conv: hip.DeviceBuffer, state: hip.DeviceBuffer }, +}; + +/// Words of a descriptor before its layers: the positions it holds and the last kept final row. +pub const header_words = 2; + +pub const Caches = struct { + layers: []LayerCache, + /// Positions the page table can name. + total: usize, + /// Kernel view: positions, last kept final row (0 until `setHidden`), two addresses a layer, then the page table. + desc: hip.DeviceBuffer, + pool: *pages.Pool, + /// The page table as the device holds it: the pages of the first positions, each held once by this stream. + table: std.ArrayList(u32) = .empty, + /// Pages promised to this stream, not yet taken (the pool's reservation). + promised: usize = 0, + + /// Device bytes the caches of `total` positions hold beside their pages: linear state and the descriptor. + pub fn deviceBytes(m: *const view.Model, total: usize) usize { + const s = m.spec; + var linear: usize = 0; + for (0..s.n_layers) |i| linear += @intFromBool(!s.full(i)); + const conv = (s.conv - 1) * view.convChannels(s) * 4; + const state = s.value_heads * s.value_dim * s.key_dim * 4; + return linear * (conv + state) + 8 * (header_words + 2 * s.n_layers + std.mem.alignForward(usize, pages.pagesFor(total), 2) / 2); + } + + /// Caches for up to `total` positions with no pages yet; every linear byte zeroed. + pub fn init(gpa: Allocator, pool: *pages.Pool, m: *const view.Model, total: usize) !Caches { + const d = pool.d; + const s = m.spec; + const layers = try gpa.alloc(LayerCache, s.n_layers); + var made: usize = 0; + errdefer { + for (layers[0..made]) |*l| free(l); + gpa.free(layers); + } + for (layers, 0..) |*l, i| { + if (s.full(i)) { + l.* = .full; + } else { + var conv = try hip.DeviceBuffer.alloc(d, (s.conv - 1) * view.convChannels(s) * 4); + errdefer conv.free(); + var state = try hip.DeviceBuffer.alloc(d, s.value_heads * s.value_dim * s.key_dim * 4); + errdefer state.free(); + try conv.fill8(0); + try state.fill8(0); + l.* = .{ .linear = .{ .conv = conv, .state = state } }; + } + made += 1; + } + const slots = std.mem.alignForward(usize, pages.pagesFor(total), 2); + const words = try gpa.alloc(u64, header_words + 2 * s.n_layers + slots / 2); + defer gpa.free(words); + @memset(words, 0); + var desc = try hip.DeviceBuffer.alloc(d, 8 * words.len); + errdefer desc.free(); + words[0] = total; + for (layers, 0..) |l, i| switch (l) { + .full => words[header_words + 2 * i ..][0..2].* = .{ pool.keys[i].base(), pool.values[i].base() }, + .linear => |x| words[header_words + 2 * i ..][0..2].* = .{ x.conv.base(), x.state.base() }, + }; + try desc.upload(0, std.mem.sliceAsBytes(words)); + return .{ .layers = layers, .total = total, .desc = desc, .pool = pool }; + } + + /// Caches for `total` positions with every page taken now (a check or a timing, with no reservation to keep). + pub fn initFull(gpa: Allocator, pool: *pages.Pool, m: *const view.Model, total: usize) !Caches { + var c = try init(gpa, pool, m, total); + errdefer c.deinit(gpa); + _ = try c.grow(gpa, total); + return c; + } + + /// The stream's last kept final row lives at `ptr`: a round's keep copies it there. + pub fn setHidden(c: *const Caches, ptr: u64) !void { + try c.desc.upload(8, std.mem.asBytes(&ptr)); + } + + fn free(l: *LayerCache) void { + switch (l.*) { + .full => {}, + .linear => |*x| { + x.conv.free(); + x.state.free(); + }, + } + } + + /// Hands every page back (to the tree and the other streams that hold them, or to the pool) and frees the buffers. + pub fn deinit(c: *Caches, gpa: Allocator) void { + for (c.table.items) |id| c.pool.release(id); + c.pool.ids.reserved -|= c.promised; + c.table.deinit(gpa); + c.desc.free(); + for (c.layers) |*l| free(l); + gpa.free(c.layers); + c.* = undefined; + } + + /// Positions the pages cover. + pub fn covered(c: *const Caches) usize { + return @min(c.table.items.len * pages.tokens, c.total); + } + + /// Bytes this stream holds: its linear state and every page it names (shared ones counted whole). + pub fn held(c: *const Caches) usize { + var n: usize = c.table.items.len * c.pool.pageBytes(); + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| n += x.conv.len + x.state.len, + }; + return n; + } + + fn put(c: *const Caches, first: usize, ids: []const u32) !void { + const base = 8 * (header_words + 2 * c.layers.len); + try c.desc.upload(base + 4 * first, std.mem.sliceAsBytes(ids)); + } + + /// Takes pages until `n` positions are covered, counted against any promise; new ids valid until the next call. + pub fn grow(c: *Caches, gpa: Allocator, n: usize) ![]const u32 { + const want = pages.pagesFor(@min(n, c.total)); + const first = c.table.items.len; + if (want <= first) return c.table.items[first..]; + try c.table.ensureTotalCapacity(gpa, want); + errdefer c.table.shrinkRetainingCapacity(first); + while (c.table.items.len < want) c.table.appendAssumeCapacity(c.pool.take() orelse return error.OutOfPages); + const taken = want - first; + const own = @min(c.promised, taken); + c.promised -= own; + c.pool.ids.reserved -|= own; + try c.put(first, c.table.items[first..]); + return c.table.items[first..]; + } + + /// Sets the table from page `at` to `ids`; the caller's references move into it and replaced pages are released. + pub fn set(c: *Caches, gpa: Allocator, at: usize, ids: []const u32) !void { + try c.table.ensureTotalCapacity(gpa, at + ids.len); + for (ids, at..) |id, i| { + if (i < c.table.items.len) { + if (c.table.items[i] == id) { + c.pool.release(id); + continue; + } + c.pool.release(c.table.items[i]); + c.table.items[i] = id; + } else { + std.debug.assert(i == c.table.items.len); + c.table.appendAssumeCapacity(id); + } + } + try c.put(at, c.table.items[at..][0..ids.len]); + } + + /// Copies each shared page holding positions `from .. to`; `out` gets its table index, old and new page. + pub fn writable(c: *Caches, out: *std.ArrayList([3]u32), gpa: Allocator, from: usize, to: usize, stream: hip.abi.Stream) !void { + var i = from / pages.tokens; + const last = @min(pages.pagesFor(to), c.table.items.len); + while (i < last) : (i += 1) { + const old = c.table.items[i]; + if (c.pool.ids.refs[old] < 2) continue; + const fresh = c.pool.take() orelse return error.OutOfPages; + errdefer c.pool.release(fresh); + try c.pool.copyPage(old, fresh, stream); + c.table.items[i] = fresh; + c.pool.release(old); + try c.put(i, c.table.items[i..][0..1]); + try out.append(gpa, .{ @intCast(i), old, fresh }); + } + } + + /// The attention kernels' view of a full layer's pages. + pub fn paged(c: *const Caches, m: *const view.Model, index: usize) hip.ops.Ops.Paged { + const base = c.desc.base() + 8 * (header_words + 2 * c.layers.len); + return .{ .k = c.pool.keys[index].base(), .v = c.pool.values[index].base(), .table = base, .kind = m.act, .kv_heads = m.spec.kv_heads, .d = m.spec.head_dim, .count = c.pool.count }; + } + + /// Bytes of the linear layers' state. + pub fn linearBytes(c: *const Caches) usize { + var n: usize = 0; + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| n += x.conv.len + x.state.len, + }; + return n; + } +}; + +/// A stream's linear state at a prompt's page edge: each linear layer's conv window and DeltaNet state, in tree slots. +pub const Snapshots = struct { + gpa: Allocator, + d: *const hip.Runtime, + slots: std.ArrayList(?hip.DeviceBuffer) = .empty, + + pub fn init(gpa: Allocator, d: *const hip.Runtime) Snapshots { + return .{ .gpa = gpa, .d = d }; + } + + pub fn deinit(s: *Snapshots) void { + for (s.slots.items) |*b| if (b.*) |*x| x.free(); + s.slots.deinit(s.gpa); + } + + /// Frees every slot's buffer. + pub fn clear(s: *Snapshots) void { + for (s.slots.items) |*b| if (b.*) |*x| x.free(); + s.slots.clearRetainingCapacity(); + } + + /// The caches' linear state copied into slot `slot` (its buffer made on first use). + pub fn take(s: *Snapshots, slot: u32, c: *const Caches, stream: hip.abi.Stream) !void { + while (s.slots.items.len <= slot) try s.slots.append(s.gpa, null); + const entry = &s.slots.items[slot]; + if (entry.* == null) entry.* = try hip.DeviceBuffer.alloc(s.d, c.linearBytes()); + var at: usize = 0; + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| for ([_]hip.DeviceBuffer{ x.conv, x.state }) |b| { + try hip.raw.copy(entry.*.?, at, b.base(), b.len, stream); + at += b.len; + }, + }; + } + + /// Slot `slot`'s linear state copied back into the caches. + pub fn put(s: *const Snapshots, slot: u32, c: *Caches, stream: hip.abi.Stream) !void { + const buf = (if (slot < s.slots.items.len) s.slots.items[slot] else null) orelse return error.NoSnapshot; + var at: usize = 0; + for (c.layers) |l| switch (l) { + .full => {}, + .linear => |x| for ([_]hip.DeviceBuffer{ x.conv, x.state }) |b| { + try hip.raw.copy(b, 0, buf.base() + at, b.len, stream); + at += b.len; + }, + }; + } + + /// Bytes the slots hold. + pub fn held(s: *const Snapshots) usize { + var n: usize = 0; + for (s.slots.items) |b| n += if (b) |x| x.len else 0; + return n; + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/forward/window.zig b/zig/src/families/qwen3_5/backend/hip/forward/window.zig new file mode 100644 index 00000000000..46e0e6ac28f --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/forward/window.zig @@ -0,0 +1,173 @@ +//! A lane round's forward: every stream's window in one pass over the round's device plan, each row bitwise serial. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("../model/view.zig"); +const fwd = @import("forward.zig"); +const moe = @import("moe.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const pops = hip.plan_ops; + +/// A round's launches: the device plan, its token ids, the keys the attention walk covers, each layer's kept inputs. +pub const Round = struct { plan: pops.Plan, tokens: u64, span: usize, inputs: []const [2]u64 }; + +/// Whether this build and model run lane rounds: the merged decode launches, and shapes the plan kernels take. +pub fn supported(o: Ops, m: *const view.Model) bool { + const s = m.spec; + return o.fused() and s.key_dim <= 1024 and s.conv <= 8 and (s.key_dim == 128 or s.key_dim == 16) and s.value_dim % 8 == 0 and s.head_dim <= 256 and m.act != .f32; +} + +/// A linear layer's inputs a keep replays, `rows` rows: the conv inputs, then k, v, gate and beta; zero for attention. +pub fn kept(o: Ops, m: *const view.Model, rows: usize, table: [][2]u64) !void { + const s = m.spec; + for (table, 0..) |*t, index| { + t.* = .{ 0, 0 }; + if (s.full(index)) continue; + t[0] = try o.arena.of(f32, rows * view.convChannels(s)); + t[1] = try o.arena.of(f32, rows * (s.keyWidth() + s.valueWidth() + 2 * s.value_heads)); + } +} + +/// The final-normed rows of the round, in order (rows, hidden), padding rows included. +pub fn forward(ops: Ops, m: *const view.Model, r: Round, trace: ?fwd.Trace) fwd.Error!Tensor { + // a round's rows keep their decode kernels however many share it + var o = ops; + o.window = true; + const s = m.spec; + const total = r.plan.rows; + const x = try fwd.take(o, m.act, total * s.hidden); + try o.embedRows(m.embed, r.tokens, total, x); + const normed = try fwd.take(o, m.act, total * s.hidden); + const out = try fwd.take(o, m.act, total * s.hidden); + const eps: f32 = @floatCast(s.eps); + try o.rms(x, inputNorm(m.layers[0]), normed, total, s.hidden, eps); + for (m.layers, 0..) |layer, index| { + const mark = o.arena.mark(); + defer o.arena.release(mark); + const post_norm, const mlp = switch (layer) { + .full => |f| .{ f.post_norm, f.mlp }, + .linear => |l| .{ l.post_norm, l.mlp }, + }; + const y = switch (layer) { + .full => |f| try attentionRows(o, m, f, r, index, normed), + .linear => |l| try linearRows(o, m, l, r, index, normed), + }; + // the launches of a layer's two tails merge when the rows stay on this rank + const merge = o.fused() and y.kind == m.act; + const last = index + 1 == m.layers.len; + const next_norm = if (last) m.final_norm else inputNorm(m.layers[index + 1]); + const dest = if (last) out else normed; + if (merge) { + try o.addRms(x, y, post_norm, normed, total, s.hidden, eps); + } else { + try fwd.residual(o, m, x, y, total * s.hidden); + try o.rms(x, post_norm, normed, total, s.hidden, eps); + } + switch (mlp) { + .moe => |rt| if (merge and rt.remap == 0) { + const parts = try moe.parts(o, m, rt, normed, total); + try o.moeTail(x, parts.y, parts.wts, next_norm, dest, total, parts.slots, s.hidden, eps); + } else { + const z = try fwd.mlpRows(o, m, mlp, normed, total, true); + try fwd.residual(o, m, x, z, total * s.hidden); + try o.rms(x, next_norm, dest, total, s.hidden, eps); + }, + .dense => { + const z = try fwd.mlpRows(o, m, mlp, normed, total, true); + if (merge and z.kind == m.act) { + try o.addRms(x, z, next_norm, dest, total, s.hidden, eps); + } else { + try fwd.residual(o, m, x, z, total * s.hidden); + try o.rms(x, next_norm, dest, total, s.hidden, eps); + } + }, + } + if (trace) |t| t.layer(t.ctx, index, x, total) catch return error.HipFailed; + } + return out; +} + +fn inputNorm(layer: view.Layer) u64 { + return switch (layer) { + .full => |f| f.input_norm, + .linear => |l| l.input_norm, + }; +} + +/// Keeps the slots `counts` lists (negative: none): linear layers replay their kept rows, `hidden` gets the last. +pub fn keep(o: Ops, m: *const view.Model, p: pops.Plan, counts: u64, hidden: u64) hip.ops.Error!void { + const s = m.spec; + try pops.keep(o, p, .{ + .keep = counts, + .hidden = hidden, + .hidden_words = s.hidden * m.act.size() / 4, + .channels = view.convChannels(s), + .taps = s.conv - 1, + .layers = s.n_layers, + }); + try pops.gdnReplay(o, counts, p, s.key_heads, s.value_heads, s.key_dim, s.value_dim, s.n_layers); +} + +fn attentionRows(o: Ops, m: *const view.Model, f: view.Full, r: Round, index: usize, x: Tensor) fwd.Error!Tensor { + const s = m.spec; + const hd = s.head_dim; + const total = r.plan.rows; + var outs: [4]Tensor = undefined; + const qg, const keys, const values = if (try o.projectGroup(x, &.{ f.q, f.k, f.v }, total, &outs)) + .{ outs[0], outs[1], outs[2] } + else + .{ try o.project(x, f.q, total, false), try o.project(x, f.k, total, false), try o.project(x, f.v, total, false) }; + const q_rows = total * s.heads; + const eps: f32 = @floatCast(s.eps); + const theta: f32 = @floatCast(s.rope_theta); + // q and k normed, rotated and rounded in one launch; k then goes with v into the slots' caches + const q32 = try o.arena.of(f32, q_rows * hd); + try o.qkRope(qg, s.heads * 2 * hd, 2 * hd, f.q_norm, eps, total, s.heads, hd, s.rotary_dim, theta, r.plan.args.pos, q32, null, 0); + const k32 = try o.arena.of(f32, total * s.kv_heads * hd); + try o.qkRope(keys, s.kv_heads * hd, hd, f.k_norm, eps, total, s.kv_heads, hd, s.rotary_dim, theta, r.plan.args.pos, k32, null, 0); + try pops.kvWrite(o, k32, values, r.plan, index, s.kv_heads, hd); + const att = try o.arena.of(f32, q_rows * hd); + try pops.causal(o, q32, m.act, att, r.plan, index, s.heads, s.kv_heads, hd, r.span, fwd.scaleOf(hd)); + const gated = try fwd.take(o, m.act, q_rows * hd); + try o.attnGate(att, qg, gated, total, s.heads, hd, true); + return o.project(gated, f.o, total, f.o.partial); +} + +fn linearRows(o: Ops, m: *const view.Model, l: view.Linear, r: Round, index: usize, x: Tensor) fwd.Error!Tensor { + const s = m.spec; + const total = r.plan.rows; + var outs: [4]Tensor = undefined; + const qkv, const z, const a, const b = if (try o.projectGroup(x, &.{ l.qkv, l.z, l.a, l.b }, total, &outs)) + .{ outs[0], outs[1], outs[2], outs[3] } + else + .{ try o.project(x, l.qkv, total, false), try o.project(x, l.z, total, false), try o.project(x, l.a, total, false), try o.project(x, l.b, total, false) }; + const ch = view.convChannels(s); + const y = try o.arena.of(f32, total * s.valueWidth()); + // the k, v, gate and beta a keep replays live in the round's kept inputs + const kw = s.keyWidth(); + const k_kept = r.inputs[index][1]; + const vv = k_kept + 4 * total * kw; + const gate = vv + 4 * total * s.valueWidth(); + const beta = gate + 4 * total * s.value_heads; + // the cast, the conv, the split of its output and, for heads of 128, the q and k norms and the gate in one launch + const qn = try o.arena.of(f32, total * kw); + const heads128 = s.key_dim == 128 and kw % 128 == 0; + const kn = if (heads128) k_kept else try o.arena.of(f32, total * kw); + const norm: ?pops.Norm = if (heads128) .{ .q = m.qk.q_weight, .k = m.qk.k_weight, .eps = m.qk.eps } else null; + const gates: pops.Gates = .{ .a = a, .b = b, .a_log = l.a_log, .dt_bias = l.dt_bias, .gate = gate, .beta = beta, .count = total * s.value_heads, .heads = s.value_heads }; + try pops.convSplit(o, qkv, l.conv, qn, kn, vv, r.plan, index, ch, s.conv, kw, s.valueWidth(), norm, if (heads128) gates else null); + var q = qn; + var k = kn; + if (!heads128) { + const qc = try o.arena.of(f32, total * kw); + const kc = k_kept; + try o.rms2(qn, m.qk.q_weight, qc, kn, m.qk.k_weight, kc, total * s.key_heads, s.key_dim, m.qk.eps); + try o.gdnGate(a, b, l.a_log, l.dt_bias, gate, beta, total * s.value_heads, s.value_heads); + q = qc; + k = kc; + } + try pops.gatedDelta(o, q, k, vv, gate, beta, y, r.plan, index, s.key_heads, s.value_heads, s.key_dim, s.value_dim); + return fwd.gatedOut(o, m, l, y, z, total); +} diff --git a/zig/src/families/qwen3_5/backend/hip/model/bridge.zig b/zig/src/families/qwen3_5/backend/hip/model/bridge.zig new file mode 100644 index 00000000000..5b1a5e93164 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/model/bridge.zig @@ -0,0 +1,87 @@ +//! The forward's view of an uploaded model: projections, activation dtype and normalize_qk's constants. + +const std = @import("std"); +const hip = @import("hip"); +const view = @import("view.zig"); +const weights = @import("weights.zig"); + +pub const Error = error{UnsupportedTables} || hip.Error || std.mem.Allocator.Error; + +/// A projection (N, K) from its uploaded tensors, in whichever format they are. +pub fn projection(p: weights.Projection) Error!view.Projection { + return hip.quant.view(p, false); +} + +/// A projection split along K: its fp32 output is one rank's share of the sum. +fn share(p: weights.Projection, sliced: bool) Error!view.Projection { + var a = try projection(p); + a.partial = sliced; + return a; +} + +/// An uploaded MLP as the forward reads it: a dense one's projections, or the routed experts (rank share if `sliced`). +pub fn mlpView(m: weights.Mlp, sliced: bool) Error!view.Mlp { + return switch (m) { + .dense => |d| .{ .dense = .{ .gate = try projection(d.gate), .up = try projection(d.up), .down = try share(d.down, sliced) } }, + .routed => |r| .{ .moe = .{ + .rows32 = r.rows32.ptr, + .top_k = r.top_k, + .rows = r.router.dim(0), + .remap = if (r.remap) |b| b.ptr else 0, + .experts = .{ + .fused = try hip.quant.view(r.experts.fused, true), + .down = try hip.quant.view(r.experts.down, true), + .count = r.experts.count, + .width = r.experts.width, + .dims = r.experts.dims, + }, + } }, + }; +} + +pub const Bridge = struct { + gpa: std.mem.Allocator, + layers: []view.Layer, + q_weight: hip.DeviceBuffer, + k_weight: hip.DeviceBuffer, + model: view.Model, + + /// The view of `m` for activations of `act` (fp16 on RDNA2, bf16 on gfx11 / gfx12). + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, m: *const weights.Model, act: view.Kind) !*Bridge { + const s = m.spec; + const b = try gpa.create(Bridge); + errdefer gpa.destroy(b); + b.gpa = gpa; + b.layers = try gpa.alloc(view.Layer, m.layers.len); + errdefer gpa.free(b.layers); + for (m.layers, b.layers) |l, *out| out.* = switch (l) { + .full => |f| .{ .full = .{ .input_norm = f.input_norm.ptr, .post_norm = f.post_norm.ptr, .q = try projection(f.q), .k = try projection(f.k), .v = try projection(f.v), .o = try share(f.o, m.sliced), .q_norm = f.q_norm.ptr, .k_norm = f.k_norm.ptr, .mlp = try mlpView(f.mlp, m.sliced) } }, + .linear => |x| .{ .linear = .{ .input_norm = x.input_norm.ptr, .post_norm = x.post_norm.ptr, .qkv = try projection(x.qkv), .z = try projection(x.z), .a = try projection(x.a), .b = try projection(x.b), .out = try share(x.out, m.sliced), .conv = x.conv.ptr, .a_log = x.a_log.ptr, .dt_bias = x.dt_bias.ptr, .gnorm = x.gnorm.ptr, .mlp = try mlpView(x.mlp, m.sliced) } }, + }; + const c = view.qkConstants(s.key_dim, s.eps); + const qs = try gpa.alloc(f32, s.key_dim); + defer gpa.free(qs); + @memset(qs, c.q); + b.q_weight = try hip.DeviceBuffer.fromHost(d, std.mem.sliceAsBytes(qs)); + errdefer b.q_weight.free(); + @memset(qs, c.k); + b.k_weight = try hip.DeviceBuffer.fromHost(d, std.mem.sliceAsBytes(qs)); + b.model = .{ + .spec = s, + .act = act, + .embed = try projection(m.embed), + .layers = b.layers, + .final_norm = m.final_norm.ptr, + .head = try projection(m.outputHead()), + .qk = .{ .q_weight = b.q_weight.base(), .k_weight = b.k_weight.base(), .eps = c.eps }, + }; + return b; + } + + pub fn deinit(b: *Bridge) void { + b.q_weight.free(); + b.k_weight.free(); + b.gpa.free(b.layers); + b.gpa.destroy(b); + } +}; diff --git a/zig/src/families/qwen3_5/backend/hip/model/view.zig b/zig/src/families/qwen3_5/backend/hip/model/view.zig new file mode 100644 index 00000000000..e5b2f650064 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/model/view.zig @@ -0,0 +1,124 @@ +//! The device weights the forward reads: projections, fp32 norms, conv taps, DeltaNet tables, MLPs and the MTP head. + +const std = @import("std"); +const hip = @import("hip"); + +pub const Projection = hip.quant.Projection; +pub const Kind = hip.ops.Kind; + +/// The text model's dimensions (Python's Spec), as the checkpoint's config gives them. +pub const Spec = @import("../../../weights/config.zig").Spec; + +/// The conv's channels: q, k and v of the linear attention. +pub fn convChannels(s: Spec) usize { + return 2 * s.keyWidth() + s.valueWidth(); +} + +/// A layer's experts, shared expert last: gate and up stacked as one (E + 1, 2 NI, ...) weight, down (E + 1, D, ...). +pub const Experts = struct { + fused: Projection, + down: Projection, + count: usize, + width: usize, + dims: usize, + limit: f32 = 0, +}; + +/// The router's rows in fp32 (E + 1, D), the shared expert's gate last, and the experts. +pub const Routed = struct { + rows32: u64, + experts: Experts, + top_k: usize, + /// The router's rows, E + 1: the model's expert count, whatever share of the experts this rank holds. + rows: usize, + /// A rank's expert ids (int32, E + 1): each id's place among its own, -1 for another rank's; zero on one rank. + remap: u64 = 0, + + /// Routed experts, the shared one not counted. + pub fn count(r: Routed) usize { + return r.rows - 1; + } +}; + +pub const Mlp = union(enum) { + dense: struct { gate: Projection, up: Projection, down: Projection }, + moe: Routed, +}; + +pub const Full = struct { + input_norm: u64, + post_norm: u64, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + q_norm: u64, + k_norm: u64, + mlp: Mlp, +}; + +pub const Linear = struct { + input_norm: u64, + post_norm: u64, + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + out: Projection, + conv: u64, + a_log: u64, + dt_bias: u64, + gnorm: u64, + mlp: Mlp, +}; + +pub const Layer = union(enum) { full: Full, linear: Linear }; + +/// The MTP head: the Qwen3 shape (gated attention, an MLP or experts) with its own or the model's output head. +pub const Mtp = struct { + fc_e_norm: u64, + fc_h_norm: u64, + fc_e: Projection, + fc_h: Projection, + q_norm: u64, + k_norm: u64, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + final_norm: u64, + head: ?Projection, + input_norm: ?u64, + post_norm: ?u64, + mlp: ?Mlp, + gated: bool, +}; + +/// normalize_qk's constant norm weights (key_dim ** -0.5 squared for q, once for k) and its eps. +pub const QkNorm = struct { q_weight: u64, k_weight: u64, eps: f32 }; + +pub const Model = struct { + /// What this rank sees: under tp its heads and value heads. + spec: Spec, + /// The tensor-parallel communicator; null on one rank. + tp: ?hip.rccl.Comm = null, + act: Kind, + embed: Projection, + layers: []const Layer, + final_norm: u64, + head: Projection, + qk: QkNorm, + mtp: ?Mtp = null, +}; + +/// q and k's normalize_qk weights and eps exactly as Python makes them: double arithmetic, then fp32. +pub fn qkConstants(key_dim: usize, eps: f64) struct { q: f32, k: f32, eps: f32 } { + const inv = std.math.pow(f64, @floatFromInt(key_dim), -0.5); + return .{ .q = @floatCast(inv * inv), .k = @floatCast(inv), .eps = @floatCast(eps * inv * inv) }; +} + +test "normalize_qk constants for a 128-wide key" { + const c = qkConstants(128, 1e-6); + try std.testing.expectEqual(@as(f32, 0.0078125), c.q); + try std.testing.expect(@abs(c.k - 0.08838834764) < 1e-8); +} diff --git a/zig/src/families/qwen3_5/backend/hip/model/weights.zig b/zig/src/families/qwen3_5/backend/hip/model/weights.zig new file mode 100644 index 00000000000..1a2c40f8914 --- /dev/null +++ b/zig/src/families/qwen3_5/backend/hip/model/weights.zig @@ -0,0 +1,250 @@ +//! The Qwen3.5 / Qwen3.6 text model on the GPU: the Python TextModel's tensors as device buffers with their dtypes. + +const std = @import("std"); +const hip = @import("hip"); +const config = @import("../../../weights/config.zig"); +const table = @import("../../../weights/table.zig"); +const host = @import("../../../weights/host.zig"); +const checkpoint = @import("../../../weights/checkpoint.zig"); +const slicing = @import("../../../weights/slicing.zig"); + +const quant = hip.quant; +const Tensor = table.Tensor; +pub const DType = table.DType; + +/// One uploaded tensor: its device address and the element type and shape of the bytes there. +pub const Buf = quant.Buf; + +/// A projection on the device in its format: the tensors as that format keeps them. +pub const Projection = quant.Device; + +/// A layer's E + 1 experts, the shared one last; `fused` is gate then up per expert when `gated`. +pub const Experts = struct { + fused: Projection, + gated: bool, + down: Projection, + width: usize, + dims: usize, + count: usize, +}; + +/// Router rows [E + 1, D], the shared gate row last: bf16 as the Python holds them and `rows32` widened. +pub const Routed = struct { router: Buf, rows32: Buf, experts: Experts, top_k: usize, remap: ?Buf = null }; + +pub const DenseMlp = struct { gate: Projection, up: Projection, down: Projection }; + +pub const Mlp = union(enum) { dense: DenseMlp, routed: Routed }; + +pub const LinearLayer = struct { + input_norm: Buf, + post_norm: Buf, + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + conv: Buf, + a_log: Buf, + dt_bias: Buf, + gnorm: Buf, + out: Projection, + mlp: Mlp, +}; + +pub const FullLayer = struct { + input_norm: Buf, + post_norm: Buf, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + q_norm: Buf, + k_norm: Buf, + mlp: Mlp, +}; + +pub const Layer = union(enum) { linear: LinearLayer, full: FullLayer }; + +pub const MtpHead = struct { + fc_e_norm: Buf, + fc_h_norm: Buf, + fc_e: Projection, + fc_h: Projection, + q_norm: Buf, + k_norm: Buf, + q: Projection, + k: Projection, + v: Projection, + o: Projection, + final_norm: Buf, + /// `null` ties with the main model's output head. + head: ?Projection, + input_norm: ?Buf, + post_norm: ?Buf, + mlp: ?Mlp, + gated: bool, +}; + +/// Device memory of one model; every `Buf` of it is freed by `deinit`. +const Uploader = struct { + up: hip.Upload, + + fn tensor(u: Uploader, t: Tensor) !Buf { + return u.up.uploader().tensor(t); + } + + fn projection(u: Uploader, p: host.Projection) !Projection { + return quant.upload(u.up.uploader(), p); + } + + fn mlp(u: Uploader, m: host.Mlp) !Mlp { + switch (m) { + .dense => |d| return .{ .dense = .{ .gate = try u.projection(d.gate), .up = try u.projection(d.up), .down = try u.projection(d.down) } }, + .routed => |r| { + const e = r.experts; + return .{ .routed = .{ + .router = try u.tensor(r.router), + .rows32 = try u.tensor(r.rows32), + .experts = .{ + .fused = try u.projection(e.fused), + .gated = e.gated, + .down = try u.projection(e.down), + .width = e.width, + .dims = e.dims, + .count = e.count, + }, + .top_k = r.top_k, + .remap = if (r.remap) |t| try u.tensor(t) else null, + } }; + }, + } + } + + fn layer(u: Uploader, l: host.Layer) !Layer { + switch (l.body) { + .linear => |x| return .{ .linear = .{ + .input_norm = try u.tensor(x.input_norm), + .post_norm = try u.tensor(x.post_norm), + .qkv = try u.projection(x.qkv), + .z = try u.projection(x.z), + .a = try u.projection(x.a), + .b = try u.projection(x.b), + .conv = try u.tensor(x.conv), + .a_log = try u.tensor(x.a_log), + .dt_bias = try u.tensor(x.dt_bias), + .gnorm = try u.tensor(x.gnorm), + .out = try u.projection(x.out), + .mlp = try u.mlp(x.mlp), + } }, + .full => |x| return .{ .full = .{ + .input_norm = try u.tensor(x.input_norm), + .post_norm = try u.tensor(x.post_norm), + .q = try u.projection(x.q), + .k = try u.projection(x.k), + .v = try u.projection(x.v), + .o = try u.projection(x.o), + .q_norm = try u.tensor(x.q_norm), + .k_norm = try u.tensor(x.k_norm), + .mlp = try u.mlp(x.mlp), + } }, + } + } + + fn mtp(u: Uploader, m: host.Mtp) !MtpHead { + return .{ + .fc_e_norm = try u.tensor(m.fc_e_norm), + .fc_h_norm = try u.tensor(m.fc_h_norm), + .fc_e = try u.projection(m.fc_e), + .fc_h = try u.projection(m.fc_h), + .q_norm = try u.tensor(m.q_norm), + .k_norm = try u.tensor(m.k_norm), + .q = try u.projection(m.q), + .k = try u.projection(m.k), + .v = try u.projection(m.v), + .o = try u.projection(m.o), + .final_norm = try u.tensor(m.final_norm), + .head = if (m.head) |h| try u.projection(h) else null, + .input_norm = if (m.input_norm) |n| try u.tensor(n) else null, + .post_norm = if (m.post_norm) |n| try u.tensor(n) else null, + .mlp = if (m.mlp) |x| try u.mlp(x) else null, + .gated = m.gated, + }; + } +}; + +pub const Model = struct { + gpa: std.mem.Allocator, + spec: config.Spec, + buffers: std.ArrayList(hip.DeviceBuffer) = .empty, + embed: Projection = undefined, + layers: []Layer = &.{}, + final_norm: Buf = undefined, + /// `null` ties the output head with `embed`. + head: ?Projection = null, + mtp: ?MtpHead = null, + /// A tensor-parallel rank's share: the output projections hold fp32 shares of a sum. + sliced: bool = false, + + /// The text tower of the checkpoint in `dir`, one layer at a time through host memory. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const hip.Runtime, dir: []const u8) !Model { + return loadRank(gpa, io, d, dir, null); + } + + /// As `load`, keeping only tensor-parallel rank `rank`'s share (null: the whole model). + pub fn loadRank(gpa: std.mem.Allocator, io: std.Io, d: *const hip.Runtime, dir: []const u8, rank: ?slicing.Rank) !Model { + var ck = try checkpoint.Checkpoint.open(gpa, io, dir); + defer ck.close(); + return fromCheckpointRank(gpa, d, &ck, std.math.maxInt(usize), rank); + } + + /// The first `limit` layers of `ck` (all when `limit` is large), with the MTP head only when every layer loads. + pub fn fromCheckpoint(gpa: std.mem.Allocator, d: *const hip.Runtime, ck: *const checkpoint.Checkpoint, limit: usize) !Model { + return fromCheckpointRank(gpa, d, ck, limit, null); + } + + /// `fromCheckpoint` for one tensor-parallel rank, `spec` being what that rank sees. + pub fn fromCheckpointRank(gpa: std.mem.Allocator, d: *const hip.Runtime, ck: *const checkpoint.Checkpoint, limit: usize, rank: ?slicing.Rank) !Model { + const whole = ck.spec(); + var m: Model = .{ .gpa = gpa, .spec = if (rank) |r| try slicing.localSpec(whole, r) else whole, .sliced = rank != null }; + errdefer m.deinit(); + const u: Uploader = .{ .up = .{ .r = d, .buffers = &m.buffers, .gpa = gpa } }; + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + m.embed = try u.projection(embed); + m.final_norm = try u.tensor(try ck.finalNorm(scratch.allocator())); + const head = try ck.head(scratch.allocator()); + if (rank) |r| { + m.head = try u.projection(try slicing.vocabRows(scratch.allocator(), head orelse embed, whole.vocab, r)); + } else if (head) |h| m.head = try u.projection(h); + var list: std.ArrayList(Layer) = .empty; + errdefer list.deinit(gpa); + for (0..@min(limit, m.spec.n_layers)) |i| { + var host_layer = try ck.layer(i); + defer host_layer.deinit(); + if (rank) |r| try slicing.layer(&host_layer, whole, r); + try list.append(gpa, try u.layer(host_layer)); + } + m.layers = try list.toOwnedSlice(gpa); + // under tp only rank 0 drafts: its head is whole, logits rows included (its own or the model's whole head) + const drafts = if (rank) |r| r.rank == 0 else true; + if (drafts and m.layers.len == m.spec.n_layers) if (try ck.mtp()) |head_layer| { + var h = head_layer; + defer h.deinit(); + if (rank != null and h.head == null) h.head = head orelse embed; + m.mtp = try u.mtp(h); + }; + return m; + } + + /// The output head: the embedding itself when the checkpoint ties them. + pub fn outputHead(m: *const Model) Projection { + return m.head orelse m.embed; + } + + pub fn deinit(m: *Model) void { + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + m.gpa.free(m.layers); + m.* = undefined; + } +}; diff --git a/zig/src/families/qwen3_5/hip.zig b/zig/src/families/qwen3_5/hip.zig new file mode 100644 index 00000000000..a6a583a4ba4 --- /dev/null +++ b/zig/src/families/qwen3_5/hip.zig @@ -0,0 +1,56 @@ +//! Qwen3.5 / Qwen3.6 text checkpoints for the native HIP engine: configuration, host index and upload. + +pub const config = @import("weights/config.zig"); +pub const table = @import("weights/table.zig"); +pub const host = @import("weights/host.zig"); +pub const checkpoint = @import("weights/checkpoint.zig"); +pub const weights = @import("backend/hip/model/weights.zig"); +pub const Config = config.Config; +pub const Spec = config.Spec; +pub const Checkpoint = checkpoint.Checkpoint; +pub const Model = weights.Model; +pub const view = @import("backend/hip/model/view.zig"); +pub const state = @import("backend/hip/forward/state.zig"); +pub const pages = @import("backend/hip/forward/pages.zig"); +pub const forward = @import("backend/hip/forward/forward.zig"); +pub const window = @import("backend/hip/forward/window.zig"); +pub const plan = @import("backend/hip/forward/plan.zig"); +pub const moe = @import("backend/hip/forward/moe.zig"); +pub const sample = @import("backend/hip/engine/sample.zig"); +pub const draw = @import("backend/hip/engine/draw.zig"); +pub const bridge = @import("backend/hip/model/bridge.zig"); +pub const engine = @import("backend/hip/engine/engine.zig"); +pub const memory = @import("backend/hip/engine/memory.zig"); +pub const prefix = @import("backend/hip/engine/prefix.zig"); +pub const radix = @import("engine_api").prompt_radix; +pub const hip_lanes = @import("backend/hip/engine/hip_lanes.zig"); +pub const mtp = @import("backend/hip/engine/mtp.zig"); +pub const worker = @import("backend/hip/engine/worker.zig"); +pub const slicing = @import("weights/slicing.zig"); +pub const reduce = @import("backend/hip/forward/reduce.zig"); +pub const native_engine = @import("backend/hip/engine/native.zig"); +/// The registry entries of the native server: the dense and the sparse checkpoints. +pub const native = native_engine.Native("qwen3_5"); +pub const native_moe = native_engine.Native("qwen3_5_moe"); + +test { + _ = config; + _ = table; + _ = @import("weights/shard.zig"); + _ = @import("weights/projection.zig"); + _ = @import("weights/checkpoint_test.zig"); + _ = @import("weights/real_test.zig"); + _ = view; + _ = moe; + _ = sample; + _ = prefix; + _ = radix; + _ = native_engine; + _ = pages; + _ = plan; + _ = slicing; + // the engine and its workers compile on a host with no GPU + @import("std").testing.refAllDecls(hip_lanes.Hip); + @import("std").testing.refAllDecls(worker.Worker); + @import("std").testing.refAllDecls(engine.Engine); +} diff --git a/zig/src/hip/admission.zig b/zig/src/hip/admission.zig new file mode 100644 index 00000000000..2082b5b49de --- /dev/null +++ b/zig/src/hip/admission.zig @@ -0,0 +1,65 @@ +//! What the HIP engine may serve: the CUDA path's memory rules (cuda_memory.zig) and the window and weights it reads. +const std = @import("std"); +const memory = @import("cuda_memory"); +const Allocator = std.mem.Allocator; + +pub const MemInfo = memory.MemInfo; +pub const Pool = memory.Pool; +pub const meminfo = memory.meminfo; +pub const reserveBytes = memory.reserveBytes; +pub const limitBytes = memory.limitBytes; +pub const admit = memory.admit; +pub const counts = memory.counts; + +/// The model's window (config.json's max_position_embeddings, text_config's first), 0 when it names none. +pub fn modelContext(a: Allocator, io: std.Io, dir: []const u8) i64 { + const path = std.fs.path.join(a, &.{ dir, "config.json" }) catch return 0; + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)) catch return 0; + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}) catch return 0; + if (doc != .object) return 0; + const text = if (doc.object.get("text_config")) |t| (if (t == .object) t else doc) else doc; + const limit = text.object.get("max_position_embeddings") orelse doc.object.get("max_position_embeddings") orelse return 0; + return if (limit == .integer and limit.integer > 0) limit.integer else 0; +} + +/// Prompt plus reply tokens a request may use: --context (0: the model's window), else the family default within it. +pub fn contextWindow(requested: ?i64, native: i64, default: i64) error{ Negative, NoNative, PastNative }!i64 { + const r = requested orelse return if (native > 0) @min(default, native) else default; + if (r < 0) return error.Negative; + if (r == 0) return if (native > 0) native else error.NoNative; + if (native > 0 and r > native) return error.PastNative; + return r; +} + +/// The bytes of the checkpoint's safetensors files: what its weights need on the device, near enough to refuse early. +pub fn weightBytes(io: std.Io, dir: []const u8) u64 { + var d = std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var total: u64 = 0; + var it = d.iterate(); + while (it.next(io) catch null) |e| { + if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; + const st = d.statFile(io, e.name, .{}) catch continue; + total += st.size; + } + return total; +} + +/// A /proc file's text, streamed: procfs reports size 0, and a positional read (readFileAlloc) stops there. +pub fn procText(a: Allocator, io: std.Io, path: []const u8) ?[]u8 { + var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null; + defer file.close(io); + var buf: [4096]u8 = undefined; + var r = file.readerStreaming(io, &buf); + return r.interface.allocRemaining(a, .limited(1 << 20)) catch null; +} + +test "context windows: the family default inside the model's, 0 for the model's, never past it" { + try std.testing.expectEqual(@as(i64, 16384), try contextWindow(null, 262144, 16384)); + try std.testing.expectEqual(@as(i64, 4096), try contextWindow(null, 4096, 16384)); + try std.testing.expectEqual(@as(i64, 262144), try contextWindow(0, 262144, 16384)); + try std.testing.expectEqual(@as(i64, 65536), try contextWindow(65536, 262144, 16384)); + try std.testing.expectError(error.PastNative, contextWindow(300000, 262144, 16384)); + try std.testing.expectError(error.Negative, contextWindow(-5, 262144, 16384)); + try std.testing.expectError(error.NoNative, contextWindow(0, 0, 16384)); +} diff --git a/zig/src/hip/comm/group.zig b/zig/src/hip/comm/group.zig new file mode 100644 index 00000000000..9be68e2b7fd --- /dev/null +++ b/zig/src/hip/comm/group.zig @@ -0,0 +1,36 @@ +//! The ranks of a tensor-parallel group: the TCP link that carries rank 0's steps and RCCL's unique id. + +const std = @import("std"); +const rccl_mod = @import("rccl.zig"); +const link_mod = @import("link.zig"); +const Caps = @import("../caps.zig").Caps; +const Policy = @import("../policy.zig").Policy; + +pub const Error = link_mod.Error || error{ NoRccl, NoId }; + +/// RCCL's library stays loaded until the group is closed (its bootstrap thread starts at the id). +pub const Group = struct { + rccl: rccl_mod.Rccl, + link: link_mod.Link, + id: rccl_mod.UniqueId, + + /// Rank 0 listens on `master`:`port`, sends its id and policy; a rank whose GPU differs from rank 0's is refused. + pub fn join(gpa: std.mem.Allocator, io: std.Io, rank: u32, world: u32, master: []const u8, port: u16, caps: Caps, policy: *Policy) Error!*Group { + const g = try gpa.create(Group); + errdefer gpa.destroy(g); + g.rccl = rccl_mod.Rccl.open(policy.rccl_lib.slice()) catch return error.NoRccl; + errdefer g.rccl.close(); + const mine: rccl_mod.UniqueId = if (rank == 0) g.rccl.uniqueId() catch return error.NoId else undefined; + const host = if (std.mem.eql(u8, master, "localhost")) "127.0.0.1" else master; + const pair = try link_mod.Link.open(io, rank, world, host, port, mine, .{ .caps = @import("../device.zig").Device.groupId(caps), .policy = policy.words() }); + g.link, g.id, const hello = pair; + if (rank != 0) policy.* = Policy.fromWords(hello.policy, policy.*); + return g; + } + + pub fn close(g: *Group, gpa: std.mem.Allocator) void { + g.link.close(); + g.rccl.close(); + gpa.destroy(g); + } +}; diff --git a/zig/src/hip/comm/link.zig b/zig/src/hip/comm/link.zig new file mode 100644 index 00000000000..0ec403f56b5 --- /dev/null +++ b/zig/src/hip/comm/link.zig @@ -0,0 +1,136 @@ +//! The ranks' TCP link: rank 0 listens, the others connect once, get the communicator's id, take rank 0's commands. + +const std = @import("std"); +const posix = std.posix; +const rccl = @import("rccl.zig"); +const Policy = @import("../policy.zig").Policy; + +pub const Error = error{ SocketFailed, BindFailed, ConnectFailed, LinkClosed, BadRank, MixedGpus } || std.mem.Allocator.Error; + +pub const max_world = 16; + +/// What the ranks agree on at join: the kernels' GPU id (every rank's must match) and rank 0's policy. +pub const Hello = struct { caps: u32, policy: [Policy.word_count]u32 }; + +pub const Link = struct { + rank: usize, + world: usize, + /// Rank 0: the follower of rank r + 1 at index r. A follower: rank 0's socket at index 0. + fds: [max_world - 1]posix.socket_t = undefined, + + /// Rank 0 listens on `host:port`, sends each rank `id` and `hello`; a GPU that differs from rank 0's is refused. + pub fn open(io: std.Io, rank: usize, world: usize, host: []const u8, port: u16, id: rccl.UniqueId, hello: Hello) Error!struct { Link, rccl.UniqueId, Hello } { + if (world < 2 or world > max_world or rank >= world) return error.BadRank; + const ip = std.Io.net.IpAddress.parse(host, port) catch return error.ConnectFailed; + if (ip != .ip4) return error.ConnectFailed; + var addr: posix.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port), .addr = std.mem.readInt(u32, &ip.ip4.bytes, .little) }; + var link: Link = .{ .rank = rank, .world = world }; + if (rank == 0) { + const server = try socket(); + defer _ = posix.system.close(server); + const one: c_int = 1; + posix.setsockopt(server, posix.SOL.SOCKET, posix.SO.REUSEADDR, std.mem.asBytes(&one)) catch return error.SocketFailed; + if (posix.errno(posix.system.bind(server, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) != .SUCCESS) return error.BindFailed; + if (posix.errno(posix.system.listen(server, 16)) != .SUCCESS) return error.BindFailed; + var seen: usize = 0; + while (seen < world - 1) : (seen += 1) { + const rc = posix.system.accept(server, null, null); + if (posix.errno(rc) != .SUCCESS) return error.SocketFailed; + const fd: posix.socket_t = @intCast(rc); + var peer: u32 = undefined; + try readAll(fd, std.mem.asBytes(&peer)); + var caps: u32 = undefined; + try readAll(fd, std.mem.asBytes(&caps)); + if (peer == 0 or peer >= world) return error.BadRank; + link.fds[peer - 1] = fd; + const status: u32 = if (caps == hello.caps) 0 else 1; + try writeAll(fd, std.mem.asBytes(&status)); + if (status != 0) return error.MixedGpus; + try writeAll(fd, std.mem.asBytes(&id)); + try writeAll(fd, std.mem.sliceAsBytes(&hello.policy)); + } + return .{ link, id, hello }; + } + var tries: usize = 0; + while (true) : (tries += 1) { + const fd = try socket(); + if (posix.errno(posix.system.connect(fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) == .SUCCESS) { + link.fds[0] = fd; + break; + } + _ = posix.system.close(fd); + if (tries >= 6000) return error.ConnectFailed; + std.Io.sleep(io, .fromMilliseconds(100), .awake) catch {}; + } + const mine: u32 = @intCast(rank); + try writeAll(link.fds[0], std.mem.asBytes(&mine)); + try writeAll(link.fds[0], std.mem.asBytes(&hello.caps)); + var status: u32 = undefined; + try readAll(link.fds[0], std.mem.asBytes(&status)); + if (status != 0) return error.MixedGpus; + var got: rccl.UniqueId = undefined; + try readAll(link.fds[0], std.mem.asBytes(&got)); + var theirs: Hello = .{ .caps = hello.caps, .policy = undefined }; + try readAll(link.fds[0], std.mem.sliceAsBytes(&theirs.policy)); + return .{ link, got, theirs }; + } + + pub fn close(l: *Link) void { + const n = if (l.rank == 0) l.world - 1 else 1; + for (l.fds[0..n]) |fd| _ = posix.system.close(fd); + } + + /// Rank 0: `words` to every follower, behind their count. + pub fn send(l: *const Link, words: []const u32) Error!void { + const n: u32 = @intCast(words.len); + for (l.fds[0 .. l.world - 1]) |fd| { + try writeAll(fd, std.mem.asBytes(&n)); + try writeAll(fd, std.mem.sliceAsBytes(words)); + } + } + + /// A follower: rank 0's next message, appended to `out` (cleared first). + pub fn recv(l: *const Link, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) Error!void { + var n: u32 = undefined; + try readAll(l.fds[0], std.mem.asBytes(&n)); + out.clearRetainingCapacity(); + try out.resize(gpa, n); + try readAll(l.fds[0], std.mem.sliceAsBytes(out.items)); + } +}; + +fn socket() Error!posix.socket_t { + const rc = posix.system.socket(posix.AF.INET, posix.SOCK.STREAM, 0); + if (posix.errno(rc) != .SUCCESS) return error.SocketFailed; + const fd: posix.socket_t = @intCast(rc); + const one: c_int = 1; + posix.setsockopt(fd, posix.IPPROTO.TCP, posix.TCP.NODELAY, std.mem.asBytes(&one)) catch {}; + return fd; +} + +fn writeAll(fd: posix.socket_t, bytes: []const u8) Error!void { + var at: usize = 0; + while (at < bytes.len) { + const rc = posix.system.write(fd, bytes[at..].ptr, bytes.len - at); + switch (posix.errno(rc)) { + .SUCCESS => at += @intCast(rc), + .INTR => {}, + else => return error.LinkClosed, + } + } +} + +fn readAll(fd: posix.socket_t, bytes: []u8) Error!void { + var at: usize = 0; + while (at < bytes.len) { + const rc = posix.system.read(fd, bytes[at..].ptr, bytes.len - at); + switch (posix.errno(rc)) { + .SUCCESS => { + if (rc == 0) return error.LinkClosed; + at += @intCast(rc); + }, + .INTR => {}, + else => return error.LinkClosed, + } + } +} diff --git a/zig/src/hip/comm/rccl.zig b/zig/src/hip/comm/rccl.zig new file mode 100644 index 00000000000..74ff5e6544e --- /dev/null +++ b/zig/src/hip/comm/rccl.zig @@ -0,0 +1,125 @@ +//! RCCL opened at run time: the tensor-parallel forward's collectives on our streams, as hand-declared exports. + +const std = @import("std"); +const abi = @import("../abi.zig"); + +pub const Error = error{ RcclUnavailable, MissingSymbol, RcclFailed, Invalid }; + +/// ncclUniqueId: the opaque 128 bytes rank 0 makes and every rank passes to its init. +pub const UniqueId = extern struct { internal: [128]u8 }; + +/// ncclDataType_t, RCCL's numbering. +pub const Dtype = enum(c_int) { u8 = 1, i32 = 2, i64 = 4, f16 = 6, f32 = 7, bf16 = 9 }; + +const Handle = ?*anyopaque; +const C = ?*const anyopaque; +const P = ?*anyopaque; + +/// Each field is the library's exact export. +const Api = struct { + ncclGetErrorString: *const fn (c_int) callconv(.c) [*:0]const u8, + ncclGetUniqueId: *const fn (*UniqueId) callconv(.c) c_int, + ncclCommInitRank: *const fn (*Handle, c_int, UniqueId, c_int) callconv(.c) c_int, + ncclCommDestroy: *const fn (Handle) callconv(.c) c_int, + ncclAllReduce: *const fn (C, P, usize, c_int, c_int, Handle, abi.Stream) callconv(.c) c_int, + ncclAllGather: *const fn (C, P, usize, c_int, Handle, abi.Stream) callconv(.c) c_int, + ncclBroadcast: *const fn (C, P, usize, c_int, c_int, Handle, abi.Stream) callconv(.c) c_int, +}; + +const paths = [_][]const u8{ "librccl.so.1", "librccl.so", "/opt/rocm/lib/librccl.so.1" }; + +/// ncclSum: the only reduction the forward uses. +const sum_op: c_int = 0; + +pub const Rccl = struct { + lib: std.DynLib, + api: Api, + + /// `first` (the policy's `rccl_lib`) is tried before the usual places. + pub fn open(first: ?[]const u8) Error!Rccl { + var candidates: [paths.len + 1][]const u8 = undefined; + var n: usize = 0; + if (first) |path| { + candidates[0] = path; + n = 1; + } + for (paths) |path| { + candidates[n] = path; + n += 1; + } + for (candidates[0..n]) |path| { + var lib = std.DynLib.open(path) catch continue; + errdefer lib.close(); + var api: Api = undefined; + const info = @typeInfo(Api).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + @field(api, name) = lib.lookup(T, name) orelse { + std.log.err("{s} has no {s}", .{ path, name }); + return error.MissingSymbol; + }; + } + return .{ .lib = lib, .api = api }; + } + return error.RcclUnavailable; + } + + pub fn close(r: *Rccl) void { + r.lib.close(); + } + + fn check(r: *const Rccl, code: c_int, what: []const u8) Error!void { + if (code == 0) return; + std.log.err("{s}: RCCL error {d}: {s}", .{ what, code, std.mem.span(r.api.ncclGetErrorString(code)) }); + return error.RcclFailed; + } + + /// A fresh id; rank 0 makes it and hands it to the others. + pub fn uniqueId(r: *const Rccl) Error!UniqueId { + var id: UniqueId = undefined; + try r.check(r.api.ncclGetUniqueId(&id), "ncclGetUniqueId"); + return id; + } +}; + +/// One rank's communicator. Collectives queue on the stream they are given and wait for every rank's matching call. +pub const Comm = struct { + rccl: *const Rccl, + handle: Handle, + rank: usize, + world: usize, + + /// Joins the ranks; blocks until all `world` have called it with the same `id`. The device is current already. + pub fn init(rccl: *const Rccl, id: UniqueId, rank: usize, world: usize) Error!Comm { + if (world < 2 or rank >= world) return error.Invalid; + var h: Handle = null; + try rccl.check(rccl.api.ncclCommInitRank(&h, @intCast(world), id, @intCast(rank)), "ncclCommInitRank"); + return .{ .rccl = rccl, .handle = h, .rank = rank, .world = world }; + } + + pub fn deinit(c: *Comm) void { + _ = c.rccl.api.ncclCommDestroy(c.handle); + c.* = undefined; + } + + /// `recv` = the ranks' `send` summed, `n` values of `dtype` (sum of two ranks is the one add, any order). + pub fn allReduce(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + if (stream == @import("../launches/util.zig").counting) return; + try c.rccl.check(c.rccl.api.ncclAllReduce(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), sum_op, c.handle, stream), "ncclAllReduce"); + } + + /// `recv` (world * n values) = every rank's `send` (n values) in rank order. + pub fn allGather(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + if (stream == @import("../launches/util.zig").counting) return; + try c.rccl.check(c.rccl.api.ncclAllGather(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), c.handle, stream), "ncclAllGather"); + } + + /// `root`'s `send` into every rank's `recv`, `n` values. + pub fn broadcast(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void { + if (stream == @import("../launches/util.zig").counting) return; + try c.rccl.check(c.rccl.api.ncclBroadcast(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), @intCast(root), c.handle, stream), "ncclBroadcast"); + } +}; + +test "the unique id is the 128 bytes RCCL passes by value" { + try std.testing.expectEqual(@as(usize, 128), @sizeOf(UniqueId)); +} diff --git a/zig/src/hip/device.zig b/zig/src/hip/device.zig new file mode 100644 index 00000000000..7ffe2d982ea --- /dev/null +++ b/zig/src/hip/device.zig @@ -0,0 +1,70 @@ +//! The GPU a rank serves on and what the run may use there, chosen once by whoever opens an engine. + +const std = @import("std"); +const runtime = @import("runtime.zig"); +const kernels = @import("kernels.zig"); +const Caps = @import("caps.zig").Caps; +const Policy = @import("policy.zig").Policy; +const Group = @import("comm/group.zig").Group; + +pub const Device = struct { + /// The ordinal among the visible cards. + index: c_int, + caps: Caps, + /// Rank 0's policy; the other ranks adopt it when they join the group. + policy: Policy, + /// The tensor-parallel group this rank belongs to (null: one rank). + group: ?*Group = null, + + /// The card of `rank`: with every card visible rank r takes card r, with one card a process that card. + pub fn ordinal(rank: u32) c_int { + var r = runtime.Runtime.open() catch return 0; + defer r.close(); + const count = r.deviceCount() catch return 0; + return if (count > 0) @intCast(rank % @as(u32, @intCast(count))) else 0; + } + + /// The caps of the card at `index` when this build's kernels were compiled for it; refused otherwise. + pub fn kernelCaps(r: *runtime.Runtime, index: c_int) error{ UnsupportedGpu, KernelArch }!Caps { + var buf: [64]u8 = undefined; + const arch = archName(r, index, &buf) catch return error.UnsupportedGpu; + const caps = Caps.of(arch) orelse return error.UnsupportedGpu; + const end = std.mem.indexOfScalar(u8, arch, ':') orelse arch.len; + if (!std.mem.eql(u8, arch[0..end], kernels.arch)) { + std.log.err("this GPU is {s}; this build's kernels are for {s} (-Dhip-arch)", .{ arch[0..end], kernels.arch }); + return error.KernelArch; + } + return caps; + } + + /// What every rank of a group must share: the GPU its kernels were built for. + pub fn groupId(caps: Caps) u32 { + return std.hash.Crc32.hash(kernels.arch) ^ @as(u32, @backingInt(caps.generation)); + } + + /// What the card at `index` can do, or null when it is no usable GPU or one outside the caps table. + pub fn capsOf(index: c_int) ?Caps { + var r = runtime.Runtime.open() catch return null; + defer r.close(); + var buf: [64]u8 = undefined; + const arch = archName(&r, index, &buf) catch return null; + return Caps.of(arch); + } + + /// The card's gfx name ("gfx1100", "gfx906:sramecc+:xnack-"), found in its properties record by its prefix. + pub fn archName(r: *runtime.Runtime, index: c_int, out: []u8) runtime.Error![]const u8 { + const Properties = *const fn (*anyopaque, c_int) callconv(.c) c_int; + const get = r.lib.lookup(Properties, "hipGetDevicePropertiesR0600") orelse return error.MissingSymbol; + var props: [16384]u8 align(8) = @splat(0); + try runtime.check(get(&props, index)); + var at: usize = 256; + while (at + 4 < props.len) : (at += 1) { + if (!std.mem.startsWith(u8, props[at..], "gfx") or !std.ascii.isHex(props[at + 3])) continue; + const text = std.mem.sliceTo(props[at..], 0); + if (text.len > out.len) return error.Invalid; + @memcpy(out[0..text.len], text); + return out[0..text.len]; + } + return error.Invalid; + } +}; diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig new file mode 100644 index 00000000000..49093cc7b3c --- /dev/null +++ b/zig/src/hip/policy.zig @@ -0,0 +1,248 @@ +//! What a run may use, resolved once at open; nothing below the engine reads the environment, it reads this. + +const std = @import("std"); +const Launcher = @import("launches.zig").Launcher; +const affine = @import("launches/affine.zig"); + +pub const Choice = enum { auto, on, off }; +/// The prefill attention tile: `f32` keeps the one-row kernel. +pub const Attention = enum { auto, f32 }; +/// One kernel family switched to its reference, apart from `kernels=reference` that switches them all. +pub const Pick = enum { auto, reference }; + +/// MTP drafting: `--mtp-drafts` and `--mtp-confidence`. +pub const Mtp = struct { drafts: u8 = 3, confidence: f64 = 0.3 }; + +/// A path a rank reads locally (it never travels with the policy). +pub const Path = struct { + buf: [160]u8 = @splat(0), + + pub fn slice(p: *const Path) ?[]const u8 { + const n = std.mem.indexOfScalar(u8, &p.buf, 0) orelse p.buf.len; + return if (n == 0) null else p.buf[0..n]; + } + + fn set(p: *Path, text: []const u8) error{BadValue}!void { + if (text.len >= p.buf.len) return error.BadValue; + p.buf = @splat(0); + @memcpy(p.buf[0..text.len], text); + } +}; + +pub const Policy = struct { + matrix: Choice = .auto, + attention: Attention = .auto, + kernels: Pick = .auto, + graphs: Choice = .auto, + /// Reference kernels one at a time: decode stream tile, prefill GEMM tile, fused decode tails, chunked recurrence. + stream: Pick = .auto, + gemm: Pick = .auto, + fuse: Pick = .auto, + gdn: Pick = .auto, + prefill_step: u32 = 1024, + /// Set from the serve flags, not keys: rank 0's travel to the other ranks. + mtp: Mtp = .{}, + /// Snapshots the radix prompt cache keeps (`--checkpoint-slots`). + slots: u32 = 8, + /// Rank whose graph capture fails on purpose, for the tests of the fallback (-1: none). Local to a rank. + graph_fail: i32 = -1, + /// The RCCL library to load first. Local to a rank. + rccl_lib: Path = .{}, + + pub const Error = error{ UnknownKey, BadValue, StepNotAligned }; + + /// Whether the decode stream tile is on. + pub fn streamOn(p: *const Policy) bool { + return p.kernels != .reference and p.stream != .reference; + } + + /// Whether the prefill GEMM tile (not the reference block tile) takes the products. + pub fn gemmOn(p: *const Policy) bool { + return p.kernels != .reference and p.gemm != .reference; + } + + /// Whether decode.hip's merged launches are on. + pub fn fused(p: *const Policy) bool { + return p.kernels != .reference and p.fuse != .reference; + } + + /// Whether the DeltaNet prefill runs chunked. + pub fn chunked(p: *const Policy) bool { + return p.kernels != .reference and p.gdn != .reference; + } + + /// What the kernel launches choose under this policy. + pub fn choices(p: *const Policy) Launcher.Choices { + const matrix: affine.Matrix = switch (p.matrix) { + .auto => .auto, + .on => .on, + .off => .off, + }; + return .{ .fuse = p.fused(), .wide = p.wideAttention(), .chunked = p.chunked(), .products = .{ .matrix = matrix, .stream = p.streamOn(), .gemm = p.gemmOn() } }; + } + + /// Whether the 64-row prefill attention tile is on. + pub fn wideAttention(p: *const Policy) bool { + return p.attention != .f32; + } + + /// Whether rounds replay captured graphs on a group of `world` ranks. + pub fn graphsOn(p: *const Policy, world: usize) bool { + return switch (p.graphs) { + .on => true, + .off => false, + .auto => world == 1, + }; + } + + /// Applies `key=value,key=value` (`--policy`'s and TF_POLICY's syntax) over this policy, all of it or none. + pub fn apply(p: *Policy, text: []const u8) Error!void { + var next = p.*; + var it = std.mem.tokenizeAny(u8, text, ", "); + while (it.next()) |pair| { + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse return error.BadValue; + try next.set(pair[0..eq], pair[eq + 1 ..]); + } + if (next.prefill_step == 0 or next.prefill_step % 64 != 0) return error.StepNotAligned; + p.* = next; + } + + fn set(p: *Policy, key: []const u8, value: []const u8) Error!void { + const eql = std.mem.eql; + if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "gdn")) p.gdn = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { + p.prefill_step = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; + } else if (eql(u8, key, "graph_fail")) { + p.graph_fail = std.fmt.parseInt(i32, value, 10) catch return error.BadValue; + } else if (eql(u8, key, "rccl_lib")) try p.rccl_lib.set(value) else return error.UnknownKey; + } + + fn parseEnum(comptime E: type, value: []const u8) Error!E { + return std.meta.stringToEnum(E, value) orelse error.BadValue; + } + + /// One line for the start-up log and server info; default and local fields are left out of the keys. + pub fn format(p: Policy, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.print("matrix={t},attention={t},kernels={t},graphs={t},prefill_step={d}", .{ p.matrix, p.attention, p.kernels, p.graphs, p.prefill_step }); + if (p.stream != .auto) try w.print(",stream={t}", .{p.stream}); + if (p.gemm != .auto) try w.print(",gemm={t}", .{p.gemm}); + if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); + if (p.gdn != .auto) try w.print(",gdn={t}", .{p.gdn}); + if (p.graph_fail >= 0) try w.print(",graph_fail={d}", .{p.graph_fail}); + if (p.rccl_lib.slice()) |path| try w.print(",rccl_lib={s}", .{path}); + try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); + } + + pub const word_count = 6; + + /// The policy as a fixed set of words, for rank 0 to send and every rank to use the same. + pub fn words(p: Policy) [word_count]u32 { + const conf: u64 = @bitCast(p.mtp.confidence); + const pack = [_]u32{ + @backingInt(p.matrix), @backingInt(p.attention), @backingInt(p.kernels), @backingInt(p.graphs), + @backingInt(p.stream), @backingInt(p.gemm), @backingInt(p.fuse), @backingInt(p.gdn), + }; + var nibbles: [2]u32 = .{ 0, 0 }; + for (pack, 0..) |v, i| nibbles[i / 8] |= v << @intCast(4 * (i % 8)); + return .{ nibbles[0], nibbles[1] | @as(u32, p.mtp.drafts) << 24, p.prefill_step, @truncate(conf), @intCast(conf >> 32), p.slots }; + } + + /// `local` with every field rank 0 sent; a rank keeps its own graph fault and library path. + pub fn fromWords(w: [word_count]u32, local: Policy) Policy { + var p = local; + var vals: [8]u32 = undefined; + for (&vals, 0..) |*v, i| v.* = (w[i / 8] >> @intCast(4 * (i % 8))) & 0xf; + p.matrix = @fromBackingInt(@intCast(vals[0])); + p.attention = @fromBackingInt(@intCast(vals[1])); + p.kernels = @fromBackingInt(@intCast(vals[2])); + p.graphs = @fromBackingInt(@intCast(vals[3])); + p.stream = @fromBackingInt(@intCast(vals[4])); + p.gemm = @fromBackingInt(@intCast(vals[5])); + p.fuse = @fromBackingInt(@intCast(vals[6])); + p.gdn = @fromBackingInt(@intCast(vals[7])); + p.mtp = .{ .drafts = @truncate(w[1] >> 24), .confidence = @bitCast(@as(u64, w[3]) | @as(u64, w[4]) << 32) }; + p.prefill_step = w[2]; + p.slots = w[5]; + return p; + } + + /// Where TF_POLICY is read from, once, at resolution. + pub const Env = struct { + /// Read the process's variables after `vars`. + process: bool = false, + vars: []const [2][]const u8 = &.{}, + + pub const none: Env = .{}; + pub const current: Env = .{ .process = true }; + + fn get(e: Env, name: [:0]const u8) ?[]const u8 { + for (e.vars) |v| if (std.mem.eql(u8, v[0], name)) return v[1]; + if (!e.process) return null; + return std.mem.span(std.c.getenv(name.ptr) orelse return null); + } + }; + + /// What resolution found besides the flags (TF_POLICY), for the start-up line. + pub const Notes = struct { + buf: [768]u8 = undefined, + len: usize = 0, + + fn add(n: *Notes, comptime fmt: []const u8, args: anytype) void { + const out = std.fmt.bufPrint(n.buf[n.len..], fmt, args) catch return; + n.len += out.len; + } + + pub fn text(n: *const Notes) []const u8 { + return n.buf[0..n.len]; + } + }; + + /// The policy: defaults, then `flags` (`--policy`), then TF_POLICY; `notes` says when TF_POLICY acted. + pub fn resolve(flags: []const u8, env: Env, notes: *Notes) Error!Policy { + var p: Policy = .{}; + try p.apply(flags); + if (env.get("TF_POLICY")) |text| { + notes.add("TF_POLICY={s}; ", .{text}); + try p.apply(text); + } + return p; + } +}; + +test "apply sets fields and refuses what it does not know" { + var p: Policy = .{}; + try p.apply("matrix=off, kernels=reference,prefill_step=2048"); + try std.testing.expectEqual(Choice.off, p.matrix); + try std.testing.expectEqual(Pick.reference, p.kernels); + try std.testing.expectEqual(@as(u32, 2048), p.prefill_step); + try std.testing.expectError(error.UnknownKey, p.apply("wmma=on")); + try std.testing.expectError(error.UnknownKey, p.apply("mtp_drafts=2")); + try std.testing.expectError(error.BadValue, p.apply("matrix=maybe")); + try std.testing.expectError(error.StepNotAligned, p.apply("prefill_step=1000")); +} + +test "a policy survives its words" { + var p: Policy = .{ .mtp = .{ .drafts = 2, .confidence = 0.25 }, .slots = 4, .graph_fail = 1 }; + try p.apply("matrix=on,attention=f32,graphs=off,gdn=reference"); + const back = Policy.fromWords(p.words(), .{ .graph_fail = 1 }); + try std.testing.expectEqualDeep(p, back); +} + +test "TF_POLICY speaks after the flags, and the reference switches" { + var notes: Policy.Notes = .{}; + const env: Policy.Env = .{ .vars = &.{.{ "TF_POLICY", "matrix=on,stream=reference,attention=f32,graphs=off" }} }; + const p = try Policy.resolve("matrix=off", env, ¬es); + try std.testing.expectEqual(Choice.on, p.matrix); + try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and p.chunked() and !p.wideAttention()); + try std.testing.expect(!p.graphsOn(1) and !p.graphsOn(2)); + try std.testing.expect(std.mem.indexOf(u8, notes.text(), "TF_POLICY=") != null); + var reference: Policy = .{}; + try reference.apply("kernels=reference"); + try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused() and !reference.chunked()); +} + +test "graphs follow the group unless the policy says" { + var p: Policy = .{}; + try std.testing.expect(p.graphsOn(1) and !p.graphsOn(2)); + try p.apply("graphs=on"); + try std.testing.expect(p.graphsOn(2)); +} diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig new file mode 100644 index 00000000000..83f2c0f2fe5 --- /dev/null +++ b/zig/src/hip/root.zig @@ -0,0 +1,47 @@ +//! The HIP backend as one module: runtime, the model-free kernels' launches and ops, and what an engine opens. + +pub const abi = @import("abi.zig"); +pub const runtime = @import("runtime.zig"); +pub const Runtime = runtime.Runtime; +pub const Error = runtime.Error; +pub const Context = @import("context.zig").Context; +pub const memory = @import("memory.zig"); +pub const DeviceBuffer = memory.DeviceBuffer; +pub const HostBuffer = memory.HostBuffer; +pub const usage = memory.usage; +pub const Usage = memory.Usage; +pub const Stream = @import("stream.zig").Stream; +pub const Module = @import("module.zig").Module; +pub const Function = @import("module.zig").Function; +pub const launch = @import("launch.zig"); +pub const graph = @import("graph.zig"); +pub const Arena = @import("arena.zig").Arena; +pub const caps = @import("caps.zig"); +pub const Caps = caps.Caps; +pub const kernels = @import("kernels.zig"); +pub const launches = @import("launches.zig"); +pub const Launcher = launches.Launcher; +/// The stream handle a dry run passes: launches do nothing on it. +pub const counting = @import("launches/util.zig").counting; +pub const raw = @import("raw.zig"); +pub const ops = @import("ops/ops.zig"); +pub const plan_ops = @import("ops/plan.zig"); +pub const policy = @import("policy.zig"); +pub const Policy = policy.Policy; +pub const admission = @import("admission.zig"); +pub const Device = @import("device.zig").Device; +pub const Upload = @import("upload.zig").Upload; +pub const quant = @import("core").quant; +pub const registry = @import("core").registry; +pub const rccl = @import("comm/rccl.zig"); +pub const link = @import("comm/link.zig"); +pub const Group = @import("comm/group.zig").Group; + +test { + _ = policy; + _ = admission; + _ = Device; + _ = rccl; + _ = link; + _ = Group; +} diff --git a/zig/src/hip/upload.zig b/zig/src/hip/upload.zig new file mode 100644 index 00000000000..c32867f4702 --- /dev/null +++ b/zig/src/hip/upload.zig @@ -0,0 +1,26 @@ +//! The HIP backend's side of a format's `load`: host tensors onto the device, kept for the model to free. + +const std = @import("std"); +const quant = @import("core").quant; +const runtime = @import("runtime.zig"); +const memory = @import("memory.zig"); + +/// Device memory of one model: every buffer a format uploads is kept in `buffers`, which the model frees. +pub const Upload = struct { + r: *const runtime.Runtime, + buffers: *std.ArrayList(memory.DeviceBuffer), + gpa: std.mem.Allocator, + + /// What a format's `upload` takes. + pub fn uploader(u: *const Upload) quant.Uploader { + return .{ .ctx = @ptrCast(@constCast(u)), .put = put }; + } + + fn put(ctx: *anyopaque, t: quant.Tensor) anyerror!quant.Buf { + const u: *const Upload = @ptrCast(@alignCast(ctx)); + var b = try memory.DeviceBuffer.fromHost(u.r, t.bytes); + errdefer b.free(); + try u.buffers.append(u.gpa, b); + return .{ .ptr = @intFromPtr(b.ptr), .len = b.len, .dtype = t.dtype, .rank = t.rank, .shape = t.shape }; + } +}; diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig new file mode 100644 index 00000000000..c28e918c5e7 --- /dev/null +++ b/zig/src/native/hip.zig @@ -0,0 +1,201 @@ +//! The engines a native server opens on HIP: the GPU, its policy, the tensor-parallel group, round loop and lane host. + +const std = @import("std"); +const hip = @import("hip"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const Allocator = std.mem.Allocator; +const admission = hip.admission; +const modelContext = admission.modelContext; + +/// The HIP families: namespaces with `model_type`, `formats`, `default_context`, `prefill_step`, `open` and `follow`. +const registry = .{ qwen35.native, qwen35.native_moe }; + +pub const backends: []const []const u8 = &.{"hip"}; +/// The serve flags past the common ones this backend takes (server/cli.zig lists and parses them). +pub const serves: []const []const u8 = &.{ "--tp", "--policy", "--mtp-drafts", "--mtp-confidence", "--checkpoint-slots", "--backend=rocm" }; +pub const families: []const api.Family = blk: { + var out: [registry.len]api.Family = undefined; + for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats }; + const final = out; + break :blk &final; +}; + +/// The GPU family gate entries name ("rdna2" for gfx103x, "rdna3" for gfx11 / gfx12); null without a usable GPU. +pub fn chip(a: Allocator) ?[]const u8 { + const caps = hip.Device.capsOf(0) orelse return null; + return a.dupe(u8, if (caps.generation == .rdna2) "rdna2" else "rdna3") catch null; +} + +/// A flag or a resource the engine cannot take: `problem` says why. +const Refused = error{Refused}; + +fn refuse(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { + problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; + return error.Refused; +} + +/// The tensor-parallel flags as the Python ROCm server checks them. +fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { + if (o.tp != 1 and o.tp != 2 and o.tp != 4 and o.tp != 8) return refuse(a, problem, "--tp {d} is not a supported ROCm world size; choose 1, 2, 4 or 8", .{o.tp}); + if (o.tp > 1 and o.master.len == 0) return refuse(a, problem, "--tp > 1 needs --master: rank 0's address on the link between the machines", .{}); + if (o.tp == 1 and o.rank != 0) return refuse(a, problem, "--rank must be 0 when --tp 1", .{}); + if (o.rank >= o.tp) return refuse(a, problem, "--rank {d} not in [0, --tp {d})", .{ o.rank, o.tp }); + if (o.keep) |n| if (n < 0) return refuse(a, problem, "--checkpoint-slots must be 0 or more", .{}); + if (o.mtp_drafts) |n| if (n > 3) return refuse(a, problem, "--mtp-drafts {d}: the HIP engine drafts at most 3", .{n}); + if (o.mtp_confidence) |c| if (c < 0 or c > 1) return refuse(a, problem, "--mtp-confidence must be from 0 to 1", .{}); + if (o.prompt_cache_gib) |g| if (g < 0) return refuse(a, problem, "--prompt-cache-gib must be 0 or more", .{}); +} + +/// What every family needs before it loads: the card, the policy, the group, and the window and lanes asked for. +const Ready = struct { + dev: hip.Device, + options: Options, + /// The policy's line, for the server's info. + policy_line: []const u8, + + const Options = qwen35.native_engine.Options; + + fn deinit(r: Ready, gpa: Allocator) void { + gpa.free(r.policy_line); + if (r.dev.group) |g| g.close(gpa); + } +}; + +/// Resolves the policy on rank 0 (defaults, flags, old variables, TF_POLICY), joins the group, sends it to the others. +fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) (Refused || Allocator.Error)!Ready { + try checkGroup(a, o, problem); + const native = modelContext(a, io, o.dir); + const window = admission.contextWindow(o.context, native, F.default_context) catch |err| return switch (err) { + error.Negative => refuse(a, problem, "--context {d}: a token count, or 0 for the model's window", .{o.context.?}), + error.NoNative => refuse(a, problem, "--context 0 asks for the model's window, and its config.json names none: give a token count", .{}), + error.PastNative => refuse(a, problem, "--context {d} exceeds this model's {d}-token window", .{ o.context.?, native }), + }; + const index: c_int = if (o.device) |d| @intCast(d) else hip.Device.ordinal(o.rank); + const caps = hip.Device.capsOf(index) orelse return refuse(a, problem, "HIP device {d} is not a GPU this engine supports", .{index}); + var notes: hip.Policy.Notes = .{}; + var policy = hip.Policy.resolve(o.policy, .current, ¬es) catch |err| return refuse(a, problem, "the policy \"{s}\" is refused ({s})", .{ o.policy, @errorName(err) }); + if (o.mtp_drafts) |n| policy.mtp.drafts = @intCast(n); + if (o.mtp_confidence) |c| policy.mtp.confidence = c; + if (o.keep) |n| policy.slots = @intCast(@min(n, 1 << 16)); + const group: ?*hip.Group = if (o.tp > 1) hip.Group.join(gpa, io, o.rank, o.tp, o.master, o.master_port, caps, &policy) catch |err| return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.NoRccl => refuse(a, problem, "tensor parallelism needs RCCL", .{}), + error.NoId => refuse(a, problem, "RCCL gave no id", .{}), + error.MixedGpus => refuse(a, problem, "the ranks' GPUs differ: a group needs one kind of GPU", .{}), + else => refuse(a, problem, "the ranks' link at {s}:{d} failed ({s})", .{ o.master, o.master_port, @errorName(err) }), + } else null; + errdefer if (group) |g| g.close(gpa); + const policy_line = try std.fmt.allocPrint(gpa, "{f}", .{policy}); + std.debug.print("[tensorfold] HIP rank {d} of {d}: policy {s}{s} {s}\n", .{ o.rank, o.tp, policy_line, if (o.rank > 0) " (rank 0's)" else "", notes.text() }); + return .{ + .dev = .{ .index = index, .caps = caps, .policy = policy, .group = group }, + .options = .{ + .window = @intCast(window), + .streams = @max(o.lanes, 1), + .fixed = o.lanes_fixed, + .rank = o.rank, + .world = o.tp, + .cache_gib = o.prompt_cache_gib, + .cache_over_cap = o.prompt_cache_over_cap, + }, + .policy_line = policy_line, + }; +} + +/// One loaded model behind the lane host: everything the engine thread reads lives here. +const Host = struct { + gpa: Allocator, + group: ?*hip.Group, + policy_line: []const u8, + family: *anyopaque, + release: *const fn (*anyopaque) void, + cfg: lanes.Config, + clock: lanes.backend.WallClock, + core: lanes.Engine, + host: api.LaneHost, + + fn close(p: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(p)); + h.host.stop(); + h.core.deinit(); + h.cfg.deinit(h.gpa); + h.release(h.family); + if (h.group) |g| g.close(h.gpa); + h.gpa.free(h.policy_line); + h.gpa.destroy(h); + } +}; + +/// The device bytes this process holds and their peak, as the runtime counts them. +fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { + const u = hip.usage(reset_peak); + return .{ .active = u.device, .cache = 0, .peak = u.peak }; +} + +/// The engine for `o.dir`, or null with `problem` when no HIP family reads it; under tensor parallelism, rank 0. +pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + inline for (registry) |F| { + if (std.mem.eql(u8, o.model_type, F.model_type)) return openWith(F, a, gpa, io, o, problem); + } + problem.* = try std.fmt.allocPrint(a, "the native HIP engine has no backend for {s} checkpoints yet; serve with --engine python", .{o.model_type}); + return null; +} + +fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const r = ready(F, a, gpa, io, o, problem) catch |err| switch (err) { + error.Refused => return null, + else => |x| return x, + }; + var served = false; + defer if (!served) r.deinit(gpa); + const loaded = F.open(a, gpa, io, r.dev, o.dir, r.options, problem) catch |err| switch (err) { + error.Refused => return null, + else => |x| return x, + }; + errdefer loaded.deinit(loaded.ctx); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.group = r.dev.group; + h.policy_line = r.policy_line; + h.family = loaded.ctx; + h.release = loaded.deinit; + h.cfg = try lanes.Config.init(gpa, loaded.facts, loaded.rows, loaded.rows - 1); + errdefer h.cfg.deinit(gpa); + h.clock = .{ .io = io }; + h.core = lanes.Engine.init(gpa, &h.cfg, loaded.backend, h.clock.clock()); + errdefer h.core.deinit(); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = @intCast(loaded.streams), .context_window = @intCast(r.options.window), .prefill_step = F.prefill_step, .policy = h.policy_line, .startup = loaded.startup }); + h.host.memory = .{ .read = readMemory }; + try h.host.start(); + served = true; + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} + +/// A rank above 0: holds its share and runs rank 0's steps until rank 0 stops; false with `problem` if it cannot start. +pub fn follow(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !bool { + inline for (registry) |F| { + if (std.mem.eql(u8, o.model_type, F.model_type)) { + const r = ready(F, a, gpa, io, o, problem) catch |err| switch (err) { + error.Refused => return false, + else => |x| return x, + }; + defer r.deinit(gpa); + F.follow(a, gpa, io, r.dev, o.dir, r.options, problem) catch |err| switch (err) { + error.Refused => return false, + else => |x| return x, + }; + return true; + } + } + problem.* = try std.fmt.allocPrint(a, "the native HIP engine has no backend for {s} checkpoints yet; serve with --engine python", .{o.model_type}); + return false; +} + +test "every registered family is listed for capabilities" { + try std.testing.expectEqual(@as(usize, registry.len), families.len); + try std.testing.expectEqualStrings("qwen3_5", families[0].model_type); + try std.testing.expectEqualStrings("qwen3_5_moe", families[1].model_type); +} diff --git a/zig/tests/hip/args.zig b/zig/tests/hip/args.zig new file mode 100644 index 00000000000..daabc8f6b73 --- /dev/null +++ b/zig/tests/hip/args.zig @@ -0,0 +1,121 @@ +//! The command line of `tf-hip-test`: the commands, and the old command names as aliases of them. + +const std = @import("std"); + +pub const Command = enum { runtime, kernels, bench_launches, bench_overhead, info }; + +/// What an invocation asks for, whether by the new names or an old alias. +pub const Plan = struct { + command: Command, + filter: []const u8 = "", + bench: bool = false, + oracle: ?[]const u8 = null, + reps: ?usize = null, + n: ?usize = null, +}; + +pub const Bad = error{ BadArguments, UnknownCommand }; + +fn number(text: []const u8) Bad!usize { + return std.fmt.parseInt(usize, text, 10) catch error.BadArguments; +} + +fn value(rest: []const []const u8, i: *usize) Bad![]const u8 { + i.* += 1; + if (i.* >= rest.len) return error.BadArguments; + return rest[i.*]; +} + +/// The old commands as filters of the new ones; their positional [reps] [filter] arguments are read. +fn oldAlias(cmd: []const u8, rest: []const []const u8) Bad!?Plan { + const eql = std.mem.eql; + const first: []const u8 = if (rest.len > 0) rest[0] else ""; + if (eql(u8, cmd, "info")) return .{ .command = .info }; + for ([_][]const u8{ "smoke", "graph", "cooperative", "library", "image" }) |name| { + if (eql(u8, cmd, name)) return .{ .command = .runtime, .filter = name }; + } + if (eql(u8, cmd, "affine")) return .{ .command = .kernels, .filter = "oracle", .oracle = if (rest.len > 0) first else return error.BadArguments }; + if (eql(u8, cmd, "gemm")) { + if (eql(u8, first, "sweep")) return .{ .command = .kernels, .filter = "affine sweep" }; + if (eql(u8, first, "tiers")) return .{ .command = .kernels, .filter = "rows prefill" }; + if (eql(u8, first, "short")) return .{ .command = .kernels, .filter = "affine short", .bench = true }; + return .{ .command = .kernels, .filter = "affine prefill", .bench = true }; + } + if (eql(u8, cmd, "gemv")) return .{ .command = .kernels, .filter = "affine decode", .bench = true }; + if (eql(u8, cmd, "exact")) return .{ .command = .kernels, .filter = "rows decode" }; + if (eql(u8, cmd, "gdn")) return .{ .command = .kernels, .filter = if (eql(u8, first, "bench")) "gdn bench" else "gdn", .bench = eql(u8, first, "bench") }; + if (eql(u8, cmd, "decode")) { + const which: []const u8 = if (rest.len > 1) rest[1] else ""; + const filters = [_][]const u8{ "decode router", "decode tail", "decode group", "decode pair", "decode chain" }; + for (filters) |f| if (which.len > 0 and std.mem.endsWith(u8, f, which)) return .{ .command = .kernels, .filter = f, .bench = true }; + return .{ .command = .kernels, .filter = "decode ", .bench = true }; + } + if (eql(u8, cmd, "launches")) return .{ .command = .bench_launches, .n = if (rest.len > 0) try number(first) else null, .reps = if (rest.len > 1) try number(rest[1]) else null }; + if (eql(u8, cmd, "overhead")) return .{ .command = .bench_overhead, .n = if (rest.len > 0) try number(first) else null, .reps = if (rest.len > 1) try number(rest[1]) else null }; + return null; +} + +pub fn parse(cmd: []const u8, rest: []const []const u8) Bad!Plan { + if (try oldAlias(cmd, rest)) |plan| { + std.debug.print("note: `{s}` is an alias of the {t} command, with {s}\n", .{ cmd, plan.command, if (plan.filter.len > 0) plan.filter else "all groups" }); + return plan; + } + var plan: Plan = undefined; + var i: usize = 0; + if (std.mem.eql(u8, cmd, "runtime")) { + plan = .{ .command = .runtime }; + } else if (std.mem.eql(u8, cmd, "kernels")) { + plan = .{ .command = .kernels }; + } else if (std.mem.eql(u8, cmd, "bench")) { + if (rest.len == 0) return error.BadArguments; + plan = .{ .command = if (std.mem.eql(u8, rest[0], "launches")) .bench_launches else if (std.mem.eql(u8, rest[0], "overhead")) .bench_overhead else return error.BadArguments }; + if (rest.len > 1) plan.n = try number(rest[1]); + if (rest.len > 2) plan.reps = try number(rest[2]); + return plan; + } else return error.UnknownCommand; + while (i < rest.len) : (i += 1) { + const a = rest[i]; + if (std.mem.eql(u8, a, "--filter")) { + plan.filter = try value(rest, &i); + } else if (std.mem.eql(u8, a, "--bench") and plan.command == .kernels) { + plan.bench = true; + } else if (std.mem.eql(u8, a, "--oracle") and plan.command == .kernels) { + plan.oracle = try value(rest, &i); + } else if (std.mem.eql(u8, a, "--reps") and plan.command == .kernels) { + plan.reps = try number(try value(rest, &i)); + } else return error.BadArguments; + } + return plan; +} + +test "the old names resolve to groups of the new commands" { + const a = (try oldAlias("exact", &.{})).?; + try std.testing.expectEqual(Command.kernels, a.command); + try std.testing.expectEqualStrings("rows decode", a.filter); + const g = (try oldAlias("gemm", &.{"tiers"})).?; + try std.testing.expectEqualStrings("rows prefill", g.filter); + try std.testing.expect(!g.bench); + const m = (try oldAlias("gemv", &.{"3"})).?; + try std.testing.expect(m.bench); + const d = (try oldAlias("decode", &.{ "1", "pair" })).?; + try std.testing.expectEqualStrings("decode pair", d.filter); + const f = (try oldAlias("affine", &.{"dir"})).?; + try std.testing.expectEqualStrings("dir", f.oracle.?); + try std.testing.expectError(error.BadArguments, oldAlias("affine", &.{})); + try std.testing.expect((try oldAlias("kernels", &.{})) == null); +} + +test "the new commands take their flags" { + const p = try parse("kernels", &.{ "--filter", "gdn", "--bench", "--oracle", "x", "--reps", "7" }); + try std.testing.expectEqual(Command.kernels, p.command); + try std.testing.expectEqualStrings("gdn", p.filter); + try std.testing.expect(p.bench); + try std.testing.expectEqual(@as(?usize, 7), p.reps); + const r = try parse("runtime", &.{ "--filter", "smoke" }); + try std.testing.expectEqual(Command.runtime, r.command); + try std.testing.expectError(error.BadArguments, parse("runtime", &.{"--bench"})); + const b = try parse("bench", &.{ "overhead", "500" }); + try std.testing.expectEqual(Command.bench_overhead, b.command); + try std.testing.expectEqual(@as(?usize, 500), b.n); + try std.testing.expectError(error.UnknownCommand, parse("nothing", &.{})); +} diff --git a/zig/tests/qwen35/check.zig b/zig/tests/qwen35/check.zig new file mode 100644 index 00000000000..105a5eaf390 --- /dev/null +++ b/zig/tests/qwen35/check.zig @@ -0,0 +1,122 @@ +//! `check [--tp N --rank R] [--truth T --ids IDS] [--only invariants|accuracy|speed]`: a line a check. + +const std = @import("std"); +const qwen35 = @import("qwen3_5"); +const check_accuracy = @import("check_accuracy.zig"); +const check_ctx = @import("check_ctx.zig"); +const check_invariants = @import("check_invariants.zig"); +const check_radix = @import("check_radix.zig"); +const check_report = @import("check_report.zig"); +const check_speed = @import("check_speed.zig"); +const group_mod = @import("group.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); + +const Phase = enum { invariants, accuracy, speed }; + +const Options = struct { + model: []const u8, + group: group_mod.Group = .{}, + prompts: ?[]const u8 = null, + truth: ?[]const u8 = null, + ids: ?[]const u8 = null, + speed: bool = false, + explain: bool = false, + only: ?Phase = null, + tokens: u32 = 48, + bar: check_accuracy.Bar = .{}, + + fn runs(o: Options, p: Phase) bool { + if (o.only) |only| return only == p; + return switch (p) { + .invariants => true, + .accuracy => o.truth != null, + .speed => o.speed, + }; + } +}; + +fn parse(args: []const [:0]const u8) !Options { + if (args.len < 1) return error.MissingArgument; + var o: Options = .{ .model = args[0] }; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (try o.group.option(args, &i)) continue; + const a = args[i]; + if (std.mem.eql(u8, a, "--speed")) { + o.speed = true; + continue; + } + if (std.mem.eql(u8, a, "--explain-kernels")) { + o.explain = true; + continue; + } + i += 1; + if (i >= args.len) return error.MissingArgument; + if (std.mem.eql(u8, a, "--prompts")) o.prompts = args[i] else if (std.mem.eql(u8, a, "--truth")) o.truth = args[i] else if (std.mem.eql(u8, a, "--ids")) o.ids = args[i] else if (std.mem.eql(u8, a, "--only")) o.only = std.meta.stringToEnum(Phase, args[i]) orelse return error.UnknownPhase else if (std.mem.eql(u8, a, "--tokens")) o.tokens = try std.fmt.parseInt(u32, args[i], 10) else if (std.mem.eql(u8, a, "--kl")) o.bar.kl_mean = try std.fmt.parseFloat(f64, args[i]) else if (std.mem.eql(u8, a, "--top1")) o.bar.top1 = try std.fmt.parseFloat(f64, args[i]) else return error.UnknownOption; + } + if (o.runs(.accuracy) and o.truth == null and !o.explain) return error.NoTruth; + return o; +} + +/// The ids file the truth was made from, next to it, when none is given. +fn idsPath(arena: std.mem.Allocator, o: Options) !?[]const u8 { + if (o.ids) |p| return p; + const t = o.truth orelse return null; + const stem = if (std.mem.endsWith(u8, t, ".npy")) t[0 .. t.len - 4] else t; + return try std.fmt.allocPrint(arena, "{s}.ids.npy", .{stem}); +} + +/// Pages of the largest phase (four streams at the capacity, or the radix streams and tree) and the padding slot's. +fn poolPages(capacity: usize, tokens: u32) usize { + const pages = qwen35.pages.pagesFor; + const radix = check_radix.most_streams * pages(check_radix.capacity(tokens)) + check_radix.tree_pages; + return @max(4 * pages(capacity), radix) + pages(rows); +} + +/// Rows a round of the checks holds at most: four streams of the widest window. +const rows = 4 * qwen35.hip_lanes.Hip.max_window; + +/// Exit code: 0 when every check passed (or skipped), 1 when one failed. +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !u8 { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const o = try parse(args); + const ids = if (try idsPath(arena, o)) |p| try ids_file.load(arena, io, p) else try ids_file.synthetic(arena, 1536); + const short = try ids_file.short(arena); + const long = if (o.prompts) |p| try ids_file.read(arena, io, p) else try ids_file.long(arena, ids); + + var capacity = ids_file.longest(long) + 2 * o.tokens + 64; + capacity = @max(capacity, check_radix.capacity(o.tokens)); + if (o.runs(.accuracy)) capacity = @max(capacity, ids.len + 64); + if (o.runs(.speed)) capacity = @max(capacity, check_speed.longest_prefill + 64); + var joined = try o.group.join(io); + defer joined.close(); + const e = try o.group.engine(gpa, io, o.model, joined, .{ .capacity = capacity, .prompt_rows = capacity, .streams = check_radix.most_streams, .snapshots = check_radix.slots, .batch_rows = rows, .pool_pages = poolPages(capacity, o.tokens) }); + defer e.deinit(); + if (o.group.rank > 0) { + try group_mod.follow(gpa, e, &joined); + return 0; + } + if (o.explain) { + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try e.lib.affine.reg.explain(e.lib.affine.env(), .mlx, &w, e.weights.spec.bits, e.weights.spec.group); + std.debug.print("{s}", .{w.buffered()}); + return 0; + } + var session: lanes_session.Session = undefined; + try session.init(gpa, io, e, if (o.group.world > 1) &joined.link else null); + defer session.deinit(); + + var report: check_report.Report = .{}; + var c: check_ctx.Ctx = .{ .gpa = gpa, .io = io, .arena = arena, .e = e, .session = &session, .report = &report, .group = o.group, .ids = ids, .short = short, .long = long, .tokens = o.tokens, .pages_at_start = e.pool.ids.used() }; + const t0 = std.Io.Clock.awake.now(io); + std.debug.print("check {s}, tp {d}\n", .{ o.model, o.group.world }); + if (o.runs(.invariants)) check_invariants.run(&c); + if (o.runs(.accuracy)) check_accuracy.run(&c, o.truth.?, o.bar); + if (o.runs(.speed)) check_speed.run(&c); + report.summary(@as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds() - t0.toNanoseconds())) / 1e9); + return if (report.failed == 0) 0 else 1; +} diff --git a/zig/tests/qwen35/check_accuracy.zig b/zig/tests/qwen35/check_accuracy.zig new file mode 100644 index 00000000000..22c4c5ef2f6 --- /dev/null +++ b/zig/tests/qwen35/check_accuracy.zig @@ -0,0 +1,34 @@ +//! The accuracy checks of `check`: every row's logits, from a cold prefill and from decode rounds, against fp64 truth. + +const std = @import("std"); +const check_ctx = @import("check_ctx.zig"); +const logits_run = @import("logits_run.zig"); +const truth_score = @import("truth_score.zig"); + +const Ctx = check_ctx.Ctx; + +/// What a score must stay within. +pub const Bar = struct { kl_mean: f64 = 0.01, top1: f64 = 90.0, ppl_ratio: f64 = 1.02 }; + +pub fn run(c: *Ctx, truth: []const u8, bar: Bar) void { + if (c.tp()) return c.report.skip("accuracy", "the logits run on one rank"); + const mode0: logits_run.Mode = .{ .wide = true }; + var scorer = truth_score.Scorer.init(c.gpa, c.io, truth, c.ids, logits_run.kindOf(c.e, mode0), logits_run.vocab(c.e)) catch |err| return c.report.broke("accuracy", err); + defer scorer.deinit(); + for ([_]bool{ false, true }) |decode| { + const name = if (decode) "accuracy decode" else "accuracy prefill"; + scorer.reset(); + logits_run.stream(c.gpa, c.e, c.ids, .{ .wide = true, .decode = decode }, .{ .ctx = &scorer, .put = truth_score.Scorer.put }) catch |err| { + c.report.broke(name, err); + continue; + }; + const s = scorer.result() catch |err| { + c.report.broke(name, err); + continue; + }; + const ok = s.kl_mean <= bar.kl_mean and s.top1 >= bar.top1 and s.ppl <= s.ppl_truth * bar.ppl_ratio; + const line = "rows={d} KL mean={e:.3} max={e:.3} top1={d:.2}% max|dlogit|={d:.4} ppl truth={d:.4} cand={d:.4}"; + const args = .{ s.rows, s.kl_mean, s.kl_max, s.top1, s.max_abs, s.ppl_truth, s.ppl }; + if (ok) c.report.pass(name, line, args) else c.report.fail(name, line ++ " (bar: KL mean <= {e:.1}, top1 >= {d:.0}%, ppl within {d:.0}%)", args ++ .{ bar.kl_mean, bar.top1, (bar.ppl_ratio - 1) * 100 }); + } +} diff --git a/zig/tests/qwen35/check_ctx.zig b/zig/tests/qwen35/check_ctx.zig new file mode 100644 index 00000000000..cb5ec1120d9 --- /dev/null +++ b/zig/tests/qwen35/check_ctx.zig @@ -0,0 +1,41 @@ +//! What the checks of one `check` run share: the engine, its lane session, the prompts and the report. + +const std = @import("std"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const group_mod = @import("group.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); +const check_report = @import("check_report.zig"); + +pub const Ctx = struct { + gpa: std.mem.Allocator, + io: std.Io, + /// Lives to the end of the run: replies, prompt sets. + arena: std.mem.Allocator, + e: *qwen35.engine.Engine, + session: *lanes_session.Session, + report: *check_report.Report, + group: group_mod.Group, + /// Ids for the long prompts, the row cases and the accuracy rows. + ids: []const u32, + short: []const ids_file.Prompt, + long: []const ids_file.Prompt, + /// Tokens each stream of an invariant run generates. + tokens: u32, + /// Pages the pool held before the first run: the scratch rows'. + pages_at_start: usize = 0, + + /// Whether this run spans GPUs, where only what the lane core drives can run. + pub fn tp(c: *const Ctx) bool { + return c.group.world > 1; + } +}; + +/// The ways a stream draws its tokens. +pub const Draw = struct { name: []const u8, sampling: ?lanes.Sampling }; + +pub const draws = [_]Draw{ + .{ .name = "greedy", .sampling = null }, + .{ .name = "seeded t=1", .sampling = .{ .seed = 7, .temperature = 1.0 } }, +}; diff --git a/zig/tests/qwen35/check_invariants.zig b/zig/tests/qwen35/check_invariants.zig new file mode 100644 index 00000000000..aaaa3907308 --- /dev/null +++ b/zig/tests/qwen35/check_invariants.zig @@ -0,0 +1,139 @@ +//! The exactness checks of `check`: windows, drafts, shared rounds, resumed prompts and replayed graphs against serial. + +const std = @import("std"); +const check_ctx = @import("check_ctx.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); +const rows_run = @import("rows_run.zig"); +const check_radix = @import("check_radix.zig"); + +const Ctx = check_ctx.Ctx; +const Session = lanes_session.Session; + +/// Windows of 1 to 16 rows, streams with a rejected draft's partial keep, and rounds padded up to a bucket. +const cases = blk: { + var list: [25]rows_run.Case = undefined; + for (0..16) |i| list[i] = .{ .streams = 1, .n = i + 1, .keep = i + 1 }; + list[16] = .{ .streams = 4, .n = 4, .keep = 4 }; + list[17] = .{ .streams = 4, .n = 4, .keep = 2 }; + list[18] = .{ .streams = 4, .n = 2, .keep = 2 }; + list[19] = .{ .streams = 4, .n = 2, .keep = 1 }; + list[20] = .{ .streams = 1, .n = 1, .keep = 1, .pad = 4 }; + list[21] = .{ .streams = 1, .n = 3, .keep = 3, .pad = 8 }; + list[22] = .{ .streams = 3, .n = 3, .keep = 2, .pad = 16 }; + list[23] = .{ .streams = 4, .n = 4, .keep = 4, .pad = 32 }; + list[24] = .{ .streams = 2, .n = 4, .keep = 1, .pad = 64 }; + break :blk list; +}; + +pub fn run(c: *Ctx) void { + rows(c); + lanesSet(c, "short", c.short); + lanesSet(c, "long", c.long); + resumed(c); + check_radix.run(c); + replayShare(c); + check_radix.leaked(c); +} + +fn rows(c: *Ctx) void { + if (c.tp()) return c.report.skip("rows", "the layer by layer trace runs on one rank; the lane checks below run the windows under tp"); + const ids = c.ids[0..@min(c.ids.len, 256)]; + for (cases) |k| { + const plain = std.fmt.allocPrint(c.arena, "rows {d} stream{s} x {d} row{s}, {d} kept", .{ k.streams, if (k.streams == 1) "" else "s", k.n, if (k.n == 1) "" else "s", k.keep }) catch return; + const name = if (k.pad > 0) std.fmt.allocPrint(c.arena, "{s}, padded to {d}", .{ plain, k.pad }) catch return else plain; + const diff = rows_run.runCase(c.gpa, c.e, ids, k) catch |err| { + c.report.broke(name, err); + continue; + }; + if (diff) |d| { + c.report.fail(name, "layer {d} ({s}), stream {d} row {d}: first difference at column {d}", .{ d.layer, d.kind, d.stream, d.row, d.column }); + } else c.report.pass(name, "every layer's residuals and the final rows equal each stream one row at a time", .{}); + } +} + +/// Where two runs' replies first differ, as a line to print; null when they are equal. +fn differ(a: Session.Done, b: Session.Done, buf: []u8) ?[]const u8 { + for (a.replies, b.replies) |x, y| { + const at = std.mem.indexOfDiff(u32, x.tokens, y.tokens) orelse continue; + const xt: i64 = if (at < x.tokens.len) x.tokens[at] else -1; + const yt: i64 = if (at < y.tokens.len) y.tokens[at] else -1; + return std.fmt.bufPrint(buf, "{s} differs at token {d}: {d} against {d}", .{ x.name, at, xt, yt }) catch "differs"; + } + return null; +} + +fn verdict(c: *Ctx, name: []const u8, a: Session.Done, b: Session.Done) void { + var buf: [160]u8 = undefined; + if (differ(a, b, &buf)) |why| return c.report.fail(name, "{s}", .{why}); + c.report.pass(name, "{d} streams, {d} tokens, {d} drafts accepted", .{ a.replies.len, a.tokens(), a.accepted() }); +} + +fn named(c: *Ctx, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(c.arena, fmt, args) catch "lanes"; +} + +/// Drafted against serial, solo against together and graph against eager, for each way of drawing. +fn lanesSet(c: *Ctx, set: []const u8, prompts: []const ids_file.Prompt) void { + for (check_ctx.draws) |d| { + const job: Session.Job = .{ .prompts = prompts, .max_new = c.tokens, .sampling = d.sampling }; + const together = c.session.run(c.arena, job) catch |err| return c.report.broke(named(c, "lanes {s} {s}", .{ set, d.name }), err); + var serial = job; + serial.drafts = false; + const drafted = named(c, "lanes {s} {s}: drafted == serial", .{ set, d.name }); + if (c.session.h.head == null) { + c.report.skip(drafted, "the model has no draft head"); + } else if (c.session.run(c.arena, serial)) |done| verdict(c, drafted, together, done) else |err| c.report.broke(drafted, err); + var solo = job; + solo.solo = true; + if (c.session.run(c.arena, solo)) |done| verdict(c, named(c, "lanes {s} {s}: solo == together", .{ set, d.name }), together, done) else |err| c.report.broke(named(c, "lanes {s} {s}: solo == together", .{ set, d.name }), err); + graphs(c, named(c, "lanes {s} {s}: graph == eager", .{ set, d.name }), job, together); + } +} + +/// `graph` ran with the engine's graphs; the same job again with every round eager. +fn graphs(c: *Ctx, name: []const u8, job: Session.Job, graph: Session.Done) void { + if (c.tp()) return c.report.skip(name, "rounds under tp run eager unless --policy graphs=on"); + if (!c.e.o.graphs) return c.report.skip(name, "graphs are off"); + if (graph.replayed == 0) return c.report.skip(name, "no round of the run replayed a graph"); + c.e.o.graphs = false; + defer c.e.o.graphs = true; + const eager = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + var buf: [160]u8 = undefined; + if (differ(graph, eager, &buf)) |why| return c.report.fail(name, "{s}", .{why}); + c.report.pass(name, "{d} rounds replayed, {d} tokens", .{ graph.replayed, graph.tokens() }); +} + +/// Each long prompt again, extended by its reply, on the caches the first run kept, against a run with none kept. +fn resumed(c: *Ctx) void { + const name = "lanes long greedy: resumed == fresh"; + c.session.h.keepPrompts(8, 4 << 30); + defer c.session.h.keepPrompts(0, 0); + const first = c.session.run(c.arena, .{ .prompts = c.long, .max_new = c.tokens }) catch |err| return c.report.broke(name, err); + const extended = lanes_session.extend(c.arena, c.long, first.replies) catch |err| return c.report.broke(name, err); + const again = c.session.run(c.arena, .{ .prompts = extended, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + const fresh = c.session.run(c.arena, .{ .prompts = extended, .max_new = c.tokens, .solo = true, .drafts = false }) catch |err| return c.report.broke(name, err); + var cached: usize = 0; + var every = true; + for (again.replies) |r| { + cached += r.cached; + every = every and r.cached > 0; + } + var buf: [160]u8 = undefined; + if (differ(again, fresh, &buf)) |why| return c.report.fail(name, "{s}", .{why}); + if (!every) return c.report.fail(name, "a prompt resumed from no kept caches ({d} tokens kept in all)", .{cached}); + c.report.pass(name, "{d} streams, {d} tokens, {d} prompt tokens from the kept caches", .{ again.replies.len, again.tokens(), cached }); +} + +/// A drafted run of every stream at once, the third time: once its shapes are met, rounds replay graphs. +fn replayShare(c: *Ctx) void { + const name = "lanes short greedy: rounds replayed"; + if (c.tp() and !c.e.o.graphs) return c.report.skip(name, "rounds under tp run eager unless the policy says graphs=on"); + if (!c.e.o.graphs) return c.report.skip(name, "graphs are off"); + const job: Session.Job = .{ .prompts = c.short, .max_new = c.tokens }; + var done: Session.Done = undefined; + for (0..3) |_| done = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + const share = 100.0 * @as(f64, @floatFromInt(done.replayed)) / @as(f64, @floatFromInt(@max(done.rounds, 1))); + if (share < 99.0) return c.report.fail(name, "{d:.1}% of {d} rounds replayed", .{ share, done.rounds }); + c.report.pass(name, "{d:.1}% of {d} rounds replayed, {d:.0} us a round submitting", .{ share, done.rounds, @as(f64, @floatFromInt(done.submit_ns)) / @as(f64, @floatFromInt(@max(done.rounds, 1))) / 1e3 }); +} diff --git a/zig/tests/qwen35/check_radix.zig b/zig/tests/qwen35/check_radix.zig new file mode 100644 index 00000000000..8119f81b310 --- /dev/null +++ b/zig/tests/qwen35/check_radix.zig @@ -0,0 +1,260 @@ +//! The prefix tree's checks of `check`: shared prefixes equal fresh runs, copy on write, and no page leaks. + +const std = @import("std"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const check_ctx = @import("check_ctx.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); + +const Ctx = check_ctx.Ctx; +const Prompt = ids_file.Prompt; +const Session = lanes_session.Session; +const pages = qwen35.pages; + +/// Tokens of the system prompt the requests share, and how many questions follow it. +const system_len = 1100; +const questions = 8; +/// Of those, the ones whose conversation goes on a turn. +const turns = 4; +/// Pages the tree checks leave room for beside the streams'. +pub const tree_pages = 600; +/// Snapshots the stress keeps, and the streams its last pass runs at once: every question, turn and branch. +pub const slots = 8; +pub const most_streams = questions + turns + 2; + +/// Tokens of the question of each request of the memory line, and how far apart they start. +const long_tail = 320; +const tail_step = 16; + +/// Positions the longest request of the tree checks takes, replies of `tokens` tokens included. +pub fn capacity(tokens: u32) usize { + return system_len + long_tail + 2 * tokens + 64; +} + +/// The requests the tree is built from: every one a shared system prompt and its own question. +fn singles(c: *Ctx) ![]const Prompt { + const sys = c.ids[0..system_len]; + const shared = try c.arena.dupe(u32, &.{system_len}); + const step = (c.ids.len - system_len) / questions; + const out = try c.arena.alloc(Prompt, questions); + for (out, 0..) |*p, j| { + const tail = c.ids[system_len + j * step ..][0 .. 24 + 8 * (j % 4)]; + p.* = .{ .name = try std.fmt.allocPrint(c.arena, "a{d}", .{j}), .ids = try std.mem.concat(c.arena, u32, &.{ sys, tail }), .shared = shared }; + } + return out; +} + +/// Requests that branch off the others: one inside the system prompt's last page, one in the middle of its pages. +fn branches(c: *Ctx, singles_set: []const Prompt) ![]const Prompt { + const sys = c.ids[0..system_len]; + const shared = try c.arena.dupe(u32, &.{system_len}); + const first = singles_set[0].ids[system_len..][0..20]; + const other = singles_set[questions - 1].ids[system_len..][0..30]; + const out = try c.arena.alloc(Prompt, 2); + out[0] = .{ .name = "c0", .ids = try std.mem.concat(c.arena, u32, &.{ sys, first, other }), .shared = shared }; + out[1] = .{ .name = "c1", .ids = try std.mem.concat(c.arena, u32, &.{ sys[0..640], c.ids[100..160] }) }; + return out; +} + +fn sameReplies(a: Session.Done, b: Session.Done, skip: usize, buf: []u8) ?[]const u8 { + for (a.replies[skip..], b.replies[skip..]) |x, y| { + const at = std.mem.indexOfDiff(u32, x.tokens, y.tokens) orelse continue; + return std.fmt.bufPrint(buf, "{s} differs at token {d}", .{ x.name, at }) catch "differs"; + } + return null; +} + +/// Bytes a copy of the caches at each kept mark would hold: marks past where each request resumed, repeats once. +fn copiedBytes(c: *Ctx, set: []const Prompt, replies: []const Session.Reply) usize { + const spec = c.e.model().spec; + var kept: std.ArrayList([]const u32) = .empty; + var bytes: usize = 0; + for (set, replies) |p, r| { + const marks = c.session.h.prefix.store.marks(c.arena, p.ids, r.cached, @intCast(p.ids.len / 2), p.shared, &.{}) catch return bytes; + for (marks) |m| { + const ids = p.ids[0..m]; + const known = for (kept.items) |k| { + if (std.mem.eql(u32, k, ids)) break true; + } else false; + if (known) continue; + kept.append(c.arena, ids) catch return bytes; + bytes += qwen35.memory.stateBytes(spec, c.e.model().act.size(), m); + } + } + return bytes; +} + +fn mib(bytes: usize) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 20); +} + +pub fn run(c: *Ctx) void { + stress(c); + memoryLine(c); + if (c.tp()) { + c.report.skip("radix: a resumed page equals a fresh one", "a prompt pass runs on one rank"); + c.report.skip("radix: a shared page is copied before a write", "the copy runs on one rank"); + return; + } + resumedPages(c); + copyOnWrite(c); +} + +/// Requests branching from shared prefixes, each against its own fresh run, alone and then all together. +fn stress(c: *Ctx) void { + const name = "radix stress"; + if (c.ids.len < system_len + 8 * questions) return c.report.skip(name, "too few ids"); + const h = c.session.h; + h.keepPrompts(0, 0); + h.keepPrompts(slots, 4 << 30); + defer h.keepPrompts(0, 0); + const first = singles(c) catch |err| return c.report.broke(name, err); + const alone = c.session.run(c.arena, .{ .prompts = first, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + // the next turn of some conversations, and the branches + const next = lanes_session.extend(c.arena, first[0..turns], alone.replies[0..turns]) catch |err| return c.report.broke(name, err); + const branched = branches(c, first) catch |err| return c.report.broke(name, err); + const second = std.mem.concat(c.arena, Prompt, &.{ next, branched }) catch |err| return c.report.broke(name, err); + const more = c.session.run(c.arena, .{ .prompts = second, .max_new = c.tokens, .solo = true }) catch |err| return c.report.broke(name, err); + const every = std.mem.concat(c.arena, Prompt, &.{ first, second }) catch |err| return c.report.broke(name, err); + // all of them again at once, on the warm tree + const together = c.session.run(c.arena, .{ .prompts = every, .max_new = c.tokens }) catch |err| return c.report.broke(name, err); + const fresh = c.session.run(c.arena, .{ .prompts = every, .max_new = c.tokens, .solo = true, .drafts = false }) catch |err| return c.report.broke(name, err); + var buf: [128]u8 = undefined; + const label = std.fmt.allocPrint(c.arena, "radix: {d} requests, resumed == fresh", .{every.len}) catch return; + if (sameReplies(alone, .{ .replies = fresh.replies[0..first.len], .seconds = 0, .rounds = 0, .replayed = 0, .submit_ns = 0, .spent = fresh.spent, .calls = fresh.calls }, 0, &buf)) |why| return c.report.fail(label, "{s}", .{why}); + if (sameReplies(more, .{ .replies = fresh.replies[first.len..], .seconds = 0, .rounds = 0, .replayed = 0, .submit_ns = 0, .spent = fresh.spent, .calls = fresh.calls }, 0, &buf)) |why| return c.report.fail(label, "{s}", .{why}); + var resumed: usize = 0; + var edges = true; + for ([_][]const Session.Reply{ alone.replies, more.replies, together.replies }) |set| for (set) |r| { + edges = edges and r.cached % pages.tokens == 0; + resumed += @intFromBool(r.cached > 0); + }; + c.report.pass(label, "{d} of {d} resumed, {d} tokens each", .{ resumed, alone.replies.len + more.replies.len + together.replies.len, c.tokens }); + if (sameReplies(together, fresh, 0, &buf)) |why| return c.report.fail("radix: all together == fresh", "{s}", .{why}); + c.report.pass("radix: all together == fresh", "{d} streams, {d} drafts accepted", .{ together.replies.len, together.accepted() }); + if (!edges) c.report.fail("radix: spans start on page edges", "a request resumed off a page edge", .{}) else c.report.pass("radix: spans start on page edges", "every resume at a multiple of {d}", .{pages.tokens}); + // the requests after the first take the system prompt's whole pages from the tree + const want: usize = system_len / pages.tokens * pages.tokens; + var short: usize = 0; + for (alone.replies[1..]) |r| short += @intFromBool(r.cached != want); + if (short > 0) c.report.fail("radix: the system prompt is shared", "{d} of {d} requests after the first did not resume at {d}", .{ short, alone.replies.len - 1, want }) else c.report.pass("radix: the system prompt is shared", "{d} requests resumed at {d} of {d} tokens", .{ alone.replies.len - 1, want, system_len }); +} + +/// What `questions` requests sharing one system prompt leave in the tree, against per-cut copies of the caches. +fn memoryLine(c: *Ctx) void { + const name = "radix memory"; + if (c.ids.len < system_len + tail_step * questions + long_tail) return c.report.skip(name, "too few ids"); + const h = c.session.h; + h.keepPrompts(0, 0); + h.keepPrompts(2 * questions, 2 << 30); + defer h.keepPrompts(0, 0); + const sys = c.ids[0..system_len]; + const shared = c.arena.dupe(u32, &.{system_len}) catch return; + const set = c.arena.alloc(Prompt, questions) catch return; + for (set, 0..) |*p, j| { + const tail = c.ids[system_len + j * tail_step ..][0..long_tail]; + p.* = .{ .name = std.fmt.allocPrint(c.arena, "q{d}", .{j}) catch return, .ids = std.mem.concat(c.arena, u32, &.{ sys, tail }) catch return, .shared = shared }; + } + const done = c.session.run(c.arena, .{ .prompts = set, .max_new = 1, .solo = true }) catch |err| return c.report.broke(name, err); + const tree = &h.prefix.store.tree; + const copied = copiedBytes(c, set, done.replies); + const unique = pagesBytes(c, tree.held_pages); + const states = tree.held() - unique; + var cached: usize = 0; + for (done.replies) |r| cached += r.cached; + c.report.pass(name, "{d} requests sharing {d} system tokens, {d} tokens each: the tree holds {d:.1} MiB ({d} pages {d:.1} MiB, {d} snapshots {d:.1} MiB); copies of the caches at each cut held {d:.1} MiB; {d} prompt tokens came from the tree", .{ set.len, system_len, set[0].ids.len, mib(tree.held()), tree.held_pages, mib(unique), tree.snaps, mib(states), mib(copied), cached }); +} + +fn pagesBytes(c: *Ctx, n: usize) u64 { + return n * c.e.pool.pageBytes(); +} + +/// The pages of a prompt resumed from the tree hold what a fresh prefill of it writes. +fn resumedPages(c: *Ctx) void { + const name = "radix: a resumed page equals a fresh one"; + const h = c.session.h; + const e = c.e; + h.keepPrompts(0, 0); + h.keepPrompts(8, 4 << 30); + defer h.keepPrompts(0, 0); + const set = singles(c) catch |err| return c.report.broke(name, err); + // the first run keeps the system prompt, the second resumes from it + _ = c.session.run(c.arena, .{ .prompts = set[0..1], .max_new = 1, .solo = true }) catch |err| return c.report.broke(name, err); + const prompt = set[1].ids; + var st = lanes.Stream.init(c.gpa, .{ .id = "resumed", .prompt = prompt, .max_new = 1, .history_len = @intCast(prompt.len / 2), .shared_prefixes = set[1].shared }) catch |err| return c.report.broke(name, err); + defer st.deinit(c.gpa); + const be = h.backend(); + be.prefill(&st) catch |err| return c.report.broke(name, err); + defer be.release(&st); + if (st.cached == 0) return c.report.fail(name, "the prompt resumed from nothing", .{}); + const lane = h.lanes.get(&st) orelse return c.report.fail(name, "no lane", .{}); + var fresh = e.newCaches(prompt.len + 8) catch |err| return c.report.broke(name, err); + defer fresh.deinit(c.gpa); + _ = e.prefill(&fresh, prompt, 0, null, .{ .sampling = null, .position = prompt.len }, null) catch |err| return c.report.broke(name, err); + e.drain(); + const m = e.model(); + const layer_bytes = e.pool.layerBytes(); + const row = m.spec.head_dim * m.act.size(); + const mine = c.arena.alloc(u8, 2 * layer_bytes) catch return; + const theirs = c.arena.alloc(u8, 2 * layer_bytes) catch return; + var compared: usize = 0; + for (0..m.spec.n_layers) |layer| { + if (!m.spec.full(layer)) continue; + for (0..pages.pagesFor(prompt.len)) |p| { + e.pool.read(layer, lane.caches.table.items[p], mine) catch |err| return c.report.broke(name, err); + e.pool.read(layer, fresh.table.items[p], theirs) catch |err| return c.report.broke(name, err); + const used = @min(pages.tokens, prompt.len - p * pages.tokens); + for ([_]usize{ 0, layer_bytes }) |half| for (0..m.spec.kv_heads) |head| { + const at = half + head * pages.tokens * row; + if (!std.mem.eql(u8, mine[at..][0 .. used * row], theirs[at..][0 .. used * row])) return c.report.fail(name, "layer {d}, page {d}, head {d} differs", .{ layer, p, head }); + }; + compared += 1; + } + } + const per_layer = pages.pagesFor(prompt.len); + c.report.pass(name, "{d} pages of {d} tokens in each of {d} attention layers, the first {d} from the tree, all equal", .{ per_layer, prompt.len, compared / per_layer, st.cached / pages.tokens }); +} + +/// A page two streams hold is copied before one writes it, and the copy holds the same bytes. +fn copyOnWrite(c: *Ctx) void { + const name = "radix: a shared page is copied before a write"; + const e = c.e; + const m = e.model(); + const len = pages.tokens + 36; + var first = e.newCaches(2 * pages.tokens) catch |err| return c.report.broke(name, err); + defer first.deinit(c.gpa); + _ = e.prefill(&first, c.ids[0..len], 0, null, .{ .sampling = null, .position = len }, null) catch |err| return c.report.broke(name, err); + e.drain(); + var second = e.emptyCaches(2 * pages.tokens) catch |err| return c.report.broke(name, err); + defer second.deinit(c.gpa); + for (first.table.items[0..2]) |id| e.pool.retain(id); + second.set(c.gpa, 0, first.table.items[0..2]) catch |err| return c.report.broke(name, err); + var done: std.ArrayList([3]u32) = .empty; + defer done.deinit(c.gpa); + // a write at position 100 lands in the second page, which both hold + second.writable(&done, c.gpa, 100, 101, e.stream.handle) catch |err| return c.report.broke(name, err); + e.drain(); + if (done.items.len != 1 or done.items[0][0] != 1) return c.report.fail(name, "{d} pages copied", .{done.items.len}); + if (second.table.items[0] != first.table.items[0] or second.table.items[1] == first.table.items[1]) return c.report.fail(name, "the wrong pages were copied", .{}); + const layer_bytes = e.pool.layerBytes(); + const a = c.arena.alloc(u8, 2 * layer_bytes) catch return; + const b = c.arena.alloc(u8, 2 * layer_bytes) catch return; + for (0..m.spec.n_layers) |layer| { + if (!m.spec.full(layer)) continue; + e.pool.read(layer, first.table.items[1], a) catch |err| return c.report.broke(name, err); + e.pool.read(layer, second.table.items[1], b) catch |err| return c.report.broke(name, err); + if (!std.mem.eql(u8, a, b)) return c.report.fail(name, "layer {d}: the copy differs", .{layer}); + } + if (e.pool.ids.refs[first.table.items[0]] != 2 or e.pool.ids.refs[first.table.items[1]] != 1) return c.report.fail(name, "the holders were not counted", .{}); + c.report.pass(name, "page 1 copied, page 0 still shared, the copy equal in every attention layer", .{}); +} + +/// After every run the pool holds the pages it started with: no stream and no tree entry leaked one. +pub fn leaked(c: *Ctx) void { + const name = "radix: every page comes back"; + c.session.h.keepPrompts(0, 0); + const used = c.e.pool.ids.used(); + if (used != c.pages_at_start or c.e.pool.ids.reserved != 0) return c.report.fail(name, "{d} pages held and {d} promised after the runs, {d} held before", .{ used, c.e.pool.ids.reserved, c.pages_at_start }); + c.report.pass(name, "{d} of {d} pages held after the runs, as before", .{ used, c.e.pool.count }); +} diff --git a/zig/tests/qwen35/check_report.zig b/zig/tests/qwen35/check_report.zig new file mode 100644 index 00000000000..8137c561d60 --- /dev/null +++ b/zig/tests/qwen35/check_report.zig @@ -0,0 +1,33 @@ +//! The lines of a `check` run: one a check, PASS, FAIL or SKIP with its numbers, and the summary. + +const std = @import("std"); + +pub const Report = struct { + passed: usize = 0, + failed: usize = 0, + skipped: usize = 0, + + pub fn pass(r: *Report, name: []const u8, comptime fmt: []const u8, args: anytype) void { + r.passed += 1; + std.debug.print("PASS {s}: " ++ fmt ++ "\n", .{name} ++ args); + } + + pub fn fail(r: *Report, name: []const u8, comptime fmt: []const u8, args: anytype) void { + r.failed += 1; + std.debug.print("FAIL {s}: " ++ fmt ++ "\n", .{name} ++ args); + } + + pub fn skip(r: *Report, name: []const u8, why: []const u8) void { + r.skipped += 1; + std.debug.print("SKIP {s}: {s}\n", .{ name, why }); + } + + /// A check that stopped on an error instead of a verdict. + pub fn broke(r: *Report, name: []const u8, err: anyerror) void { + r.fail(name, "error.{s}", .{@errorName(err)}); + } + + pub fn summary(r: Report, seconds: f64) void { + std.debug.print("check {s}: {d} passed, {d} failed, {d} skipped in {d:.1} s\n", .{ if (r.failed == 0) "PASS" else "FAIL", r.passed, r.failed, r.skipped, seconds }); + } +}; diff --git a/zig/tests/qwen35/check_speed.zig b/zig/tests/qwen35/check_speed.zig new file mode 100644 index 00000000000..c4b3807b156 --- /dev/null +++ b/zig/tests/qwen35/check_speed.zig @@ -0,0 +1,66 @@ +//! The speed lines of `check`: cold prefill and decode with drafts off and on; they fail only when a run does. + +const std = @import("std"); +const check_ctx = @import("check_ctx.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); +const prefill_run = @import("prefill_run.zig"); + +const Ctx = check_ctx.Ctx; +const Session = lanes_session.Session; + +/// The longest prompt `run` times: the engine's capacity must hold it. +pub const longest_prefill = 8192; + +const prefill_lengths = [_]usize{ 13, 2048, longest_prefill }; + +pub fn run(c: *Ctx) void { + prefill(c); + for ([_]bool{ false, true }) |drafts| { + decode(c, drafts, c.short[0..1], 256); + decode(c, drafts, c.short, 128); + } +} + +fn prefill(c: *Ctx) void { + if (c.tp()) return c.report.skip("speed prefill", "a prompt pass runs on one rank"); + const prompt = ids_file.synthetic(c.arena, longest_prefill) catch |err| return c.report.broke("speed prefill", err); + for (prefill_lengths) |len| { + const name = std.fmt.allocPrint(c.arena, "speed prefill {d} tokens", .{len}) catch return; + const t = prefill_run.seconds(c.gpa, c.io, c.e, prompt[0..len]) catch |err| { + c.report.broke(name, err); + continue; + }; + c.report.pass(name, "{d:.3} s, {d:.0} tok/s", .{ t, @as(f64, @floatFromInt(len)) / t }); + } +} + +/// `prompts` generating `max_new` tokens each, the last of three runs (the first two capture the graphs). +fn decode(c: *Ctx, drafts: bool, prompts: []const ids_file.Prompt, max_new: u32) void { + const name = std.fmt.allocPrint(c.arena, "speed decode {d} stream{s}, drafts {s}", .{ prompts.len, if (prompts.len == 1) "" else "s", if (drafts) "on" else "off" }) catch return; + const job: Session.Job = .{ .prompts = prompts, .max_new = max_new, .drafts = drafts }; + for (0..2) |_| _ = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + const done = c.session.run(c.arena, job) catch |err| return c.report.broke(name, err); + var rounds: u64 = 0; + for (done.replies) |r| rounds += r.rounds; + const n = done.tokens(); + const shared: f64 = @floatFromInt(@max(done.rounds, 1)); + c.report.pass(name, "{d:.1} tok/s, {d} tokens in {d:.3} s, {d:.2} tokens a stream round, {d:.1}% of {d} rounds replayed, {d:.0} us a round submitting, {d:.0} us a round in all (backend, a call: verify {d:.0} us, keep {d:.0} us, draft {d:.0} us)", .{ + @as(f64, @floatFromInt(n)) / done.seconds, + n, + done.seconds, + @as(f64, @floatFromInt(n)) / @as(f64, @floatFromInt(@max(rounds, 1))), + 100.0 * @as(f64, @floatFromInt(done.replayed)) / shared, + done.rounds, + @as(f64, @floatFromInt(done.submit_ns)) / shared / 1e3, + done.seconds * 1e6 / shared, + each(done, 0), + each(done, 1), + each(done, 2), + }); +} + +/// Microseconds a backend call of kind `which` (verify, keep, draft) took on average. +fn each(d: Session.Done, which: usize) f64 { + return @as(f64, @floatFromInt(d.spent[which])) / @as(f64, @floatFromInt(@max(d.calls[which], 1))) / 1e3; +} diff --git a/zig/tests/qwen35/draw_run.zig b/zig/tests/qwen35/draw_run.zig new file mode 100644 index 00000000000..184f6dc45cf --- /dev/null +++ b/zig/tests/qwen35/draw_run.zig @@ -0,0 +1,101 @@ +//! `draw`: the device argmax and top-k kernels against the host's (sample.zig) on tie-heavy rows (GPU). + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); + +const sample = qwen35.sample; + +const Order = struct { + row: []const u16, + dtype: sample.Dtype, + + fn less(c: Order, a: u32, b: u32) bool { + const va = sample.widen(c.row, c.dtype, a); + const vb = sample.widen(c.row, c.dtype, b); + return va > vb or (va == vb and a < b); + } +}; + +pub fn run(gpa: std.mem.Allocator) !void { + var d = try hip.Runtime.open(); + defer d.close(); + var ctx = try hip.Context.init(&d, 0); + defer ctx.deinit(); + const caps = try hip.Device.kernelCaps(&d, 0); + var notes: hip.Policy.Notes = .{}; + var lib = try hip.Launcher.load(&d, (try hip.Policy.resolve("", .current, ¬es)).choices(), hip.kernels.images); + defer lib.unload(); + var stream = try hip.Stream.init(&d); + defer stream.deinit(); + var arena = try hip.Arena.init(&d, 1 << 20); + defer arena.deinit(); + const o: hip.ops.Ops = .{ .l = &lib, .bf16 = caps.act == .bf16, .stream = stream.handle, .arena = &arena }; + const dtype: sample.Dtype = if (caps.act == .f16) .f16 else .bf16; + const kind: hip.ops.Kind = if (caps.act == .f16) .f16 else .bf16; + var prng = std.Random.DefaultPrng.init(7); + const rnd = prng.random(); + const rows = 5; + for ([_]usize{ 1000, 4099, 248320 }) |vocab| { + // few distinct values (both zeros among them) so the k-th value is shared by many ids + const palette: [8]u16 = if (dtype == .f16) + .{ 0x0000, 0x8000, 0x3c00, 0xbc00, 0x4000, 0x4400, 0xc000, 0x3800 } + else + .{ 0x0000, 0x8000, 0x3f80, 0xbf80, 0x4000, 0x4080, 0xc000, 0x3f00 }; + const host = try gpa.alloc(u16, rows * vocab); + defer gpa.free(host); + for (host, 0..) |*v, i| v.* = if (i / vocab % 2 == 0) palette[rnd.uintLessThan(usize, palette.len)] else rnd.int(u16) & 0xbfff; + var logits = try hip.DeviceBuffer.alloc(&d, host.len * 2); + defer logits.free(); + try logits.upload(0, std.mem.sliceAsBytes(host)); + const ks = [rows]i32{ 1, 8, 28, 100, 0 }; + const stride = 100; + var ks_dev = try hip.DeviceBuffer.alloc(&d, rows * 4); + defer ks_dev.free(); + try ks_dev.upload(0, std.mem.sliceAsBytes(&ks)); + var arg_dev = try hip.DeviceBuffer.alloc(&d, rows * 4); + defer arg_dev.free(); + var ids_dev = try hip.DeviceBuffer.alloc(&d, rows * stride * 4); + defer ids_dev.free(); + var vals_dev = try hip.DeviceBuffer.alloc(&d, rows * stride * 2); + defer vals_dev.free(); + const t: hip.ops.Tensor = .{ .ptr = logits.base(), .kind = kind }; + try o.argmaxRows(t, rows, vocab, arg_dev.base()); + try o.topkRows(t, rows, vocab, ks_dev.base(), stride, ids_dev.base(), vals_dev.base()); + try stream.synchronize(); + var arg: [rows]i32 = undefined; + try arg_dev.download(0, std.mem.sliceAsBytes(&arg)); + const ids = try gpa.alloc(i32, rows * stride); + defer gpa.free(ids); + try ids_dev.download(0, std.mem.sliceAsBytes(ids)); + const vals = try gpa.alloc(u16, rows * stride); + defer gpa.free(vals); + try vals_dev.download(0, std.mem.sliceAsBytes(vals)); + for (0..rows) |r| { + const row = host[r * vocab ..][0..vocab]; + if (sample.argmax(row, dtype) != arg[r]) { + std.debug.print("argmax row {d} vocab {d}: device {d}, host {d}\n", .{ r, vocab, arg[r], sample.argmax(row, dtype) }); + return error.Mismatch; + } + const k: usize = @intCast(ks[r]); + if (k == 0) continue; + // the host's selection: sort every id by (value desc, id asc) and take k + const order = try gpa.alloc(u32, vocab); + defer gpa.free(order); + for (order, 0..) |*x, i| x.* = @intCast(i); + std.mem.sort(u32, order, Order{ .row = row, .dtype = dtype }, Order.less); + var want: std.AutoHashMapUnmanaged(u32, void) = .empty; + defer want.deinit(gpa); + for (order[0..k]) |id| try want.put(gpa, id, {}); + for (0..k) |j| { + const id: u32 = @intCast(ids[r * stride + j]); + if (!want.remove(id) or vals[r * stride + j] != row[id]) { + std.debug.print("top-{d} row {d} vocab {d}: id {d} is not the host's pick\n", .{ k, r, vocab, id }); + return error.Mismatch; + } + } + } + std.debug.print("vocab {d}: argmax and top-k of {d} rows equal the host's\n", .{ vocab, rows }); + } + std.debug.print("OK\n", .{}); +} diff --git a/zig/tests/qwen35/group.zig b/zig/tests/qwen35/group.zig new file mode 100644 index 00000000000..09f00b2a6ee --- /dev/null +++ b/zig/tests/qwen35/group.zig @@ -0,0 +1,94 @@ +//! The tensor-parallel group of one test process: its options, the link to the other ranks and the RCCL bootstrap. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); + +/// One rank of `world`, joined at `master:port`; every rank runs the same command. +pub const Group = struct { + rank: usize = 0, + world: usize = 1, + master: []const u8 = "127.0.0.1", + port: u16 = 29551, + /// The policy flags, `key=value,...`. + policy: []const u8 = "", + + /// Takes the option at `args[i.*]` if it is one of the group's, moving `i` to its value. + pub fn option(g: *Group, args: []const [:0]const u8, i: *usize) !bool { + const name = args[i.*]; + const known = [_][]const u8{ "--tp", "--rank", "--master", "--port", "--policy" }; + const index = for (known, 0..) |k, n| { + if (std.mem.eql(u8, name, k)) break n; + } else return false; + i.* += 1; + if (i.* >= args.len) return error.MissingArgument; + const v = args[i.*]; + switch (index) { + 0 => g.world = try std.fmt.parseInt(usize, v, 10), + 1 => g.rank = try std.fmt.parseInt(usize, v, 10), + 2 => g.master = v, + 3 => g.port = try std.fmt.parseInt(u16, v, 10), + else => g.policy = v, + } + return true; + } + + /// What a group of more than one rank holds besides the engine: close it after the engine. + pub const Joined = struct { + rccl: ?hip.rccl.Rccl = null, + link: hip.link.Link = undefined, + id: ?hip.rccl.UniqueId = null, + world: usize = 1, + /// What every rank runs under: rank 0's. + policy: hip.Policy = .{}, + + pub fn close(j: *Joined) void { + if (j.world > 1) j.link.close(); + if (j.rccl) |*r| r.close(); + } + }; + + /// The unique id starts RCCL's bootstrap thread: the library stays loaded until the engine is gone. + pub fn join(g: Group, io: std.Io) !Joined { + const found = try resolve(g.policy, @intCast(g.rank)); + var j: Joined = .{ .world = g.world, .policy = found.policy }; + if (g.world < 2) return j; + j.rccl = try hip.rccl.Rccl.open(j.policy.rccl_lib.slice()); + errdefer j.rccl.?.close(); + const pair = try hip.link.Link.open(io, g.rank, g.world, g.master, g.port, if (g.rank == 0) try j.rccl.?.uniqueId() else undefined, .{ .caps = hip.Device.groupId(found.caps), .policy = j.policy.words() }); + j.link, j.id, const hello = pair; + if (g.rank != 0) j.policy = hip.Policy.fromWords(hello.policy, j.policy); + return j; + } + + /// The engine on the device of this rank's number, with its share of the model. + pub fn engine(g: Group, gpa: std.mem.Allocator, io: std.Io, dir: []const u8, j: Joined, o: qwen35.engine.Options) !*qwen35.engine.Engine { + var own = o; + own.device = @intCast(g.rank); + own.rank = g.rank; + own.world = g.world; + own.id = j.id; + own.policy = j.policy; + return qwen35.engine.Engine.open(gpa, io, dir, own); + } +}; + +/// The policy of a test run on `device` and its caps: the GPU's defaults, `flags`, the variables and TF_POLICY, logged. +pub fn resolve(flags: []const u8, device: c_int) !struct { policy: hip.Policy, caps: hip.Caps } { + var d = try hip.Runtime.open(); + defer d.close(); + var ctx = try hip.Context.init(&d, device); + defer ctx.deinit(); + const caps = try hip.Device.kernelCaps(&d, device); + var notes: hip.Policy.Notes = .{}; + const policy = try hip.Policy.resolve(flags, .current, ¬es); + std.debug.print("policy {f} {s}\n", .{ policy, notes.text() }); + return .{ .policy = policy, .caps = caps }; +} + +/// A rank above 0 runs what rank 0 sends until it says stop. +pub fn follow(gpa: std.mem.Allocator, e: *qwen35.engine.Engine, j: *const Group.Joined) !void { + var w = try qwen35.worker.Worker.init(gpa, e); + defer w.deinit(); + return w.follow(&j.link); +} diff --git a/zig/tests/qwen35/ids_file.zig b/zig/tests/qwen35/ids_file.zig new file mode 100644 index 00000000000..f856035953f --- /dev/null +++ b/zig/tests/qwen35/ids_file.zig @@ -0,0 +1,61 @@ +//! Token ids from a .npy file (int32 or int64), and the prompt sets the checks run. + +const std = @import("std"); +const npy = @import("npy"); + +/// The ids of `path`, owned by the caller. +pub fn load(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u32 { + const file = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 28)); + defer gpa.free(file); + const a = try npy.parse(file); + const ids = try gpa.alloc(u32, a.count()); + for (ids, 0..) |*t, i| t.* = if (std.mem.eql(u8, a.descr, " [--solo] [--no-drafts] [--resume PREFIX] [--tp N --rank R]` + +const std = @import("std"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const group_mod = @import("group.zig"); +const ids_file = @import("ids_file.zig"); +const lanes_session = @import("lanes_session.zig"); + +const Session = lanes_session.Session; + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 3) return error.MissingArgument; + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const max_tokens = try std.fmt.parseInt(u32, args[2], 10); + var job: Session.Job = .{ .prompts = try ids_file.read(arena, io, args[1]), .max_new = max_tokens }; + var report: ?[]const u8 = null; + var resume_to: ?[]const u8 = null; + var group: group_mod.Group = .{}; + var i: usize = 3; + while (i < args.len) : (i += 1) { + if (try group.option(args, &i)) continue; + if (std.mem.eql(u8, args[i], "--resume")) { + i += 1; + resume_to = args[i]; + } else if (std.mem.eql(u8, args[i], "--solo")) job.solo = true else if (std.mem.eql(u8, args[i], "--no-drafts")) job.drafts = false else if (std.mem.eql(u8, args[i], "--report")) { + i += 1; + report = args[i]; + } else if (std.mem.eql(u8, args[i], "--seed")) { + i += 1; + job.sampling = .{ .seed = try std.fmt.parseInt(u64, args[i], 10), .temperature = if (job.sampling) |s| s.temperature else 1.0 }; + } else if (std.mem.eql(u8, args[i], "--temperature")) { + i += 1; + var s = job.sampling orelse lanes.Sampling{ .seed = 0 }; + s.temperature = try std.fmt.parseFloat(f64, args[i]); + job.sampling = s; + } else return error.UnknownOption; + } + var joined = try group.join(io); + defer joined.close(); + const e = try group.engine(gpa, io, args[0], joined, .{ .capacity = ids_file.longest(job.prompts) + 2 * max_tokens + 64, .prompt_rows = ids_file.longest(job.prompts) + 2 * max_tokens + 64, .streams = job.prompts.len, .batch_rows = @max(32, job.prompts.len * qwen35.hip_lanes.Hip.max_window) }); + defer e.deinit(); + if (group.rank > 0) return group_mod.follow(gpa, e, &joined); + var s: Session = undefined; + try s.init(gpa, io, e, if (group.world > 1) &joined.link else null); + defer s.deinit(); + if (resume_to != null) s.h.keepPrompts(8, 1 << 30); + const done = try s.run(arena, job); + for (done.replies) |r| std.debug.print("{s}: {d} tokens, rounds {d}, accepted {d}\n", .{ r.name, r.tokens.len, r.rounds, r.accepted }); + std.debug.print("{s}: {d} streams, {d} tokens in {d:.3} s, {d:.1} tok/s\n", .{ if (job.solo) "solo" else "together", done.replies.len, done.tokens(), done.seconds, @as(f64, @floatFromInt(done.tokens())) / done.seconds }); + if (report) |path| try writeJson(gpa, io, path, try named(arena, done.replies)); + if (resume_to) |prefix| try again(gpa, io, &s, arena, prefix, job, done); +} + +fn writeJson(gpa: std.mem.Allocator, io: std.Io, path: []const u8, value: anytype) !void { + const json = try std.json.Stringify.valueAlloc(gpa, value, .{}); + defer gpa.free(json); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = json }); +} + +const Named = struct { name: []const u8, tokens: []const u32 }; +const Cached = struct { name: []const u8, cached: u32, tokens: []const u32 }; + +fn named(arena: std.mem.Allocator, rs: []const Session.Reply) ![]const Named { + const out = try arena.alloc(Named, rs.len); + for (out, rs) |*o, r| o.* = .{ .name = r.name, .tokens = r.tokens }; + return out; +} + +/// Each prompt again, extended by its reply and its own first tokens, one at a time on the kept caches. +fn again(gpa: std.mem.Allocator, io: std.Io, s: *Session, arena: std.mem.Allocator, prefix: []const u8, first: Session.Job, done: Session.Done) !void { + const extended = try lanes_session.extend(arena, first.prompts, done.replies); + var second = first; + second.prompts = extended; + second.solo = true; + const out = try s.run(arena, second); + const kept = try arena.alloc(Cached, out.replies.len); + const prompts = try arena.alloc(Named, extended.len); + for (kept, prompts, out.replies, extended) |*k, *n, r, p| { + std.debug.print("{s} again: {d} prompt tokens, {d} from the kept caches, {d} tokens\n", .{ r.name, p.ids.len, r.cached, r.tokens.len }); + k.* = .{ .name = r.name, .cached = r.cached, .tokens = r.tokens }; + n.* = .{ .name = p.name, .tokens = p.ids }; + } + try writeJson(gpa, io, try std.fmt.allocPrint(arena, "{s}-prompts.json", .{prefix}), prompts); + try writeJson(gpa, io, try std.fmt.allocPrint(arena, "{s}-replies.json", .{prefix}), kept); +} diff --git a/zig/tests/qwen35/lanes_session.zig b/zig/tests/qwen35/lanes_session.zig new file mode 100644 index 00000000000..1953b7374bd --- /dev/null +++ b/zig/tests/qwen35/lanes_session.zig @@ -0,0 +1,118 @@ +//! Prompts through the lane core on one engine's HIP backend, as often as asked, each run's replies kept in memory. + +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); + +const Hip = qwen35.hip_lanes.Hip; + +pub const Session = struct { + gpa: std.mem.Allocator, + io: std.Io, + e: *qwen35.engine.Engine, + h: *Hip, + cfg: lanes.Config, + clock: lanes.backend.WallClock, + + /// Rank 0 of a group of `link`'s ranks (null: a lone rank) runs the core; the others follow it. + pub fn init(s: *Session, gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, link: ?*const hip.link.Link) !void { + const h = try Hip.init(gpa, e); + errdefer h.deinit(); + if (link) |l| h.withLink(l); + if (link == null) h.measure(); + const rows = Hip.max_window; + s.* = .{ .gpa = gpa, .io = io, .e = e, .h = h, .cfg = try lanes.Config.init(gpa, h.facts(), rows, rows - 1), .clock = .{ .io = io } }; + } + + pub fn deinit(s: *Session) void { + s.cfg.deinit(s.gpa); + s.h.deinit(); + } + + pub const Job = struct { + prompts: []const ids_file.Prompt, + max_new: u32, + sampling: ?lanes.Sampling = null, + drafts: bool = true, + /// One stream at a time instead of all at once. + solo: bool = false, + }; + + pub const Reply = struct { name: []const u8, tokens: []const u32, rounds: u64, accepted: u64, cached: u32 }; + + pub const Done = struct { + replies: []const Reply, + seconds: f64, + /// Rounds run, rounds replayed from graphs and the host's nanoseconds submitting them, during the run. + rounds: u64, + replayed: u64, + submit_ns: u64, + /// Nanoseconds and calls of the backend's verifies, keeps and drafts. + spent: [3]u64, + calls: [3]u64, + + pub fn tokens(d: Done) usize { + var n: usize = 0; + for (d.replies) |r| n += r.tokens.len; + return n; + } + + pub fn accepted(d: Done) u64 { + var n: u64 = 0; + for (d.replies) |r| n += r.accepted; + return n; + } + }; + + /// The job's replies, in the arena, with no end token (replies run out at `max_new`). + pub fn run(s: *Session, arena: std.mem.Allocator, job: Job) !Done { + const streams = try s.gpa.alloc(lanes.Stream, job.prompts.len); + defer s.gpa.free(streams); + var made: usize = 0; + defer for (streams[0..made]) |*st| st.deinit(s.gpa); + for (streams, job.prompts) |*st, p| { + st.* = try lanes.Stream.init(s.gpa, .{ .id = p.name, .prompt = p.ids, .max_new = job.max_new, .sampling = job.sampling, .drafts = job.drafts, .history_len = @intCast(p.ids.len / 2), .shared_prefixes = p.shared }); + made += 1; + } + const replayed = s.e.graphs.replayed; + const rounds = s.e.graphs.rounds; + const submit = s.e.graphs.submit_ns; + const spent = s.h.spent; + const calls = s.h.calls; + const t0 = std.Io.Clock.awake.now(s.io); + if (job.solo) { + for (streams) |*st| try s.finish(&.{st}); + } else { + const all = try s.gpa.alloc(*lanes.Stream, streams.len); + defer s.gpa.free(all); + for (all, streams) |*a, *st| a.* = st; + try s.finish(all); + } + const seconds = @as(f64, @floatFromInt(std.Io.Clock.awake.now(s.io).toNanoseconds() - t0.toNanoseconds())) / 1e9; + const out = try arena.alloc(Reply, streams.len); + for (out, streams, job.prompts) |*r, *st, p| r.* = .{ .name = p.name, .tokens = try arena.dupe(u32, st.emitted()), .rounds = st.rounds, .accepted = st.accepted, .cached = st.cached }; + return .{ .replies = out, .seconds = seconds, .rounds = s.e.graphs.rounds - rounds, .replayed = s.e.graphs.replayed - replayed, .submit_ns = s.e.graphs.submit_ns - submit, .spent = delta(s.h.spent, spent), .calls = delta(s.h.calls, calls) }; + } + + fn finish(s: *Session, streams: []const *lanes.Stream) !void { + var engine = lanes.Engine.init(s.gpa, &s.cfg, s.h.backend(), s.clock.clock()); + defer engine.deinit(); + for (streams) |st| try engine.addStream(st); + while (engine.live.items.len > 0) try engine.step(); + } +}; + +fn delta(now: [3]u64, before: [3]u64) [3]u64 { + var out: [3]u64 = undefined; + for (&out, now, before) |*o, a, b| o.* = a - b; + return out; +} + +/// Each prompt extended by its reply and its own first tokens: what a next turn sends. +pub fn extend(arena: std.mem.Allocator, prompts: []const ids_file.Prompt, replies: []const Session.Reply) ![]const ids_file.Prompt { + const out = try arena.alloc(ids_file.Prompt, prompts.len); + for (out, prompts, replies) |*o, p, r| o.* = .{ .name = p.name, .ids = try std.mem.concat(arena, u32, &.{ p.ids, r.tokens, p.ids[0..@min(p.ids.len, 4)] }), .shared = p.shared }; + return out; +} diff --git a/zig/tests/qwen35/layers.zig b/zig/tests/qwen35/layers.zig new file mode 100644 index 00000000000..57b1b88c962 --- /dev/null +++ b/zig/tests/qwen35/layers.zig @@ -0,0 +1,196 @@ +//! `layers [--tp N --rank R]`: the forward against qwen_rocm_dump.py's dump, byte for byte. + +const std = @import("std"); +const hip = @import("hip"); +const npy = @import("npy"); +const qwen35 = @import("qwen3_5"); + +const view = qwen35.view; +const Tensor = hip.ops.Tensor; + +const Gpu = struct { d: *const hip.Runtime, gpa: std.mem.Allocator, io: std.Io }; + +pub const Group = @import("group.zig").Group; + +/// One fixture file's data (the caller frees `bytes`). +fn read(g: Gpu, dir: []const u8, stem: []const u8, act: view.Kind) !struct { bytes: []u8, data: []const u8 } { + const name = try std.fmt.allocPrint(g.gpa, "{s}{s}", .{ stem, if (act == .bf16 and !std.mem.eql(u8, stem, "tokens") and !std.mem.eql(u8, stem, "sampled")) ".bf16.npy" else ".npy" }); + defer g.gpa.free(name); + const path = try std.fs.path.join(g.gpa, &.{ dir, name }); + defer g.gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(g.io, path, g.gpa, .limited(1 << 31)); + return .{ .bytes = bytes, .data = (try npy.parse(bytes)).data }; +} + +fn download(g: Gpu, ptr: u64, n: usize) ![]u8 { + const out = try g.gpa.alloc(u8, n); + try hip.runtime.check(g.d.api.hipMemcpyDtoH(out.ptr, @ptrFromInt(ptr), n)); + return out; +} + +/// The first differing value of two activation rows' bytes, or null. +fn firstDiff(got: []const u8, want: []const u8) ?usize { + const i = std.mem.indexOfDiff(u8, got, want) orelse return null; + return i / 2; +} + +const Check = struct { + g: Gpu, + want: []const u8, // (layers, rows, hidden) of the step + hidden: usize, + stream: hip.Stream, + failed: ?usize = null, + + fn layer(ctx: *anyopaque, index: usize, x: Tensor, rows: usize) anyerror!void { + const c: *Check = @ptrCast(@alignCast(ctx)); + try c.stream.synchronize(); + const n = rows * c.hidden * 2; + const got = try download(c.g, x.ptr, n); + defer c.g.gpa.free(got); + if (c.failed == null) if (firstDiff(got, c.want[index * n ..][0..n])) |at| { + std.debug.print("FAIL layer {d}: residual differs first at row {d} column {d}\n", .{ index, at / c.hidden, at % c.hidden }); + c.failed = index; + }; + } +}; + +pub fn run(g: Gpu, model_dir: []const u8, dir: []const u8, group: Group) !void { + var ctx = try hip.Context.init(g.d, @intCast(group.rank)); + defer ctx.deinit(); + // the oracle's sums are the reference kernels': the fixtures pin them whatever the environment says + var notes: hip.Policy.Notes = .{}; + const policy = try hip.Policy.resolve("kernels=reference", .none, ¬es); + // the unique id starts RCCL's bootstrap thread: the library stays loaded to the end + var rccl: ?hip.rccl.Rccl = null; + defer if (rccl) |*r| r.close(); + var link: hip.link.Link = undefined; + var comm: hip.rccl.Comm = undefined; + if (group.world > 1) { + rccl = try hip.rccl.Rccl.open(policy.rccl_lib.slice()); + const pair = try hip.link.Link.open(g.io, group.rank, group.world, group.master, group.port, if (group.rank == 0) try rccl.?.uniqueId() else undefined, .{ .caps = hip.Device.groupId(try hip.Device.kernelCaps(@constCast(g.d), @intCast(group.rank))), .policy = policy.words() }); + link = pair[0]; + comm = try hip.rccl.Comm.init(&rccl.?, pair[1], group.rank, group.world); + } + defer if (group.world > 1) { + comm.deinit(); + link.close(); + }; + const caps = try hip.Device.kernelCaps(@constCast(g.d), @intCast(group.rank)); + var lib = try hip.Launcher.load(g.d, policy.choices(), hip.kernels.images); + defer lib.unload(); + const act: view.Kind = if (caps.act == .f16) .f16 else .bf16; + const dtype: qwen35.sample.Dtype = if (act == .f16) .f16 else .bf16; + var model = try qwen35.Model.loadRank(g.gpa, g.io, g.d, model_dir, if (group.world > 1) .{ .rank = group.rank, .world = group.world } else null); + defer model.deinit(); + const br = try qwen35.bridge.Bridge.init(g.gpa, g.d, &model, act); + defer br.deinit(); + if (group.world > 1) br.model.tp = comm; + const m = &br.model; + const s = m.spec; + var stream = try hip.Stream.init(g.d); + defer stream.deinit(); + var arena = try hip.Arena.init(g.d, 2 << 30); + defer arena.deinit(); + const o: hip.ops.Ops = .{ .l = &lib, .bf16 = act == .bf16, .stream = stream.handle, .arena = &arena }; + + const tokens_f = try read(g, dir, "tokens", act); + defer g.gpa.free(tokens_f.bytes); + const sampled_f = try read(g, dir, "sampled", act); + defer g.gpa.free(sampled_f.bytes); + const tokens = std.mem.bytesAsSlice(i64, tokens_f.data); + const sampled = std.mem.bytesAsSlice(i64, sampled_f.data); + const len = tokens.len; + const positions = len + sampled.len + 1; + var pool = try qwen35.pages.Pool.init(g.gpa, g.d, m, qwen35.pages.pagesFor(positions) + 1, true); + defer pool.deinit(); + var caches = try qwen35.state.Caches.initFull(g.gpa, &pool, m, positions); + defer caches.deinit(g.gpa); + + const ids = try g.gpa.alloc(i32, len); + defer g.gpa.free(ids); + for (ids, tokens) |*i, t| i.* = @intCast(t); + var ids_dev = try hip.DeviceBuffer.fromHost(g.d, std.mem.sliceAsBytes(ids)); + defer ids_dev.free(); + + const want_layers = try read(g, dir, "prefill.layers", act); + defer g.gpa.free(want_layers.bytes); + var check: Check = .{ .g = g, .want = want_layers.data, .hidden = s.hidden, .stream = stream }; + const trace: qwen35.forward.Trace = .{ .ctx = &check, .layer = Check.layer }; + const hidden = try qwen35.forward.span(o, m, &caches, ids_dev.base(), len, 0, trace); + try stream.synchronize(); + if (check.failed) |l| return fail("prefill", l); + std.debug.print("PASS prefill: {d} rows, {d} layers' residuals equal\n", .{ len, s.n_layers }); + try compare(g, dir, "prefill.hidden", act, hidden.ptr, len * s.hidden * 2); + var token = try logitsToken(g, o, m, dir, "prefill.logits", act, dtype, hidden, len - 1); + try expectToken(token, sampled[0], "prefill"); + + // a decode step is a round of one row over a plan: the stream's slot, then the scratch slot + var plan_buf = try qwen35.plan.Buffer.init(g.d, 1, s.n_layers, pool.count); + defer plan_buf.deinit(); + var scratch = try qwen35.state.Caches.initFull(g.gpa, &pool, m, 1); + defer scratch.deinit(g.gpa); + const inputs = try g.gpa.alloc([2]u64, s.n_layers); + defer g.gpa.free(inputs); + for (0..sampled.len - 1) |step| { + arena.reset(); + try qwen35.window.kept(o, m, 1, inputs); + const pos = len + step; + const shape: qwen35.plan.Shape = .{ .rows = 1, .slots = 2, .span = @intCast(qwen35.plan.spanOf(pos + 1)) }; + const layout = qwen35.plan.Layout.of(1, 2, s.n_layers); + plan_buf.fill(layout, shape, &.{.{ .desc = caches.desc.base(), .pos = pos, .tokens = &.{token} }}, scratch.desc.base(), inputs); + try plan_buf.send(stream.handle, layout); + const round: qwen35.window.Round = .{ .plan = .{ .args = plan_buf.args(layout), .rows = 1, .slots = 2 }, .tokens = plan_buf.dev.base() + 4 * layout.tokens, .span = shape.span, .inputs = inputs }; + var name_buf: [32]u8 = undefined; + const stem = try std.fmt.bufPrint(&name_buf, "decode{d}", .{step}); + const want = try read(g, dir, try std.fmt.allocPrint(g.gpa, "{s}.layers", .{stem}), act); + defer g.gpa.free(want.bytes); + check = .{ .g = g, .want = want.data, .hidden = s.hidden, .stream = stream }; + const h = try qwen35.window.forward(o, m, round, trace); + try stream.synchronize(); + if (check.failed) |l| return fail(stem, l); + try compare(g, dir, try std.fmt.allocPrint(g.gpa, "{s}.hidden", .{stem}), act, h.ptr, s.hidden * 2); + token = try logitsToken(g, o, m, dir, try std.fmt.allocPrint(g.gpa, "{s}.logits", .{stem}), act, dtype, h, 0); + try expectToken(token, sampled[step + 1], stem); + std.debug.print("PASS {s}: residuals, final row, logits and token {d} equal\n", .{ stem, token }); + } +} + +fn fail(what: []const u8, layer: usize) error{Mismatch} { + std.debug.print("FAIL {s}: first differing layer {d}\n", .{ what, layer }); + return error.Mismatch; +} + +fn compare(g: Gpu, dir: []const u8, stem: []const u8, act: view.Kind, ptr: u64, n: usize) !void { + const want = try read(g, dir, stem, act); + defer g.gpa.free(want.bytes); + const got = try download(g, ptr, n); + defer g.gpa.free(got); + if (firstDiff(got, want.data)) |at| { + std.debug.print("FAIL {s}: differs first at value {d}\n", .{ stem, at }); + return error.Mismatch; + } +} + +/// The row's logits in the activation dtype (one-row projection, as the engine) compared, then its greedy token. +fn logitsToken(g: Gpu, o: hip.ops.Ops, m: *const view.Model, dir: []const u8, stem: []const u8, act: view.Kind, dtype: qwen35.sample.Dtype, hidden: Tensor, row: usize) !u32 { + const s = m.spec; + const x: Tensor = .{ .ptr = hidden.ptr + row * s.hidden * 2, .kind = act }; + var logits = try o.project(x, m.head, 1, false); + if (m.tp) |c| { + // one row: the ranks' slices in rank order are the vocabulary + const parts = try o.arena.take(c.world * m.head.n * 2); + try qwen35.reduce.gather(o, c, logits, parts, m.head.n); + logits.ptr = parts; + } + try hip.runtime.check(g.d.api.hipStreamSynchronize(o.stream)); + try compare(g, dir, stem, act, logits.ptr, s.vocab * 2); + const bytes = try download(g, logits.ptr, s.vocab * 2); + defer g.gpa.free(bytes); + return qwen35.sample.argmax(std.mem.bytesAsSlice(u16, @as([]align(2) u8, @alignCast(bytes))), dtype); +} + +fn expectToken(got: u32, want: i64, what: []const u8) !void { + if (got == want) return; + std.debug.print("FAIL {s}: token {d}, the engine drew {d}\n", .{ what, got, want }); + return error.Mismatch; +} diff --git a/zig/tests/qwen35/logit_kind.zig b/zig/tests/qwen35/logit_kind.zig new file mode 100644 index 00000000000..f0247855cfb --- /dev/null +++ b/zig/tests/qwen35/logit_kind.zig @@ -0,0 +1,36 @@ +//! The element types logits come in: the activation dtype the engine draws from, or fp32. + +const std = @import("std"); + +pub const Kind = enum { + bf16, + f16, + f32, + + pub fn size(k: Kind) usize { + return if (k == .f32) 4 else 2; + } + + pub fn descr(k: Kind) []const u8 { + return switch (k) { + .bf16 => " " " @as(f32, @bitCast(@as(u32, std.mem.readInt(u16, bytes[0..2], .little)) << 16)), + .f16 => @as(f16, @bitCast(std.mem.readInt(u16, bytes[0..2], .little))), + .f32 => @as(f32, @bitCast(std.mem.readInt(u32, bytes[0..4], .little))), + }; + } +}; + +test "elements decode to their values" { + try std.testing.expectEqual(@as(f64, 1.0), Kind.bf16.at(&.{ 0x80, 0x3f })); + try std.testing.expectEqual(@as(f64, 1.0), Kind.f16.at(&.{ 0x00, 0x3c })); + try std.testing.expectEqual(@as(f64, -2.0), Kind.f32.at(&.{ 0x00, 0x00, 0x00, 0xc0 })); +} diff --git a/zig/tests/qwen35/logits_run.zig b/zig/tests/qwen35/logits_run.zig new file mode 100644 index 00000000000..61ac1c10870 --- /dev/null +++ b/zig/tests/qwen35/logits_run.zig @@ -0,0 +1,120 @@ +//! `logits [--f32] [--decode]`: every row's logits for tools/truth/score.py to score. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); +const Kind = @import("logit_kind.zig").Kind; + +const Engine = qwen35.engine.Engine; + +/// Rows a head projection covers at once. +pub const chunk = 32; + +pub const Mode = struct { decode: bool = false, wide: bool = false }; + +/// Takes each block of rows as it is read: rows `first..first + count` of `vocab` logits, `bytes` in the kind's layout. +pub const Sink = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, first: usize, count: usize, bytes: []const u8) anyerror!void, +}; + +/// The head's width in logits (the padded vocabulary). +pub fn vocab(e: *const Engine) usize { + return e.model().spec.vocab; +} + +pub fn kindOf(e: *const Engine, mode: Mode) Kind { + return if (mode.wide) .f32 else if (e.model().act == .f16) .f16 else .bf16; +} + +/// Every row's logits of `ids` into `sink`, in blocks of up to `chunk` rows. +pub fn stream(gpa: std.mem.Allocator, e: *Engine, ids: []const u32, mode: Mode, sink: Sink) !void { + const m = e.model(); + var caches = try e.newCaches(ids.len + 8); + defer { + e.drain(); + caches.deinit(gpa); + } + e.prompts.reset(); + const o: hip.ops.Ops = e.ops(&e.prompts); + var ids_dev = try hip.DeviceBuffer.fromHost(&e.driver, std.mem.sliceAsBytes(ids)); + defer ids_dev.free(); + const hidden = try qwen35.forward.span(o, m, &caches, ids_dev.base(), if (mode.decode) 1 else ids.len, 0, null); + + const width = vocab(e) * kindOf(e, mode).size(); + const block = try gpa.alloc(u8, chunk * width); + defer gpa.free(block); + if (mode.decode) { + // row 0 from its one-row prefill, then each token a one-row round at its slot, kept before the next + const first = try o.project(hidden, m.head, 1, mode.wide); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(block.ptr, @ptrFromInt(first.ptr), width)); + for (1..ids.len) |i| { + const rows = [1]Engine.Rows{.{ .caches = &caches, .pos = i, .tokens = ids[i..][0..1] }}; + const reqs = [1]qwen35.draw.Request{.{ .sampling = null, .position = i + 1 }}; + var drawn: [1]u32 = undefined; + const r = try e.verify(&rows, &reqs, &drawn); + const round: hip.ops.Ops = e.ops(&e.rounds); + const logits = try round.project(r.hidden, m.head, 1, mode.wide); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(block[(i % chunk) * width ..].ptr, @ptrFromInt(logits.ptr), width)); + e.keep(0, 1); + try e.flush(); + if (i % chunk == chunk - 1) try sink.put(sink.ctx, i + 1 - chunk, chunk, block); + } + const tail = ids.len % chunk; + if (tail > 0) try sink.put(sink.ctx, ids.len - tail, tail, block[0 .. tail * width]); + return; + } + var row: usize = 0; + while (row < ids.len) : (row += chunk) { + const rows = @min(chunk, ids.len - row); + const at = e.prompts.mark(); + const logits = try o.project(qwen35.forward.at(hidden, row * m.spec.hidden), m.head, rows, mode.wide); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(block.ptr, @ptrFromInt(logits.ptr), rows * width)); + e.prompts.release(at); + try sink.put(sink.ctx, row, rows, block[0 .. rows * width]); + } +} + +/// The rows of a whole file in memory, written as a .npy at the end. +const File = struct { + body: []u8, + width: usize, + + fn put(ctx: *anyopaque, first: usize, _: usize, bytes: []const u8) anyerror!void { + const f: *File = @ptrCast(@alignCast(ctx)); + @memcpy(f.body[first * f.width ..][0..bytes.len], bytes); + } +}; + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 3) return error.MissingArgument; + var mode: Mode = .{}; + for (args[3..]) |a| { + if (std.mem.eql(u8, a, "--f32")) mode.wide = true else if (std.mem.eql(u8, a, "--decode")) mode.decode = true else return error.UnknownOption; + } + const ids = try ids_file.load(gpa, io, args[1]); + defer gpa.free(ids); + const e = try Engine.open(gpa, io, args[0], .{ .capacity = ids.len + 64, .prompt_rows = ids.len + 64, .streams = 1, .batch_rows = 32, .policy = (try @import("group.zig").resolve("", 0)).policy }); + defer e.deinit(); + const kind = kindOf(e, mode); + var header_buf: [128]u8 = undefined; + const dict = try std.fmt.bufPrint(&header_buf, "{{'descr': '{s}', 'fortran_order': False, 'shape': ({d}, {d}), }}", .{ kind.descr(), ids.len, vocab(e) }); + const pad = 64 - (10 + dict.len + 1) % 64; + const head = 10 + dict.len + pad + 1; + const width = vocab(e) * kind.size(); + const out = try gpa.alloc(u8, head + ids.len * width); + defer gpa.free(out); + @memcpy(out[0..8], "\x93NUMPY\x01\x00"); + std.mem.writeInt(u16, out[8..10], @intCast(dict.len + pad + 1), .little); + @memcpy(out[10..][0..dict.len], dict); + @memset(out[10 + dict.len ..][0..pad], ' '); + out[head - 1] = '\n'; + var file: File = .{ .body = out[head..], .width = width }; + try stream(gpa, e, ids, mode, .{ .ctx = &file, .put = File.put }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[2], .data = out }); + std.debug.print("wrote {d}{s} rows x {d} logits to {s}\n", .{ ids.len, if (mode.decode) " decoded" else "", vocab(e), args[2] }); +} diff --git a/zig/tests/qwen35/main.zig b/zig/tests/qwen35/main.zig new file mode 100644 index 00000000000..bf894c963ce --- /dev/null +++ b/zig/tests/qwen35/main.zig @@ -0,0 +1,195 @@ +//! Qwen3.5 / 3.6 model tests: `tf-qwen35-test ...`, the commands listed in `usage`. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); + +const Buf = qwen35.weights.Buf; +const Tensor = qwen35.table.Tensor; + +/// No per-thread alternate signal stack: its thread-local leaves RCCL's and HIP's threads too little stack to start. +pub const std_options: std.Options = .{ .signal_stack_size = null }; + +const usage = "usage: tf-qwen35-test check [--tp N --rank R --master H --port P] [--prompts FILE] [--truth T --ids IDS] [--speed] [--only invariants|accuracy|speed] | upload [first layers] | digest [--tp N --rank R] | layers [--tp N --rank R [--master HOST] [--port P]] | lanes ... | prefill ... | logits [--f32] [--decode] | rows [n] | draw x\n"; + +/// The subcommands that take their arguments after the name. +const commands = [_]struct { name: []const u8, run: *const fn (std.mem.Allocator, std.Io, []const [:0]const u8) anyerror!void }{ + .{ .name = "rows", .run = @import("rows_run.zig").run }, + .{ .name = "logits", .run = @import("logits_run.zig").run }, + .{ .name = "prefill", .run = @import("prefill_run.zig").run }, + .{ .name = "lanes", .run = @import("lanes_run.zig").run }, +}; + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 3) { + std.debug.print(usage, .{}); + return 2; + } + if (std.mem.eql(u8, args[1], "digest")) { + var rank: ?qwen35.slicing.Rank = null; + if (args.len > 6 and std.mem.eql(u8, args[3], "--tp")) rank = .{ .world = try std.fmt.parseInt(usize, args[4], 10), .rank = try std.fmt.parseInt(usize, args[6], 10) }; + digest(init.gpa, init.io, args[2], rank) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + } + if (std.mem.eql(u8, args[1], "draw")) { + @import("draw_run.zig").run(init.gpa) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + } + for (commands) |c| if (std.mem.eql(u8, args[1], c.name)) { + c.run(init.gpa, init.io, args[2..]) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + }; + if (std.mem.eql(u8, args[1], "layers") and args.len > 3) { + var d = try hip.Runtime.open(); + defer d.close(); + var group: @import("group.zig").Group = .{}; + var i: usize = 4; + while (i < args.len) : (i += 1) if (!try group.option(args, &i)) return 2; + @import("layers.zig").run(.{ .d = &d, .gpa = init.gpa, .io = init.io }, args[2], args[3], group) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; + } + if (std.mem.eql(u8, args[1], "check")) return @import("check.zig").run(init.gpa, init.io, args[2..]) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + if (!std.mem.eql(u8, args[1], "upload")) { + std.debug.print(usage, .{}); + return 2; + } + var driver = try hip.Runtime.open(); + defer driver.close(); + var ctx = try hip.Context.init(&driver, 0); + defer ctx.deinit(); + const limit = if (args.len > 3) try std.fmt.parseInt(usize, args[3], 10) else std.math.maxInt(usize); + run(init.gpa, init.io, &driver, args[2], limit) catch |e| { + std.debug.print("FAIL {t}\n", .{e}); + return 1; + }; + return 0; +} + +/// One line per host tensor: its path, dtype, shape and the SHA-256 of its bytes. +fn line(path: []const u8, t: Tensor) void { + var sum: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(t.bytes, &sum, .{}); + std.debug.print("{s} {t} {any} {s}\n", .{ path, t.dtype, t.shape[0..t.rank], std.fmt.bytesToHex(sum, .lower) }); +} + +fn emit(gpa: std.mem.Allocator, path: []const u8, v: anytype) !void { + const T = @TypeOf(v); + switch (@typeInfo(T)) { + .@"struct" => if (T == Tensor) line(path, v) else inline for (@typeInfo(T).@"struct".field_names) |name| { + if (comptime std.mem.eql(u8, name, "arena") or std.mem.eql(u8, name, "owned") or std.mem.eql(u8, name, "io")) continue; + const sub = try std.fmt.allocPrint(gpa, "{s}.{s}", .{ path, name }); + defer gpa.free(sub); + try emit(gpa, sub, @field(v, name)); + }, + .@"union" => switch (v) { + inline else => |payload, tag| { + const sub = try std.fmt.allocPrint(gpa, "{s}.{s}", .{ path, @tagName(tag) }); + defer gpa.free(sub); + try emit(gpa, sub, payload); + }, + }, + .optional => if (v) |x| try emit(gpa, path, x), + .int, .bool => std.debug.print("{s} {any}\n", .{ path, v }), + else => {}, + } +} + +fn digest(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, rank: ?qwen35.slicing.Rank) !void { + var ck = try qwen35.Checkpoint.open(gpa, io, dir); + defer ck.close(); + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const embed = try ck.embed(scratch.allocator()); + try emit(gpa, "embed", embed); + try emit(gpa, "final_norm", try ck.finalNorm(scratch.allocator())); + const head = try ck.head(scratch.allocator()); + if (rank) |r| { + try emit(gpa, "head", try qwen35.slicing.vocabRows(scratch.allocator(), head orelse embed, ck.spec().vocab, r)); + } else try emit(gpa, "head", head); + for (0..ck.spec().n_layers) |i| { + var layer = try ck.layer(i); + defer layer.deinit(); + if (rank) |r| try qwen35.slicing.layer(&layer, ck.spec(), r); + const path = try std.fmt.allocPrint(gpa, "L{d}", .{i}); + defer gpa.free(path); + try emit(gpa, path, layer.body); + } + var mtp = try ck.mtp(); + defer if (mtp) |*m| m.deinit(); + if (rank) |r| if (mtp) |*m| if (m.head) |p| { + m.head = try qwen35.slicing.vocabRows(m.arena.allocator(), p, ck.spec().vocab, r); + }; + try emit(gpa, "mtp", mtp); +} + +const Check = struct { + gpa: std.mem.Allocator, + driver: *const hip.Runtime, + buffers: usize = 0, + bytes: usize = 0, + + /// Reads `b` back and compares dtype, shape and bytes with the host tensor. + fn buf(c: *Check, b: Buf, t: Tensor) !void { + if (b.dtype != t.dtype or b.rank != t.rank or !std.mem.eql(u8, std.mem.sliceAsBytes(&b.shape), std.mem.sliceAsBytes(&t.shape)) or b.len != t.bytes.len) return error.ShapeMismatch; + const got = try c.gpa.alloc(u8, b.len); + defer c.gpa.free(got); + const device: hip.DeviceBuffer = .{ .r = c.driver, .ptr = @ptrFromInt(b.ptr), .len = b.len }; + try device.download(0, got); + if (!std.mem.eql(u8, got, t.bytes)) return error.BytesDiffer; + c.buffers += 1; + c.bytes += b.len; + } + + /// Walks a device struct and its host twin (same field and tag names) and checks every buffer. + fn walk(c: *Check, dev: anytype, h: anytype) !void { + const T = @TypeOf(dev); + switch (@typeInfo(T)) { + .@"struct" => if (T == Buf) try c.buf(dev, h) else inline for (@typeInfo(T).@"struct".field_names) |name| try c.walk(@field(dev, name), if (@hasField(@TypeOf(h), name)) @field(h, name) else {}), + .@"union" => switch (dev) { + inline else => |payload, tag| try c.walk(payload, @field(h, @tagName(tag))), + }, + .optional => if (dev) |d| try c.walk(d, h.?) else if (h != null) return error.ShapeMismatch, + else => {}, + } + } +}; + +fn run(gpa: std.mem.Allocator, io: std.Io, driver: *const hip.Runtime, dir: []const u8, limit: usize) !void { + var ck = try qwen35.Checkpoint.open(gpa, io, dir); + defer ck.close(); + var model = try qwen35.Model.fromCheckpoint(gpa, driver, &ck, limit); + defer model.deinit(); + var c: Check = .{ .gpa = gpa, .driver = driver }; + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + try c.walk(model.embed, (try ck.embed(scratch.allocator()))); + try c.walk(model.final_norm, try ck.finalNorm(scratch.allocator())); + try c.walk(model.head, try ck.head(scratch.allocator())); + for (model.layers, 0..) |layer, i| { + var host_layer = try ck.layer(i); + defer host_layer.deinit(); + try c.walk(layer, host_layer.body); + } + if (model.layers.len == ck.spec().n_layers) { + var host_mtp = try ck.mtp(); + defer if (host_mtp) |*m| m.deinit(); + try c.walk(model.mtp, host_mtp); + } + std.debug.print("PASS {d} layers, {d} buffers, {d} MiB read back equal to the host index\n", .{ model.layers.len, c.buffers, c.bytes >> 20 }); +} diff --git a/zig/tests/qwen35/matrix.sh b/zig/tests/qwen35/matrix.sh new file mode 100644 index 00000000000..06a4d5b1d0d --- /dev/null +++ b/zig/tests/qwen35/matrix.sh @@ -0,0 +1,125 @@ +#!/bin/sh +# usage: matrix.sh [options] MODELS_DIR DEVICES... [-- CHECK_ARGS]: a markdown table of `check` per model and setting. + +# DEVICES: an argument a group, a comma list of HIP ordinals ("6,7" is tensor parallel over two); exit 1 on any FAIL. + +bin=zig-out/bin/tf-qwen35-test +log= +port=29551 +limit=3000 +speed= +ids= +models= +truths= +envs= +extra= + +die() { echo "matrix.sh: $*" >&2; exit 2; } +value() { [ "$1" -ge 2 ] || die "$2 needs a value"; } + +while [ $# -gt 0 ]; do + case $1 in + --model) value $# "$1"; models="$models $2"; shift 2 ;; # a directory under MODELS_DIR; default: all of them + --env) value $# "$1"; envs="$envs $2"; shift 2 ;; # VAR=V1,V2; every combination is run + --truth) value $# "$1"; truths="$truths $2"; shift 2 ;; # NAME=FILE, the fp64 truth .npy model NAME is scored against + --ids) value $# "$1"; ids=$2; shift 2 ;; # the ids .npy the long prompts and the truth rows are cut from + --speed) speed=--speed; shift ;; + --bin) value $# "$1"; bin=$2; shift 2 ;; + --log) value $# "$1"; log=$2; shift 2 ;; + --port) value $# "$1"; port=$2; shift 2 ;; + --timeout) value $# "$1"; limit=$2; shift 2 ;; + -*) die "unknown option $1" ;; + *) break ;; + esac +done +[ $# -ge 2 ] || die "usage: matrix.sh [options] MODELS_DIR DEVICES... [-- CHECK_ARGS]" +dir=$1 +shift +groups= +while [ $# -gt 0 ] && [ "$1" != -- ]; do groups="$groups $1"; shift; done +[ $# -gt 0 ] && shift && extra="$*" # after `--`, arguments for every `check` as they are +[ -n "$groups" ] || die "no DEVICES" +[ -d "$dir" ] || die "$dir is not a directory" +[ -x "$bin" ] || die "$bin is not built" +if [ -z "$models" ]; then + for d in "$dir"/[!.]*/; do models="$models $(basename "$d")"; done +fi +[ -n "$log" ] || log=$(mktemp -d) +mkdir -p "$log" + +# every combination of the --env settings, a line each ("VAR=a OTHER=x"); one empty line when there are none +combos() ( + prefix=$1 + shift + if [ $# -eq 0 ]; then echo "$prefix"; return; fi + spec=$1 + shift + for v in $(echo "${spec#*=}" | tr ',' ' '); do combos "$prefix ${spec%%=*}=$v" "$@"; done +) + +truth_of() { + for t in $truths; do + [ "${t%%=*}" = "$1" ] && { echo "${t#*=}"; return; } + done +} + +# the numbers of one run's lines, as the cells of its table row +summarize() { + awk ' + function num(re, s) { if (match($0, re)) { s = substr($0, RSTART, RLENGTH); sub(/^[^=:]*[=:] */, "", s); sub(/[% ].*$/, "", s); return s } return "-" } + /^(PASS|FAIL) (rows|lanes) / { total++; if ($1 == "PASS") ok++ } + /^(PASS|FAIL) accuracy prefill/ { klp = num("KL mean=[^ ]+"); top = num("top1=[^ ]+") } + /^(PASS|FAIL) accuracy decode/ { kld = num("KL mean=[^ ]+") } + /^PASS speed prefill 2048 / { pf2 = num("[0-9]+ tok/s") } + /^PASS speed prefill 8192 / { pf8 = num("[0-9]+ tok/s") } + /^PASS speed decode 1 stream, drafts off/ { d1 = num(": [0-9.]+ tok/s") } + /^PASS speed decode 1 stream, drafts on/ { d1m = num(": [0-9.]+ tok/s") } + /^PASS speed decode 4 streams, drafts off/ { d4 = num(": [0-9.]+ tok/s") } + /^PASS speed decode 4 streams, drafts on/ { d4m = num(": [0-9.]+ tok/s") } + END { + if (!klp) klp = "-"; if (!kld) kld = "-"; if (!top) top = "-" + if (!pf2) pf2 = "-"; if (!pf8) pf8 = "-"; if (!d1) d1 = "-"; if (!d1m) d1m = "-"; if (!d4) d4 = "-"; if (!d4m) d4m = "-" + printf "%d/%d|%s|%s|%s|%s|%s|%s|%s|%s|%s", ok, total, klp, kld, top, pf2, pf8, d1, d1m, d4, d4m + }' "$1" +} + +rows=$log/rows.txt +: > "$rows" +bad=0 +n=0 +for model in $models; do + [ -d "$dir/$model" ] || die "$dir/$model is not a model directory" + truth=$(truth_of "$model") + for devs in $groups; do + tp=$(echo "$devs" | awk -F, '{print NF}') + combos "" $envs > "$log/settings.txt" + while IFS= read -r setting; do + setting=$(echo $setting) + n=$((n + 1)) + out=$log/run$n.log + args="$dir/$model --tp $tp --port $((port + n - 1))" + [ -n "$ids" ] && args="$args --ids $ids" + [ -n "$truth" ] && args="$args --truth $truth" + args="$args $speed $extra" + r=1 + while [ "$r" -lt "$tp" ]; do + # shellcheck disable=SC2086 + env -u ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES=$devs $setting timeout -s KILL "$limit" "$bin" check $args --rank $r > "$log/run$n.rank$r.log" 2>&1 & + r=$((r + 1)) + done + # shellcheck disable=SC2086 + env -u ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES=$devs $setting timeout -s KILL "$limit" "$bin" check $args --rank 0 > "$out" 2>&1 + code=$? + wait + status=PASS + if [ "$code" -ne 0 ] || [ "$(grep -c '^FAIL ' "$out")" -ne 0 ] || ! grep -q '^check PASS' "$out"; then status=FAIL; bad=1; fi + echo "$model|$devs|$tp|${setting:--}|$status|$(summarize "$out")" >> "$rows" + echo "run $n: $model on $devs ${setting:+($setting) }$status, $out" >&2 + done < "$log/settings.txt" + done +done + +echo "| model | devices | tp | env | status | invariants | KL prefill | KL decode | top-1 % | prefill 2048 tok/s | prefill 8192 tok/s | decode 1 | decode 1 + drafts | decode 4 | decode 4 + drafts |" +echo "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|" +sed 's/|/ | /g; s/^/| /; s/$/ |/' "$rows" +exit $bad diff --git a/zig/tests/qwen35/prefill_run.zig b/zig/tests/qwen35/prefill_run.zig new file mode 100644 index 00000000000..447cfdac776 --- /dev/null +++ b/zig/tests/qwen35/prefill_run.zig @@ -0,0 +1,38 @@ +//! `prefill ...`: cold synthetic prompts of each length through prefill, as prompt tokens a second. + +const std = @import("std"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); + +/// The median seconds of three cold prefills of `prompt` after one warm-up. +pub fn seconds(gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, prompt: []const u32) !f64 { + var times: [3]f64 = undefined; + for (0..4) |rep| { + var caches = try e.newCaches(prompt.len + 8); + defer { + e.drain(); + caches.deinit(gpa); + } + const t0 = std.Io.Clock.awake.now(io); + _ = try e.prefill(&caches, prompt, 0, null, .{ .sampling = null, .position = prompt.len }, null); + const dt = @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds() - t0.toNanoseconds())) / 1e9; + if (rep > 0) times[rep - 1] = dt; + } + std.mem.sort(f64, ×, {}, std.sort.asc(f64)); + return times[1]; +} + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 2) return error.MissingArgument; + var longest: usize = 0; + for (args[1..]) |a| longest = @max(longest, try std.fmt.parseInt(usize, a, 10)); + const e = try qwen35.engine.Engine.open(gpa, io, args[0], .{ .capacity = longest + 64, .prompt_rows = longest + 64, .streams = 1, .batch_rows = 32, .policy = (try @import("group.zig").resolve("", 0)).policy }); + defer e.deinit(); + const prompt = try ids_file.synthetic(gpa, longest); + defer gpa.free(prompt); + for (args[1..]) |a| { + const len = try std.fmt.parseInt(usize, a, 10); + const t = try seconds(gpa, io, e, prompt[0..len]); + std.debug.print("RESULT prefill {d} tokens: {d:.3} s, {d:.0} tok/s\n", .{ len, t, @as(f64, @floatFromInt(len)) / t }); + } +} diff --git a/zig/tests/qwen35/prompts.json b/zig/tests/qwen35/prompts.json new file mode 100644 index 00000000000..34e48d1a549 --- /dev/null +++ b/zig/tests/qwen35/prompts.json @@ -0,0 +1 @@ +{"a": [9707, 11, 1879, 0, 358, 1079, 264, 1273, 2814, 311, 1490, 1045, 1128, 13, 3555, 498, 3170, 1431, 30, 576, 6722, 315, 9625, 374], "b": [785, 6722, 315, 9625, 374, 12095, 13, 576, 3974, 15217, 21893, 39380, 916], "c": [151644, 872, 198, 5501, 3270, 264, 2805, 32794, 911, 279, 17951, 13, 151645, 198, 151644, 77091, 198], "d": [16, 11, 220, 17, 11, 220, 18, 11, 220, 19, 11, 220, 20]} \ No newline at end of file diff --git a/zig/tests/qwen35/rows_run.zig b/zig/tests/qwen35/rows_run.zig new file mode 100644 index 00000000000..ea60d0ac67d --- /dev/null +++ b/zig/tests/qwen35/rows_run.zig @@ -0,0 +1,153 @@ +//! `rows [n] [streams] [keep]`: the window invariant layer by layer, naming the first difference. + +const std = @import("std"); +const hip = @import("hip"); +const qwen35 = @import("qwen3_5"); +const ids_file = @import("ids_file.zig"); + +const Engine = qwen35.engine.Engine; + +/// Every layer's residual rows of one run: (layers + 1, n, hidden) bytes, the last slot the final rows. +const Sink = struct { + e: *Engine, + bytes: []u8, + n: usize, + /// The row the next capture lands at, and the real rows of the round (the forward may run padding rows past them). + row: usize = 0, + take: usize = 0, + + fn width(s: *const Sink) usize { + return s.e.model().spec.hidden * s.e.model().act.size(); + } + + fn put(s: *Sink, slot: usize, x: hip.ops.Tensor, rows: usize) !void { + try s.e.stream.synchronize(); + const w = s.width(); + const at = (slot * s.n + s.row) * w; + try hip.runtime.check(s.e.driver.api.hipMemcpyDtoH(s.bytes[at..].ptr, @ptrFromInt(x.ptr), rows * w)); + } + + fn layer(ctx: *anyopaque, index: usize, x: hip.ops.Tensor, rows: usize) anyerror!void { + const s: *Sink = @ptrCast(@alignCast(ctx)); + _ = rows; + try s.put(index, x, s.take); + } +}; + +/// One round of every stream's `tokens` from `pos[j]` of `caches[j]`, in at least `pad` rows, captured into `sink`. +fn round(e: *Engine, caches: []const *qwen35.state.Caches, pos: []const usize, tokens: []const []const u32, keep: usize, sink: *Sink, pad: usize) !void { + var rows: [8]Engine.Rows = undefined; + var reqs: [128]qwen35.draw.Request = undefined; + var out: [128]u32 = undefined; + var total: usize = 0; + for (caches, pos, tokens, 0..) |c, p, t, j| { + rows[j] = .{ .caches = c, .pos = p, .tokens = t }; + for (0..t.len) |i| reqs[total + i] = .{ .sampling = null, .position = p + i + 1 }; + total += t.len; + } + sink.take = total; + e.round.trace = .{ .ctx = sink, .layer = Sink.layer }; + e.round.pad_to = pad; + defer { + e.round.trace = null; + e.round.pad_to = 0; + } + const done = try e.verify(rows[0..caches.len], reqs[0..total], out[0..total]); + try sink.put(e.model().spec.n_layers, done.hidden, total); + for (tokens, 0..) |t, j| e.keep(j, @min(keep, t.len)); + try e.flush(); + try e.stream.synchronize(); +} + +/// Streams of `n` rows each, the first `keep` of each kept. +pub const Case = struct { streams: usize, n: usize, keep: usize, pad: usize = 0 }; + +/// Where a case's two runs first differ. +pub const Diff = struct { layer: usize, kind: []const u8, stream: usize, row: usize, column: usize }; + +/// Runs one case over prompts cut from `ids`; null when every layer's rows and the final rows are equal. +pub fn runCase(gpa: std.mem.Allocator, e: *Engine, ids: []const u32, c: Case) !?Diff { + const n = c.n; + const streams = c.streams; + // the trace waits on the stream layer by layer, which a capture cannot + const was = e.o.graphs; + e.o.graphs = false; + defer e.o.graphs = was; + if (n < 1 or n > 16) return error.BadWindow; + if (c.keep < 1 or c.keep > n) return error.BadKeep; + if (streams < 1 or streams > 8 or ids.len <= n + streams or streams * n > 64) return error.PromptTooShort; + const layers = e.model().spec.n_layers; + const rows = streams * n; + var serial: Sink = .{ .e = e, .bytes = undefined, .n = rows }; + var shared: Sink = .{ .e = e, .bytes = undefined, .n = rows }; + serial.bytes = try gpa.alloc(u8, (layers + 1) * rows * serial.width()); + defer gpa.free(serial.bytes); + shared.bytes = try gpa.alloc(u8, (layers + 1) * rows * shared.width()); + defer gpa.free(shared.bytes); + + // stream j: the ids short by j, its prompt all but its last n tokens + var alone: [8]qwen35.state.Caches = undefined; + var together: [8]qwen35.state.Caches = undefined; + var caches: [8]*qwen35.state.Caches = undefined; + var pos: [8]usize = undefined; + var tails: [8][]const u32 = undefined; + var made: usize = 0; + defer for (alone[0..made], together[0..made]) |*a1, *t1| { + a1.deinit(gpa); + t1.deinit(gpa); + }; + for (0..streams) |j| { + const end = ids.len - j; + const prompt = ids[0 .. end - n]; + tails[j] = ids[end - n .. end]; + pos[j] = prompt.len; + const req: qwen35.draw.Request = .{ .sampling = null, .position = prompt.len }; + alone[j] = try e.newCaches(ids.len + 8); + together[j] = e.newCaches(ids.len + 8) catch |err| { + alone[j].deinit(gpa); + return err; + }; + made += 1; + _ = try e.prefill(&alone[j], prompt, 0, null, req, null); + _ = try e.prefill(&together[j], prompt, 0, null, req, null); + caches[j] = &together[j]; + } + for (0..streams) |j| for (0..n) |i| { + serial.row = j * n + i; + const one = [1]*qwen35.state.Caches{&alone[j]}; + try round(e, &one, &.{pos[j] + i}, &.{tails[j][i..][0..1]}, 1, &serial, 0); + }; + try round(e, caches[0..streams], pos[0..streams], tails[0..streams], c.keep, &shared, c.pad); + // the rows past `keep` again, one at a time from the kept state, over the shared round's captures + for (c.keep..n) |i| for (0..streams) |j| { + shared.row = j * n + i; + const one = [1]*qwen35.state.Caches{&together[j]}; + try round(e, &one, &.{pos[j] + i}, &.{tails[j][i..][0..1]}, 1, &shared, 0); + }; + + const w = serial.width(); + for (0..layers + 1) |slot| for (0..rows) |r| { + const at = (slot * rows + r) * w; + if (std.mem.indexOfDiff(u8, serial.bytes[at..][0..w], shared.bytes[at..][0..w])) |col| { + const kind = if (slot == layers) "final" else if (e.model().spec.full(slot)) "full attention" else "linear attention"; + return .{ .layer = slot, .kind = kind, .stream = r / n, .row = r % n, .column = col / e.model().act.size() }; + } + }; + return null; +} + +pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { + if (args.len < 2) return error.MissingArgument; + const n = if (args.len > 2) try std.fmt.parseInt(usize, args[2], 10) else 3; + const streams = if (args.len > 3) try std.fmt.parseInt(usize, args[3], 10) else 1; + const keep = if (args.len > 4) try std.fmt.parseInt(usize, args[4], 10) else n; + const ids = try ids_file.load(gpa, io, args[1]); + defer gpa.free(ids); + const e = try Engine.open(gpa, io, args[0], .{ .capacity = ids.len + 64, .prompt_rows = ids.len + 64, .streams = streams, .batch_rows = 128, .graphs = false, .policy = (try @import("group.zig").resolve("", 0)).policy }); + defer e.deinit(); + if (try runCase(gpa, e, ids, .{ .streams = streams, .n = n, .keep = keep })) |d| { + std.debug.print("FAIL layer {d} ({s}), stream {d} row {d} of {d}: first difference at column {d}\n", .{ d.layer, d.kind, d.stream, d.row, n, d.column }); + return error.Mismatch; + } + std.debug.print("PASS {d} streams of {d} rows, {d} kept: every layer's residuals and the final rows equal each stream one row at a time\n", .{ streams, n, keep }); +} diff --git a/zig/tests/qwen35/serve_cancel.py b/zig/tests/qwen35/serve_cancel.py new file mode 100644 index 00000000000..6669c824d30 --- /dev/null +++ b/zig/tests/qwen35/serve_cancel.py @@ -0,0 +1,50 @@ +"""A request cancelled in its prompt pass frees the server at once; usage: serve_cancel.py URL MODEL [PROMPT_WORDS].""" + +import http.client +import json +import socket +import sys +import time +import urllib.parse + +URL, MODEL = sys.argv[1], sys.argv[2] +WORDS = int(sys.argv[3]) if len(sys.argv) > 3 else 3000 +HOST = urllib.parse.urlparse(URL) + + +def body(text, max_tokens): + return json.dumps({"model": MODEL, "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "temperature": 0.0, "stream": False, "chat_template_kwargs": {"enable_thinking": False}}) + + +def short(): + conn = http.client.HTTPConnection(HOST.hostname, HOST.port, timeout=600) + began = time.perf_counter() + conn.request("POST", "/v1/chat/completions", body("Count from one to ten in words.", 32), {"Content-Type": "application/json"}) + text = json.load(conn.getresponse())["choices"][0]["message"]["content"] + conn.close() + return text, time.perf_counter() - began + + +def long_then_drop(nonce): + text = f"{nonce} " + " ".join(f"item{i % 97}x{(i * 7919) % 1013}" for i in range(WORDS)) + sock = socket.create_connection((HOST.hostname, HOST.port)) + payload = body(text, 8).encode() + sock.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: " + + str(len(payload)).encode() + b"\r\n\r\n" + payload) + time.sleep(0.4) + sock.close() + + +before, _ = short() +alone = min(short()[1] for _ in range(2)) +failed = 0 +for i in range(3): + long_then_drop(f"cancel{i}-{time.time_ns()}") + time.sleep(0.05) + after, waited = short() + ok = after == before and waited < alone + 3.0 + failed += not ok + print(("ok " if ok else "FAIL ") + f"cancel {i}: the next short request took {waited:.2f} s (alone {alone:.2f} s)", flush=True) +print("failed", failed) +sys.exit(1 if failed else 0) diff --git a/zig/tests/qwen35/serve_check.py b/zig/tests/qwen35/serve_check.py new file mode 100644 index 00000000000..081e0023a1e --- /dev/null +++ b/zig/tests/qwen35/serve_check.py @@ -0,0 +1,95 @@ +"""Exactness of a running native server over HTTP; usage: serve_check.py URL MODEL [TOKENS].""" + +import json +import sys +import threading +import time +import urllib.request + +URL, MODEL = sys.argv[1], sys.argv[2] +TOKENS = int(sys.argv[3]) if len(sys.argv) > 3 else 64 +PROMPTS = [ + "Write a short poem about the sea.", + "List the first twelve prime numbers, separated by commas.", + "Explain in two sentences why the sky is blue.", + "Count from one to thirty in words.", +] + + +def ask(messages, draft=True, temperature=0.0, seed=7): + body = {"model": MODEL, "messages": messages, "max_tokens": TOKENS, "temperature": temperature, "seed": seed, + "draft": draft, "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(URL + "/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=900) as reply: + doc = json.load(reply) + return doc["choices"][0]["message"]["content"], doc.get("usage", {}).get("prompt_tokens_details", {}) + + +def user(text): + return [{"role": "user", "content": text}] + + +def together(draft, temperature): + out = [None] * len(PROMPTS) + + def run(i): + out[i] = ask(user(PROMPTS[i]), draft, temperature)[0] + + threads = [threading.Thread(target=run, args=(i,)) for i in range(len(PROMPTS))] + for t in threads: + t.start() + for t in threads: + t.join() + return out + + +LONG = "Summarise this list in one sentence: " + " ".join(f"item{i % 97}x{(i * 7919) % 1013}" for i in range(500)) + + +def among_decoders(draft, temperature): + """A long prompt (a few thousand tokens, so several prompt chunks) sent while three streams decode.""" + out = [None] * 4 + + def run(i, text, delay): + time.sleep(delay) + out[i] = ask(user(text), draft, temperature)[0] + + threads = [threading.Thread(target=run, args=(i, PROMPTS[i], 0)) for i in range(3)] + threads.append(threading.Thread(target=run, args=(3, LONG, 0.5))) + for t in threads: + t.start() + for t in threads: + t.join() + return out + + +failed = 0 + + +def check(name, same): + global failed + failed += not same + print(("ok " if same else "FAIL ") + name, flush=True) + + +for label, temperature in (("greedy", 0.0), ("t0.8", 0.8)): + serial = [ask(user(p), False, temperature)[0] for p in PROMPTS] + drafted = [ask(user(p), True, temperature)[0] for p in PROMPTS] + check(f"{label}: drafted == serial", drafted == serial) + check(f"{label}: solo == together", together(True, temperature) == drafted) + check(f"{label}: serial together == serial solo", together(False, temperature) == serial) + again = [ask(user(p), True, temperature)[0] for p in PROMPTS] + check(f"{label}: the same twice", again == drafted) + # the long prompt first among the decoders (its prompt goes in a chunk a round), then alone (resumed from its cuts) + mixed = among_decoders(True, temperature) + check(f"{label}: decoders unchanged by a long prompt", mixed[:3] == drafted[:3]) + check(f"{label}: long prompt among decoders == alone", mixed[3] == ask(user(LONG), True, temperature)[0]) + check(f"{label}: serial long prompt among decoders == alone", among_decoders(False, temperature)[3] == mixed[3]) +first, _ = ask(user(PROMPTS[0]), True) +turn = user(PROMPTS[0]) + [{"role": "assistant", "content": first}, {"role": "user", "content": "Now say it shorter."}] +fresh, _ = ask(turn, False) +resumed, details = ask(turn, True) +check(f"resumed == fresh (cached {details})", resumed == fresh) +print("failed", failed) +sys.exit(1 if failed else 0) diff --git a/zig/tests/qwen35/serve_conc.py b/zig/tests/qwen35/serve_conc.py new file mode 100644 index 00000000000..2e1fe4de460 --- /dev/null +++ b/zig/tests/qwen35/serve_conc.py @@ -0,0 +1,76 @@ +"""A long prompt arriving while streams decode; usage: serve_conc.py URL MODEL [DECODERS] [PROMPT_WORDS] [TOKENS].""" + +import http.client +import json +import sys +import threading +import time +import urllib.parse + +URL, MODEL = sys.argv[1], sys.argv[2] +DECODERS = int(sys.argv[3]) if len(sys.argv) > 3 else 3 +WORDS = int(sys.argv[4]) if len(sys.argv) > 4 else 2400 +TOKENS = int(sys.argv[5]) if len(sys.argv) > 5 else 400 +HOST = urllib.parse.urlparse(URL) +SHORT = ["Write a long story about a lighthouse keeper.", "Explain how a transformer works, in detail.", + "List one hundred animals, one per line.", "Describe the history of Rome at length."] + + +def stream(text, max_tokens, stamps, temperature=0.0): + """One streamed chat request: the time of every content chunk goes to `stamps`; returns the text.""" + body = {"model": MODEL, "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "temperature": temperature, "stream": True, "chat_template_kwargs": {"enable_thinking": False}} + conn = http.client.HTTPConnection(HOST.hostname, HOST.port, timeout=900) + conn.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"}) + reply = conn.getresponse() + out = [] + for raw in reply: + line = raw.decode().strip() + if not line.startswith("data:") or line.endswith("[DONE]"): + continue + delta = json.loads(line[5:])["choices"][0].get("delta", {}) + if delta.get("content"): + stamps.append(time.perf_counter()) + out.append(delta["content"]) + conn.close() + return "".join(out) + + +def long_prompt(nonce): + words = [f"{nonce}"] + [f"item{i % 97}x{(i * 7919) % 1013}" for i in range(WORDS)] + return "Summarise the following list in one short sentence.\n" + " ".join(words) + + +def run(label): + stamps = [[] for _ in range(DECODERS)] + threads = [threading.Thread(target=stream, args=(SHORT[i % len(SHORT)], TOKENS, stamps[i])) for i in range(DECODERS)] + for t in threads: + t.start() + while min(len(s) for s in stamps) < 16: + time.sleep(0.05) + sent = time.perf_counter() + first = [] + text = long_prompt(f"{label}-{time.time_ns()}") + t = threading.Thread(target=stream, args=(text, 16, first)) + t.start() + t.join() + done = time.perf_counter() + for th in threads: + th.join() + ttft = first[0] - sent + gaps = [] + tokens = 0 + for s in stamps: + for a, b in zip(s, s[1:]): + if b > sent and a < first[0]: + gaps.append(b - a) + tokens += sum(1 for x in s if sent <= x <= first[0]) + gaps.sort() + window = first[0] - sent + print(f"{label}: long prompt first token {ttft:.2f} s, decoding streams: longest gap {gaps[-1]:.2f} s, " + f"median gap {gaps[len(gaps) // 2] * 1000:.0f} ms, {tokens / window:.1f} tok/s over the prompt's window " + f"(the prompt ended at {done - sent:.2f} s)", flush=True) + + +for i in range(2): + run(f"run{i}") diff --git a/zig/tests/qwen35/serve_prefill.py b/zig/tests/qwen35/serve_prefill.py new file mode 100644 index 00000000000..54863a3bfc8 --- /dev/null +++ b/zig/tests/qwen35/serve_prefill.py @@ -0,0 +1,71 @@ +"""Cold prefill of a running server; usage: serve_prefill.py URL MODEL IDS.npy OUT_DIR [LENGTHS] [REPS].""" + +import json +import struct +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + + +def read_ids(path: Path) -> list[int]: + """The token ids of a 1-D little-endian int32 or int64 .npy file.""" + raw = path.read_bytes() + header_len = struct.unpack(" tuple[float, dict]: + """Seconds to the first streamed token and the final usage block; a refusal or a short prompt raises.""" + req = urllib.request.Request(url + "/v1/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + began, first, usage = time.perf_counter(), None, {} + try: + with urllib.request.urlopen(req, timeout=3600) as r: + for line in r: + if not line.startswith(b"data: ") or line.strip() == b"data: [DONE]": + continue + event = json.loads(line[6:]) + if "error" in event: + raise SystemExit(f"refused: {event['error']}") + if first is None and event.get("choices") and event["choices"][0].get("text") is not None: + first = time.perf_counter() - began + usage = event.get("usage") or usage + except urllib.error.HTTPError as e: + raise SystemExit(f"refused: HTTP {e.code} {e.read().decode(errors='replace')[:300]}") + if first is None or usage.get("prompt_tokens") != len(body["prompt"]): + raise SystemExit(f"no prefill of {len(body['prompt'])} tokens: first token {first}, usage {usage}") + return first, usage + + +def main() -> int: + url, model, ids_path, out = sys.argv[1].rstrip("/"), sys.argv[2], Path(sys.argv[3]), Path(sys.argv[4]) + lengths = [int(n) for n in (sys.argv[5] if len(sys.argv) > 5 else "2048,8192,32768,65536").split(",")] + reps = int(sys.argv[6]) if len(sys.argv) > 6 else 3 + ids, rows = read_ids(ids_path), [] + out.mkdir(parents=True, exist_ok=True) + for n in lengths: + if n > len(ids): + print(f"skip {n}: the ids hold {len(ids)} tokens") + continue + body = {"model": model, "prompt": ids[:n], "max_tokens": 1, "temperature": 0, "stream": True, + "stream_options": {"include_usage": True}} + (out / f"request_{n}.json").write_text(json.dumps(body)) + times, cached = [], [] + for _ in range(reps): + seconds, usage = stream(url, body) + times.append(seconds) + cached.append((usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)) + best = sorted(times)[len(times) // 2] + rows.append({"tokens": n, "seconds": times, "median_tok_s": n / best, "cached_tokens": cached}) + print(f"prefill {n}: median {best:.3f} s, {n / best:.0f} tok/s, cached {cached}") + (out / "prefill.json").write_text(json.dumps(rows, indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/tests/qwen35/serve_prefix.py b/zig/tests/qwen35/serve_prefix.py new file mode 100644 index 00000000000..073db8486ba --- /dev/null +++ b/zig/tests/qwen35/serve_prefix.py @@ -0,0 +1,61 @@ +"""Prompt reuse of a running native server over HTTP; usage: serve_prefix.py URL MODEL [SYSTEM_WORDS].""" + +import json +import sys +import time +import urllib.request + +URL, MODEL = sys.argv[1], sys.argv[2] +WORDS = int(sys.argv[3]) if len(sys.argv) > 3 else 1500 +SYSTEM = "You are a careful assistant. Reference notes: " + " ".join(f"note{i % 89}x{(i * 7919) % 1013}" for i in range(WORDS)) +QUESTIONS = ["What is the first note?", "How many notes are there, roughly?", "Name the last note.", "Is note5x5 listed?"] + + +def ask(question, draft=True, system=SYSTEM): + """The reply's text, its time to the first token in milliseconds and the usage the server reports.""" + body = {"model": MODEL, "messages": [{"role": "system", "content": system}, {"role": "user", "content": question}], + "max_tokens": 16, "temperature": 0.0, "draft": draft, "stream": True, + "stream_options": {"include_usage": True}, "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(URL + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + began = time.perf_counter() + first = None + text = "" + usage = {} + with urllib.request.urlopen(request, timeout=900) as reply: + for raw in reply: + line = raw.decode().strip() + if not line.startswith("data:") or line.endswith("[DONE]"): + continue + doc = json.loads(line[5:]) + if doc.get("usage"): + usage = doc["usage"] + for choice in doc.get("choices", []): + piece = choice.get("delta", {}).get("content") or "" + if piece and first is None: + first = (time.perf_counter() - began) * 1000 + text += piece + return text, first, usage + + +def cached(usage): + return (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0) + + +ask(QUESTIONS[0], True, "warm up the kernels: " + SYSTEM[:200]) +rows = [] +for label, question, draft in ( + ("first request (nothing kept)", QUESTIONS[0], True), + ("second request, same system prompt", QUESTIONS[1], True), + ("third request, same system prompt", QUESTIONS[2], True), + ("same system prompt, draft false (no cache)", QUESTIONS[3], False), + ("different system prompt of the same length", QUESTIONS[1], True), +): + system = SYSTEM if "different" not in label else SYSTEM.replace("note", "memo") + text, ttft, usage = ask(question, draft, system) + rows.append((label, usage.get("prompt_tokens", 0), cached(usage), ttft, text)) + print(f"{label}: prompt {rows[-1][1]} tokens, cached_tokens {rows[-1][2]}, time to first token {ttft:.0f} ms", flush=True) +# the same question with and without the cache: the replies must be equal +hit_text = ask(QUESTIONS[1], True)[0] +miss_text = ask(QUESTIONS[1], False)[0] +print("hit == miss:", hit_text == miss_text, flush=True) +sys.exit(0 if hit_text == miss_text else 1) diff --git a/zig/tests/qwen35/serve_tp.sh b/zig/tests/qwen35/serve_tp.sh new file mode 100644 index 00000000000..fe495e03bd4 --- /dev/null +++ b/zig/tests/qwen35/serve_tp.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# usage: serve_tp.sh DEVS WORLD MODEL_DIR PORT [serve flags]: serve_check.py on a tp server, from the build directory. +set -u +devs=$1; world=$2; model=$3; port=$4; shift 4 +bin=./zig-out/native-hip/bin/tensorfold-native +here=$(dirname "$0") +log=${TMPDIR:-/tmp}/serve_tp_$port +mkdir -p "$log" +pids="" +trap 'for p in $pids; do kill $p 2>/dev/null; done' EXIT +run() { exec env -u ROCR_VISIBLE_DEVICES HIP_VISIBLE_DEVICES=$devs "$bin" serve "$model" --tp "$world" --master 127.0.0.1 --master-port $((port + 1000)) --parallel 4 "$@"; } +r=1 +while [ "$r" -lt "$world" ]; do + run --rank $r "$@" > "$log/rank$r.log" 2>&1 & + pids="$pids $!" + r=$((r + 1)) +done +run --rank 0 --port "$port" --name m "$@" > "$log/rank0.log" 2>&1 & +head=$! +pids="$pids $head" +tries=0 +until curl -s "http://127.0.0.1:$port/health" > /dev/null; do + tries=$((tries + 1)) + if [ "$tries" -gt 600 ] || ! kill -0 "$head" 2>/dev/null; then echo "server did not start"; tail -n 5 "$log"/rank*.log; exit 1; fi + sleep 2 +done +python3 "$here/serve_check.py" "http://127.0.0.1:$port" m 64 +status=$? +kill "$head" +wait "$head" 2>/dev/null +for p in $pids; do wait "$p" 2>/dev/null; done +grep -hE "error|panic|FAIL" "$log"/rank*.log | head -5 +exit $status diff --git a/zig/tests/qwen35/truth_score.zig b/zig/tests/qwen35/truth_score.zig new file mode 100644 index 00000000000..9be0e2fc965 --- /dev/null +++ b/zig/tests/qwen35/truth_score.zig @@ -0,0 +1,211 @@ +//! Candidate logits scored against a high-precision truth .npy as tools/truth/score.py scores them, a block at a time. + +const std = @import("std"); +const npy = @import("npy"); +const Kind = @import("logit_kind.zig").Kind; + +/// One row's numbers. +const Row = struct { kl: f64, agree: bool, max_abs: f64, nll_truth: f64, nll_cand: f64 }; + +fn elem(wide: bool, bytes: []const u8, i: usize) f64 { + return if (wide) @bitCast(std.mem.readInt(u64, bytes[i * 8 ..][0..8], .little)) else @as(f32, @bitCast(std.mem.readInt(u32, bytes[i * 4 ..][0..4], .little))); +} + +/// `truth` and `cand` rows (the candidate's first `cols` logits), `target` the token the row predicts, if any. +fn scoreRow(wide: bool, truth: []const u8, kind: Kind, cand: []const u8, cols: usize, target: ?u32) Row { + var mt: f64 = -std.math.inf(f64); + var mc: f64 = -std.math.inf(f64); + var at: usize = 0; + var ac: usize = 0; + var max_abs: f64 = 0; + for (0..cols) |i| { + const t = elem(wide, truth, i); + const c = kind.at(cand[i * kind.size() ..]); + if (t > mt) { + mt = t; + at = i; + } + if (c > mc) { + mc = c; + ac = i; + } + max_abs = @max(max_abs, @abs(t - c)); + } + // KL = sum p (t - c) - (lse_t - lse_c), with p the truth's softmax + var zt: f64 = 0; + var zc: f64 = 0; + var a: f64 = 0; + for (0..cols) |i| { + const t = elem(wide, truth, i); + const c = kind.at(cand[i * kind.size() ..]); + const et = @exp(t - mt); + zt += et; + zc += @exp(c - mc); + a += et * (t - c); + } + const lse_t = mt + @log(zt); + const lse_c = mc + @log(zc); + var r: Row = .{ .kl = a / zt - (lse_t - lse_c), .agree = at == ac, .max_abs = max_abs, .nll_truth = 0, .nll_cand = 0 }; + if (target) |g| { + r.nll_truth = lse_t - elem(wide, truth, g); + r.nll_cand = lse_c - kind.at(cand[g * kind.size() ..]); + } + return r; +} + +pub const Score = struct { + rows: usize, + kl_mean: f64, + kl_max: f64, + /// Percent of rows whose top logit is the truth's. + top1: f64, + max_abs: f64, + ppl: f64, + ppl_truth: f64, +}; + +pub const Scorer = struct { + gpa: std.mem.Allocator, + io: std.Io, + file: std.Io.File, + wide: bool, + /// Where the data starts in the file, the rows, and the logits a row. + offset: u64, + rows: usize, + cols: usize, + kind: Kind, + /// The width of a candidate row (at least `cols`: the padded vocabulary). + width: usize, + /// The token each row predicts (the ids shifted by one; the last row has none). + ids: []const u32, + raw: []u8, + scored: []Row, + seen: usize = 0, + threads: usize, + + pub const block = 32; + + pub fn init(gpa: std.mem.Allocator, io: std.Io, path: []const u8, ids: []const u32, kind: Kind, width: usize) !Scorer { + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + errdefer file.close(io); + var head: [1024]u8 = undefined; + const n = try file.readPositionalAll(io, &head, 0); + const a = try npy.parse(head[0..n]); + if (a.rank != 2) return error.BadTruth; + const wide = std.mem.eql(u8, a.descr, " width) return error.TruthShape; + const raw = try gpa.alloc(u8, block * a.shape[1] * @as(usize, if (wide) 8 else 4)); + errdefer gpa.free(raw); + const scored = try gpa.alloc(Row, ids.len); + return .{ .gpa = gpa, .io = io, .file = file, .wide = wide, .offset = n - a.data.len, .rows = a.shape[0], .cols = a.shape[1], .kind = kind, .width = width, .ids = ids, .raw = raw, .scored = scored, .threads = @min(16, std.Thread.getCpuCount() catch 1) }; + } + + pub fn deinit(s: *Scorer) void { + s.gpa.free(s.scored); + s.gpa.free(s.raw); + s.file.close(s.io); + } + + /// Starts a new pass over the rows. + pub fn reset(s: *Scorer) void { + s.seen = 0; + } + + const Work = struct { + s: *const Scorer, + first: usize, + bytes: []const u8, + count: usize, + from: usize, + step: usize, + + fn go(w: Work) void { + const s = w.s; + const elem_size: usize = if (s.wide) 8 else 4; + var i = w.from; + while (i < w.count) : (i += w.step) { + const row = w.first + i; + const target: ?u32 = if (row + 1 < s.ids.len) s.ids[row + 1] else null; + s.scored[row] = scoreRow(s.wide, s.raw[i * s.cols * elem_size ..][0 .. s.cols * elem_size], s.kind, w.bytes[i * s.width * s.kind.size() ..][0 .. s.width * s.kind.size()], s.cols, target); + } + } + }; + + /// Scores rows `first..first + count` (candidate `bytes`, `width` logits a row) against the truth's. + pub fn put(ctx: *anyopaque, first: usize, count: usize, bytes: []const u8) anyerror!void { + const s: *Scorer = @ptrCast(@alignCast(ctx)); + if (first + count > s.rows) return error.TruthShape; + const elem_size: usize = if (s.wide) 8 else 4; + const n = count * s.cols * elem_size; + if (try s.file.readPositionalAll(s.io, s.raw[0..n], s.offset + first * s.cols * elem_size) != n) return error.TruthShort; + var spawned: [16]?std.Thread = @splat(null); + const t = @min(s.threads, count); + const base: Work = .{ .s = s, .first = first, .bytes = bytes, .count = count, .from = 0, .step = t }; + for (1..t) |k| { + var w = base; + w.from = k; + spawned[k] = std.Thread.spawn(.{}, Work.go, .{w}) catch null; + } + Work.go(base); + for (1..t) |k| if (spawned[k]) |th| th.join() else { + var w = base; + w.from = k; + Work.go(w); + }; + s.seen += count; + } + + pub fn result(s: *const Scorer) !Score { + if (s.seen != s.rows) return error.MissingRows; + var kl: f64 = 0; + var kl_max: f64 = 0; + var agree: usize = 0; + var max_abs: f64 = 0; + var nt: f64 = 0; + var nc: f64 = 0; + for (s.scored) |r| { + kl += r.kl; + kl_max = @max(kl_max, r.kl); + agree += @intFromBool(r.agree); + max_abs = @max(max_abs, r.max_abs); + nt += r.nll_truth; + nc += r.nll_cand; + } + const n: f64 = @floatFromInt(s.rows); + const targets: f64 = @floatFromInt(s.rows - 1); + return .{ .rows = s.rows, .kl_mean = kl / n, .kl_max = kl_max, .top1 = 100.0 * @as(f64, @floatFromInt(agree)) / n, .max_abs = max_abs, .ppl = @exp(nc / targets), .ppl_truth = @exp(nt / targets) }; + } +}; + +test { + _ = @import("logit_kind.zig"); +} + +test "a row scored against itself has no divergence" { + var truth: [4 * 8]u8 = undefined; + var cand: [4 * 4]u8 = undefined; + for ([_]f32{ 1.5, -2, 0.25, 3 }, 0..) |v, i| { + std.mem.writeInt(u64, truth[i * 8 ..][0..8], @bitCast(@as(f64, v)), .little); + std.mem.writeInt(u32, cand[i * 4 ..][0..4], @bitCast(v), .little); + } + const r = scoreRow(true, &truth, .f32, &cand, 4, 3); + try std.testing.expect(@abs(r.kl) < 1e-12); + try std.testing.expect(r.agree); + try std.testing.expectEqual(@as(f64, 0), r.max_abs); + try std.testing.expectApproxEqAbs(r.nll_truth, r.nll_cand, 1e-12); +} + +test "the divergence of a shifted row is the log-sum-exp gap" { + // truth (0, 0) is uniform, the candidate (0, ln 3) puts 3/4 on the second + var truth: [2 * 4]u8 = undefined; + var cand: [2 * 4]u8 = undefined; + std.mem.writeInt(u32, truth[0..4], @bitCast(@as(f32, 0)), .little); + std.mem.writeInt(u32, truth[4..8], @bitCast(@as(f32, 0)), .little); + std.mem.writeInt(u32, cand[0..4], @bitCast(@as(f32, 0)), .little); + std.mem.writeInt(u32, cand[4..8], @bitCast(@as(f32, @floatCast(@log(3.0)))), .little); + const r = scoreRow(false, &truth, .f32, &cand, 2, null); + const want = 0.5 * @log(0.5 / 0.25) + 0.5 * @log(0.5 / 0.75); + try std.testing.expectApproxEqAbs(want, r.kl, 1e-6); + try std.testing.expect(!r.agree); +} From 3d9bd2e69f8a9413e6262ed0b1a8343aac8e7e18 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:35:42 +0200 Subject: [PATCH 13/52] feat(hip): one rank source: --speed-up is refused, the HIP engine's ranks come from --tp The two-Mac engines take their ranks from --speed-up's settings file; the HIP engine takes them from --tp and the flags beside it. A HIP serve given --speed-up is refused, with or without --tp, so the two never mean different things for one model. --- zig/src/native/hip.zig | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index c28e918c5e7..c77d3a54a66 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -40,6 +40,8 @@ fn refuse(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: an fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { if (o.tp != 1 and o.tp != 2 and o.tp != 4 and o.tp != 8) return refuse(a, problem, "--tp {d} is not a supported ROCm world size; choose 1, 2, 4 or 8", .{o.tp}); if (o.tp > 1 and o.master.len == 0) return refuse(a, problem, "--tp > 1 needs --master: rank 0's address on the link between the machines", .{}); + // the two-Mac engines take their ranks from --speed-up's settings file; this engine takes them from --tp + if (o.speed_up != null) return refuse(a, problem, "--speed-up is the two-Mac engines' rank settings; the HIP engine takes its ranks from --tp", .{}); if (o.tp == 1 and o.rank != 0) return refuse(a, problem, "--rank must be 0 when --tp 1", .{}); if (o.rank >= o.tp) return refuse(a, problem, "--rank {d} not in [0, --tp {d})", .{ o.rank, o.tp }); if (o.keep) |n| if (n < 0) return refuse(a, problem, "--checkpoint-slots must be 0 or more", .{}); @@ -199,3 +201,32 @@ test "every registered family is listed for capabilities" { try std.testing.expectEqualStrings("qwen3_5", families[0].model_type); try std.testing.expectEqualStrings("qwen3_5_moe", families[1].model_type); } + +test "the group flags: one rank source, a supported world, a master past one rank, a rank inside the world" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + const base: api.Open = .{ .dir = "d", .model_type = "qwen3_5" }; + try checkGroup(a, base, &problem); + var two = base; + two.tp = 2; + two.master = "node0"; + try checkGroup(a, two, &problem); + var speed = base; + speed.speed_up = "settings.json"; + try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + try std.testing.expect(std.mem.indexOf(u8, problem, "--speed-up") != null); + speed.tp = 2; + speed.master = "node0"; + try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + var three = two; + three.tp = 3; + try std.testing.expectError(error.Refused, checkGroup(a, three, &problem)); + var lone = two; + lone.master = ""; + try std.testing.expectError(error.Refused, checkGroup(a, lone, &problem)); + var outside = two; + outside.rank = 2; + try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); +} From a25c8e236a2dfef15fb25804e774000b2bc11a7c Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:11:10 +0200 Subject: [PATCH 14/52] feat(qwen3_5): the HIP prompt cache serves serial requests too A request with drafts off resumed nothing and kept nothing; it now resumes from the deepest shared snapshot and keeps its marks as a drafted one does. The kept states are the target's alone (pages, DeltaNet states), so a serial pass keeps what a drafted one reads and the other way round. --- zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig index b4741382e19..6c3dd3e1c9c 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -286,13 +286,12 @@ pub const Hip = struct { errdefer h.free(lane); gop.value_ptr.* = lane; lane.id = try h.idOf(s); - // a drafted request resumes from the deepest shared snapshot and keeps its own marks; a serial one does neither + // a request resumes from the deepest shared snapshot and keeps its own marks, drafted or serial alike var owner: hip_prefix.Owner = .{ .caches = &lane.caches, .id = lane.id }; h.matched.clearRetainingCapacity(); - var plan: radix.Plan = .{}; h.prefix.restored = worker.no_snapshot; - if (s.drafts) plan = try h.prefix.begin(prompt, s.history_len, s.shared_prefixes, &owner, &h.matched); - defer if (s.drafts) h.gpa.free(plan.marks); + const plan = try h.prefix.begin(prompt, s.history_len, s.shared_prefixes, &owner, &h.matched); + defer h.gpa.free(plan.marks); errdefer for (h.matched.items) |id| h.e.pool.release(id); const at: usize = plan.from; const adopted = h.matched.items.len; From 309277438c5ee88ffc029e272123091d48f8fc43 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:14:44 +0200 Subject: [PATCH 15/52] test(qwen3_5): chat with the prompt cache equals chat without it through regenerate, edit and delete rewinds serve_rewind.py runs one conversation against a server with the cache and one with --prompt-cache-gib 0, drafts on and off: three turns, a regenerate, an edit of the last user message, a delete and a new turn, an edit of the first turn. Every reply must be equal; it prints the prompt tokens each step took from kept states. --- zig/tests/qwen35/serve_rewind.py | 63 ++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 zig/tests/qwen35/serve_rewind.py diff --git a/zig/tests/qwen35/serve_rewind.py b/zig/tests/qwen35/serve_rewind.py new file mode 100644 index 00000000000..de702eedc05 --- /dev/null +++ b/zig/tests/qwen35/serve_rewind.py @@ -0,0 +1,63 @@ +"""Chat with the prompt cache equals chat without it, through regenerate, edit and delete rewinds. + +usage: serve_rewind.py CACHED_URL UNCACHED_URL MODEL [SYSTEM_WORDS]; exits 1 on any differing reply. +""" + +import json +import sys +import urllib.request + +CACHED, UNCACHED, MODEL = sys.argv[1], sys.argv[2], sys.argv[3] +WORDS = int(sys.argv[4]) if len(sys.argv) > 4 else 1500 +SYSTEM = "You are a careful assistant. Reference notes: " + " ".join(f"note{i % 89}x{(i * 7919) % 1013}" for i in range(WORDS)) + + +def chat(url, messages, draft=True): + """The reply's text and the prompt tokens the server says it took from kept states.""" + body = {"model": MODEL, "messages": messages, "max_tokens": 48, "temperature": 0.0, "draft": draft, + "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(url + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=900) as reply: + doc = json.loads(reply.read()) + cached = (doc.get("usage", {}).get("prompt_tokens_details") or {}).get("cached_tokens", 0) + return doc["choices"][0]["message"]["content"], cached + + +def script(): + """The steps of one conversation, each the messages a client sends; replies are filled in as they come.""" + system = {"role": "system", "content": SYSTEM} + return [ + ("turn 1", lambda h: [system, {"role": "user", "content": "What is the first note?"}]), + ("turn 2", lambda h: h["turn 1"] + [{"role": "user", "content": "And the second one?"}]), + ("turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note5x5 listed?"}]), + ("regenerate turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note5x5 listed?"}]), + ("edit turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note7x7 listed?"}]), + ("delete turn 3, then turn 4", lambda h: h["turn 2"] + [{"role": "user", "content": "Name the last note."}]), + ("edit turn 1", lambda h: [system, {"role": "user", "content": "What is the third note?"}]), + ("turn 2 again", lambda h: h["turn 1"] + [{"role": "user", "content": "And the second one?"}]), + ] + + +def run(url, draft): + """Every step's reply on `url`; a step's history keeps the reply it got.""" + history, out = {}, [] + for name, build in script(): + messages = build(history) + text, cached = chat(url, messages, draft) + history[name] = messages + [{"role": "assistant", "content": text}] + out.append((name, text, cached)) + return out + + +bad = 0 +for draft in (True, False): + plain = run(UNCACHED, draft) + kept = run(CACHED, draft) + for (name, want, _), (_, got, cached) in zip(plain, kept): + ok = got == want + bad += not ok + print(f"{'PASS' if ok else 'FAIL'} rewind {name}, drafts {'on' if draft else 'off'}: {cached} prompt tokens from kept states") + if not ok: + print(f" without the cache: {want!r}\n with it: {got!r}") +print(f"rewind {'PASS' if bad == 0 else 'FAIL'}: {bad} differing replies") +sys.exit(1 if bad else 0) From 9a4e10fda3f1430a71b487fab70874c2adefbab4 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:34:54 +0200 Subject: [PATCH 16/52] feat(qwen3_5): a prompt runs 512-row chunks while other streams decode A prompt pass ran 1024-row chunks whatever else was running, so a decoding stream waited about 500 ms (gfx1100, 9B 4-bit) for each one. While another stream decodes, chunks are now policy fill_rows rows (512 by default, a multiple of 64 dividing 1024); alone, 1024. A prompt cut on 64 rows gives the same tokens however it is cut: with 256- and 1024-row chunks the 9B 4-bit and the 35B-A3B 2-bit reply the same to prompts of 325 to 5025 tokens. The policy carries fill_rows to every rank. --- .../qwen3_5/backend/hip/engine/hip_lanes.zig | 10 +++++++++- .../qwen3_5/backend/hip/engine/prefix.zig | 17 +++++++++++++---- zig/src/hip/policy.zig | 18 ++++++++++++++---- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig index 6c3dd3e1c9c..cb06dce4720 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -198,6 +198,13 @@ pub const Hip = struct { h.gpa.destroy(l); } + /// Whether a stream past its prompt holds a lane: a prompt's chunk then holds its round back. + fn decoding(h: *const Hip) bool { + var it = h.lanes.valueIterator(); + while (it.next()) |l| if (l.*.fill == null) return true; + return false; + } + /// The backend behind `ptr`, the calling thread bound to its GPU (the lane thread did not open it). fn of(ptr: *anyopaque) *Hip { const h: *Hip = @ptrCast(@alignCast(ptr)); @@ -328,7 +335,8 @@ pub const Hip = struct { const prompt = s.prompt(); const f = &lane.fill.?; const limit: usize = if (f.next < f.count) f.stops[f.next] else prompt.len; - const to = prefix.chunkEnd(f.at, limit); + // a prompt cut anywhere on 64 rows gives the same bits; streams decoding between chunks wait less on short ones + const to = prefix.chunkEnd(f.at, limit, if (h.decoding()) h.e.o.policy.fill_rows else prefix.chunk); if (h.link != null) try h.send(&.{ @backingInt(worker.Op.fill), lane.id, @intCast(to) }); if (to == prompt.len) { _ = h.take(try h.e.prefill(&lane.caches, prompt, f.at, lane.hidden, .{ .sampling = sampling(s), .position = prompt.len }, null)); diff --git a/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig b/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig index a0619770a8e..15ee1d22a3e 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/prefix.zig @@ -1,5 +1,6 @@ //! The chunks a prompt pass runs in, and the gap between the snapshots it keeps. +const std = @import("std"); const pages = @import("../forward/pages.zig"); /// A snapshot this close to the prompt's end saves too little to keep next to the one before it. @@ -8,10 +9,18 @@ pub const min_gap = 256; /// Cuts sit on page edges, multiples of the recurrence's chunk, so a resumed span chunks as a fresh prompt does. pub const step = pages.tokens; -/// Rows a prompt pass advances between two rounds; its steps end on multiples of this, so a prompt is cut the same way. +/// Rows a prompt pass advances between two rounds when no other stream decodes; steps end on multiples of it. pub const chunk = 1024; -/// Where the step from `at` ends: the next multiple of `chunk`, or `limit` when that comes first. -pub fn chunkEnd(at: usize, limit: usize) usize { - return @min(limit, (at / chunk + 1) * chunk); +/// Where the step from `at` ends: the next multiple of `rows`, or `limit` when that comes first. +pub fn chunkEnd(at: usize, limit: usize, rows: usize) usize { + return @min(limit, (at / rows + 1) * rows); +} + +test "a prompt step ends on the next multiple of its rows, or the prompt's cut" { + try std.testing.expectEqual(@as(usize, 1024), chunkEnd(0, 5000, chunk)); + try std.testing.expectEqual(@as(usize, 512), chunkEnd(0, 5000, 512)); + try std.testing.expectEqual(@as(usize, 1024), chunkEnd(512, 5000, 512)); + try std.testing.expectEqual(@as(usize, 1024), chunkEnd(700, 5000, chunk)); + try std.testing.expectEqual(@as(usize, 900), chunkEnd(700, 900, 512)); } diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index 49093cc7b3c..a94dfe10491 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -40,6 +40,8 @@ pub const Policy = struct { fuse: Pick = .auto, gdn: Pick = .auto, prefill_step: u32 = 1024, + /// Prompt rows a chunk while other streams decode: a multiple of 64 dividing 1024 (the idle chunk). + fill_rows: u32 = 512, /// Set from the serve flags, not keys: rank 0's travel to the other ranks. mtp: Mtp = .{}, /// Snapshots the radix prompt cache keeps (`--checkpoint-slots`). @@ -104,6 +106,7 @@ pub const Policy = struct { try next.set(pair[0..eq], pair[eq + 1 ..]); } if (next.prefill_step == 0 or next.prefill_step % 64 != 0) return error.StepNotAligned; + if (next.fill_rows == 0 or next.fill_rows % 64 != 0 or 1024 % next.fill_rows != 0) return error.StepNotAligned; p.* = next; } @@ -111,6 +114,8 @@ pub const Policy = struct { const eql = std.mem.eql; if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "gdn")) p.gdn = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { p.prefill_step = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; + } else if (eql(u8, key, "fill_rows")) { + p.fill_rows = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; } else if (eql(u8, key, "graph_fail")) { p.graph_fail = std.fmt.parseInt(i32, value, 10) catch return error.BadValue; } else if (eql(u8, key, "rccl_lib")) try p.rccl_lib.set(value) else return error.UnknownKey; @@ -122,7 +127,7 @@ pub const Policy = struct { /// One line for the start-up log and server info; default and local fields are left out of the keys. pub fn format(p: Policy, w: *std.Io.Writer) std.Io.Writer.Error!void { - try w.print("matrix={t},attention={t},kernels={t},graphs={t},prefill_step={d}", .{ p.matrix, p.attention, p.kernels, p.graphs, p.prefill_step }); + try w.print("matrix={t},attention={t},kernels={t},graphs={t},prefill_step={d},fill_rows={d}", .{ p.matrix, p.attention, p.kernels, p.graphs, p.prefill_step, p.fill_rows }); if (p.stream != .auto) try w.print(",stream={t}", .{p.stream}); if (p.gemm != .auto) try w.print(",gemm={t}", .{p.gemm}); if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); @@ -132,7 +137,7 @@ pub const Policy = struct { try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); } - pub const word_count = 6; + pub const word_count = 7; /// The policy as a fixed set of words, for rank 0 to send and every rank to use the same. pub fn words(p: Policy) [word_count]u32 { @@ -143,7 +148,7 @@ pub const Policy = struct { }; var nibbles: [2]u32 = .{ 0, 0 }; for (pack, 0..) |v, i| nibbles[i / 8] |= v << @intCast(4 * (i % 8)); - return .{ nibbles[0], nibbles[1] | @as(u32, p.mtp.drafts) << 24, p.prefill_step, @truncate(conf), @intCast(conf >> 32), p.slots }; + return .{ nibbles[0], nibbles[1] | @as(u32, p.mtp.drafts) << 24, p.prefill_step, @truncate(conf), @intCast(conf >> 32), p.slots, p.fill_rows }; } /// `local` with every field rank 0 sent; a rank keeps its own graph fault and library path. @@ -162,6 +167,7 @@ pub const Policy = struct { p.mtp = .{ .drafts = @truncate(w[1] >> 24), .confidence = @bitCast(@as(u64, w[3]) | @as(u64, w[4]) << 32) }; p.prefill_step = w[2]; p.slots = w[5]; + p.fill_rows = w[6]; return p; } @@ -218,11 +224,15 @@ test "apply sets fields and refuses what it does not know" { try std.testing.expectError(error.UnknownKey, p.apply("mtp_drafts=2")); try std.testing.expectError(error.BadValue, p.apply("matrix=maybe")); try std.testing.expectError(error.StepNotAligned, p.apply("prefill_step=1000")); + try p.apply("fill_rows=256"); + try std.testing.expectEqual(@as(u32, 256), p.fill_rows); + for ([_][]const u8{ "fill_rows=0", "fill_rows=100", "fill_rows=384", "fill_rows=2048" }) |bad| try std.testing.expectError(error.StepNotAligned, p.apply(bad)); + try std.testing.expectEqual(@as(u32, 256), p.fill_rows); } test "a policy survives its words" { var p: Policy = .{ .mtp = .{ .drafts = 2, .confidence = 0.25 }, .slots = 4, .graph_fail = 1 }; - try p.apply("matrix=on,attention=f32,graphs=off,gdn=reference"); + try p.apply("matrix=on,attention=f32,graphs=off,gdn=reference,fill_rows=128"); const back = Policy.fromWords(p.words(), .{ .graph_fail = 1 }); try std.testing.expectEqualDeep(p, back); } From 3f396fc6aaf4da9735df82ad242572e29d4485b5 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 06:21:13 +0200 Subject: [PATCH 17/52] feat(hip): RDNA4 runs on the dot2 tiles; matrix=on is refused where no matrix-core tile exists gfx1200 and gfx1201 build every target (the server, the model checks, the kernel and runtime tests, the bench) and run their products on the dot2 and stream tiles: the matrix-core GEMM is gfx11's WMMA layout only. matrix=on asked for matrix cores and silently got dot2 there; a serve now refuses it, naming the gfx12 tiles as not implemented yet (RDNA2: no matrix cores). matrix=auto, the default, runs on every GPU in the caps table. --- zig/src/native/hip.zig | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index c77d3a54a66..e6cb44d1fdc 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -36,6 +36,16 @@ fn refuse(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: an return error.Refused; } +/// Why `matrix=on` cannot run on a GPU of `caps`, or null when its matrix-core tiles exist (gfx11's WMMA). +fn matrixRefused(policy: hip.Policy, caps: hip.Caps) ?[]const u8 { + if (policy.matrix != .on) return null; + return switch (caps.matrix) { + .wmma11 => null, + .wmma12 => "the gfx12 matrix-core tiles (RDNA4's WMMA layout) are not implemented yet", + .none => "this GPU has no matrix cores", + }; +} + /// The tensor-parallel flags as the Python ROCm server checks them. fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { if (o.tp != 1 and o.tp != 2 and o.tp != 4 and o.tp != 8) return refuse(a, problem, "--tp {d} is not a supported ROCm world size; choose 1, 2, 4 or 8", .{o.tp}); @@ -81,6 +91,7 @@ fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open if (o.mtp_drafts) |n| policy.mtp.drafts = @intCast(n); if (o.mtp_confidence) |c| policy.mtp.confidence = c; if (o.keep) |n| policy.slots = @intCast(@min(n, 1 << 16)); + if (matrixRefused(policy, caps)) |why| return refuse(a, problem, "matrix=on: {s}; matrix=auto runs the dot2 tiles", .{why}); const group: ?*hip.Group = if (o.tp > 1) hip.Group.join(gpa, io, o.rank, o.tp, o.master, o.master_port, caps, &policy) catch |err| return switch (err) { error.OutOfMemory => error.OutOfMemory, error.NoRccl => refuse(a, problem, "tensor parallelism needs RCCL", .{}), @@ -230,3 +241,14 @@ test "the group flags: one rank source, a supported world, a master past one ran outside.rank = 2; try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); } + +test "matrix=on runs only where the matrix-core tiles exist; auto runs everywhere" { + var on: hip.Policy = .{}; + try on.apply("matrix=on"); + try std.testing.expect(matrixRefused(on, hip.Caps.of("gfx1100").?) == null); + try std.testing.expect(matrixRefused(on, hip.Caps.of("gfx1151").?) == null); + try std.testing.expect(std.mem.indexOf(u8, matrixRefused(on, hip.Caps.of("gfx1201").?).?, "not implemented") != null); + try std.testing.expect(matrixRefused(on, hip.Caps.of("gfx1030").?) != null); + const auto: hip.Policy = .{}; + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1151", "gfx1200", "gfx1201" }) |name| try std.testing.expect(matrixRefused(auto, hip.Caps.of(name).?) == null); +} From fc795cb457010ff269e4ea5495457e74d0b0a06d Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 06:58:11 +0200 Subject: [PATCH 18/52] test(qwen3_5): serve_rewind.py's docstring on one line, as the lean check asks --- zig/tests/qwen35/serve_rewind.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/zig/tests/qwen35/serve_rewind.py b/zig/tests/qwen35/serve_rewind.py index de702eedc05..4b903ab922a 100644 --- a/zig/tests/qwen35/serve_rewind.py +++ b/zig/tests/qwen35/serve_rewind.py @@ -1,7 +1,4 @@ -"""Chat with the prompt cache equals chat without it, through regenerate, edit and delete rewinds. - -usage: serve_rewind.py CACHED_URL UNCACHED_URL MODEL [SYSTEM_WORDS]; exits 1 on any differing reply. -""" +"""Cache on equals cache off through rewinds; usage: serve_rewind.py CACHED_URL UNCACHED_URL MODEL [WORDS].""" import json import sys From 10f67d94f63fb61766e899413b4e2652df512ff8 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 06:58:11 +0200 Subject: [PATCH 19/52] refactor(qwen3_5): the engine reaches the other ranks through hip/collective.zig; RCCL becomes its own PR The engine called RCCL and the ranks' TCP link directly. It now takes a collective.Group (the rank's link, its communicator opened once the GPU is current, its close) and a collective.Comm (all-reduce, all-gather, broadcast); tf-qwen35-test's group joins through the same hip.joinGroup as the server. This PR builds with no collectives backend: joinGroup refuses more than one rank, the server lists no --tp, and the rccl_lib policy key goes. RCCL (comm/: the library, the link, the group) returns behind the interface in the next PR, as #491's order has it; the engine's tensor-parallel paths and their kernels stay here, with their tests. --- .../qwen3_5/backend/hip/engine/engine.zig | 27 ++-- .../qwen3_5/backend/hip/engine/hip_lanes.zig | 4 +- .../qwen3_5/backend/hip/engine/hip_prefix.zig | 2 +- .../qwen3_5/backend/hip/engine/native.zig | 6 +- .../qwen3_5/backend/hip/engine/worker.zig | 2 +- .../qwen3_5/backend/hip/forward/reduce.zig | 8 +- .../qwen3_5/backend/hip/model/view.zig | 2 +- zig/src/hip/collective.zig | 127 ++++++++++++++++ zig/src/hip/comm/group.zig | 36 ----- zig/src/hip/comm/link.zig | 136 ------------------ zig/src/hip/comm/rccl.zig | 125 ---------------- zig/src/hip/device.zig | 4 +- zig/src/hip/policy.zig | 23 +-- zig/src/hip/root.zig | 10 +- zig/src/native/hip.zig | 7 +- zig/tests/qwen35/check.zig | 4 +- zig/tests/qwen35/group.zig | 31 ++-- zig/tests/qwen35/lanes_run.zig | 4 +- zig/tests/qwen35/lanes_session.zig | 2 +- zig/tests/qwen35/layers.zig | 23 +-- 20 files changed, 185 insertions(+), 398 deletions(-) create mode 100644 zig/src/hip/collective.zig delete mode 100644 zig/src/hip/comm/group.zig delete mode 100644 zig/src/hip/comm/link.zig delete mode 100644 zig/src/hip/comm/rccl.zig diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index 63874f637ac..f7c770d8ea9 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -39,10 +39,10 @@ pub const Options = struct { device: c_int = 0, /// Positions past a reply a verify writes (the window's rows and one more). slack: usize = 0, - /// Tensor parallelism: this rank of `world`, `id` being the communicator's unique id, the same on every rank. + /// Tensor parallelism: this rank of `world`, and the group it joined (it opens the communicator). rank: usize = 0, world: usize = 1, - id: ?hip.rccl.UniqueId = null, + group: ?hip.collective.Group = null, /// Replay rounds from captured graphs (the policy's `graphs` turns it off). graphs: bool = true, /// What the run may use, resolved once by whoever opens the engine. @@ -85,9 +85,8 @@ pub const Engine = struct { /// The keys and values of every stream and prefix entry. pool: pages.Pool, drawer: draw.Drawer, - /// Tensor parallelism: RCCL and this rank's communicator. - rccl: hip.rccl.Rccl = undefined, - comm: hip.rccl.Comm = undefined, + /// Tensor parallelism: this rank's communicator. + comm: hip.collective.Comm = undefined, graphs: round_graphs.Graphs, /// The draft head's batches replay graphs (the head holds no collective, so under tp too unless graphs=off). head_graphs: bool = true, @@ -117,15 +116,8 @@ pub const Engine = struct { e.stream = try hip.Stream.init(&e.driver); errdefer e.stream.deinit(); const group: ?slicing.Rank = if (o.world > 1) .{ .rank = o.rank, .world = o.world } else null; - if (group != null) { - e.rccl = try hip.rccl.Rccl.open(o.policy.rccl_lib.slice()); - errdefer e.rccl.close(); - e.comm = try hip.rccl.Comm.init(&e.rccl, o.id orelse return error.NoUniqueId, o.rank, o.world); - } - errdefer if (group != null) { - e.comm.deinit(); - e.rccl.close(); - }; + if (group != null) e.comm = try (o.group orelse return error.NoGroup).open(); + errdefer if (group != null) e.comm.close(); if (o.preflight) |pf| { // a rank loads its share of the checkpoint, near enough to refuse before reading it pf.* = .{ .pool = try e.budget(io), .held = hip.usage(false).device, .weights = admission.weightBytes(io, dir) / o.world }; @@ -264,10 +256,7 @@ pub const Engine = struct { e.weights.deinit(); e.stream.deinit(); e.lib.unload(); - if (e.o.world > 1) { - e.comm.deinit(); - e.rccl.close(); - } + if (e.o.world > 1) e.comm.close(); e.ctx.deinit(); e.driver.close(); e.gpa.destroy(e); @@ -318,7 +307,7 @@ pub const Engine = struct { } /// vocab_gather: every rank's slice of `rows` logits rows, joined on the device into whole rows in rank order. - fn joined(e: *Engine, o: hip.ops.Ops, c: hip.rccl.Comm, slice: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { + fn joined(e: *Engine, o: hip.ops.Ops, c: hip.collective.Comm, slice: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { const width = e.model().head.n; const n = rows * width; const size_of = slice.kind.size(); diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig index cb06dce4720..9d12c053226 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -61,7 +61,7 @@ pub const Hip = struct { matched: std.ArrayList(u32) = .empty, copied: std.ArrayList([3]u32) = .empty, /// Tensor parallelism: the other ranks, which get every step before this rank runs it (`worker.follow`). - link: ?*const hip.link.Link = null, + link: ?hip.collective.Link = null, msg: std.ArrayList(u32) = .empty, /// This engine's forward and head timings, filled by `measure` (none: the rule drafts the deepest it may). costs: costs.Costs = .{}, @@ -104,7 +104,7 @@ pub const Hip = struct { } /// Rank 0 of a tensor-parallel group: every step also goes to the ranks behind `link`. - pub fn withLink(h: *Hip, link: *const hip.link.Link) void { + pub fn withLink(h: *Hip, link: hip.collective.Link) void { h.link = link; h.prefix.link = link; } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig index 99175fa6788..06dfcd1699c 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_prefix.zig @@ -21,7 +21,7 @@ pub const Prefix = struct { /// Snapshot slots in use. used: std.ArrayList(bool) = .empty, /// The other ranks, when this is rank 0 of a group. - link: ?*const hip.link.Link = null, + link: ?hip.collective.Link = null, msg: std.ArrayList(u32) = .empty, /// The slot the last restore copied from (reset as a pass begins): the message that begins the pass names it. restored: u32 = worker.no_snapshot, diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig index 7a1a3c7a1a4..9ef3064454b 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -97,7 +97,7 @@ fn prepare(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.De .policy = dev.policy, .rank = o.rank, .world = o.world, - .id = if (dev.group) |g| g.id else null, + .group = dev.group, }) catch |err| return switch (err) { error.WeightsDoNotFit => refuse(a, problem, "the checkpoint's {d:.1} GiB of weights do not fit the {d:.1} GiB the HIP memory budget grants ({d:.1} GiB free less a {d:.1} GiB reserve{s}); free device memory or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_HIP_MEMORY_LIMIT_GB", .{ gibs(pf.weights), gibs(pf.pool.room(pf.held)), gibs(pf.pool.free), gibs(pf.pool.reserve), if (pf.pool.limit != null) ", under TENSORFOLD_HIP_MEMORY_LIMIT_GB" else "" }), error.BadReserve => refuse(a, problem, "TENSORFOLD_MEMORY_RESERVE_GIB: a number of GiB from 2 to the memory's size", .{}), @@ -182,7 +182,7 @@ fn openEngine(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip if (hip.usage(false).device - before != head) return refuse(a, problem, "the draft head holds {d} device bytes, the plan says {d}", .{ hip.usage(false).device - before, head }); if (p.cache.pages > 0) own.backend.keepPages(p.cache.pages, p.cache.snaps); // a lone rank times its forwards for the depth rule; the ranks of a group draft without costs - if (dev.group) |g| own.backend.withLink(&g.link) else own.backend.measure(); + if (dev.group) |g| own.backend.withLink(g.link()) else own.backend.measure(); return .{ .backend = own.backend.backend(), .facts = own.backend.facts(), @@ -201,5 +201,5 @@ fn followRank(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip defer gpa.free(p.startup); var w = try worker.Worker.init(gpa, p.e); defer w.deinit(); - try w.follow(&dev.group.?.link); + try w.follow(dev.group.?.link()); } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/worker.zig b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig index c69699c93cd..b390ca80442 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/worker.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig @@ -118,7 +118,7 @@ pub const Worker = struct { } /// Runs rank 0's steps until it says stop. - pub fn follow(w: *Worker, link: *const hip.link.Link) !void { + pub fn follow(w: *Worker, link: hip.collective.Link) !void { var msg: std.ArrayList(u32) = .empty; defer msg.deinit(w.gpa); var ids: [max_windows]u32 = undefined; diff --git a/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig b/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig index 62a57811dc9..7e20ac30113 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig @@ -7,10 +7,10 @@ const view = @import("../model/view.zig"); const Ops = hip.ops.Ops; const Tensor = hip.ops.Tensor; -pub const Error = hip.ops.Error || hip.rccl.Error; +pub const Error = hip.ops.Error || hip.collective.Error; /// `n` fp32 values summed over the ranks in rank order, so a row's sum does not depend on the rows sharing the call. -pub fn sum(o: Ops, c: hip.rccl.Comm, y: u64, n: usize) Error!u64 { +pub fn sum(o: Ops, c: hip.collective.Comm, y: u64, n: usize) Error!u64 { const out = try o.arena.of(f32, n); if (c.world == 2) { try c.allReduce(y, out, n, .f32, o.stream); @@ -32,7 +32,7 @@ pub fn residual(o: Ops, m: *const view.Model, x: Tensor, y: Tensor, n: usize) Er } /// The ranks' logits slices (world, rows, width) of the activation dtype, gathered into `out`. -pub fn gather(o: Ops, c: hip.rccl.Comm, slice: Tensor, out: u64, n: usize) Error!void { - const dtype: hip.rccl.Dtype = if (slice.kind == .f16) .f16 else .bf16; +pub fn gather(o: Ops, c: hip.collective.Comm, slice: Tensor, out: u64, n: usize) Error!void { + const dtype: hip.collective.Dtype = if (slice.kind == .f16) .f16 else .bf16; try c.allGather(slice.ptr, out, n, dtype, o.stream); } diff --git a/zig/src/families/qwen3_5/backend/hip/model/view.zig b/zig/src/families/qwen3_5/backend/hip/model/view.zig index e5b2f650064..4663e038c43 100644 --- a/zig/src/families/qwen3_5/backend/hip/model/view.zig +++ b/zig/src/families/qwen3_5/backend/hip/model/view.zig @@ -101,7 +101,7 @@ pub const Model = struct { /// What this rank sees: under tp its heads and value heads. spec: Spec, /// The tensor-parallel communicator; null on one rank. - tp: ?hip.rccl.Comm = null, + tp: ?hip.collective.Comm = null, act: Kind, embed: Projection, layers: []const Layer, diff --git a/zig/src/hip/collective.zig b/zig/src/hip/collective.zig new file mode 100644 index 00000000000..a24c55aba88 --- /dev/null +++ b/zig/src/hip/collective.zig @@ -0,0 +1,127 @@ +//! What a tensor-parallel engine asks of its ranks: collectives on its streams, and rank 0's words to the others. + +const std = @import("std"); +const abi = @import("abi.zig"); + +pub const Error = error{CollectiveFailed}; +pub const LinkError = error{LinkFailed} || std.mem.Allocator.Error; +/// Why a rank could not join its group: no tensor parallelism in this build, no RCCL, or the link between the ranks. +pub const JoinError = error{ NoTensorParallel, NoRccl, NoId, SocketFailed, BindFailed, ConnectFailed, LinkClosed, BadRank, MixedGpus } || std.mem.Allocator.Error; + +/// The join of a build without a collectives backend: one rank only. +pub fn noGroup(_: std.mem.Allocator, _: std.Io, _: u32, _: u32, _: []const u8, _: u16, _: @import("caps.zig").Caps, _: *@import("policy.zig").Policy) JoinError!Group { + return error.NoTensorParallel; +} + +/// The element types the forward moves, in RCCL's numbering. +pub const Dtype = enum(c_int) { u8 = 1, i32 = 2, i64 = 4, f16 = 6, f32 = 7, bf16 = 9 }; + +/// One rank's communicator. A collective queues on its stream and waits for every rank's matching call. +pub const Comm = struct { + ptr: *anyopaque, + vtable: *const VTable, + rank: usize, + world: usize, + + pub const VTable = struct { + all_reduce: *const fn (ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void, + all_gather: *const fn (ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void, + broadcast: *const fn (ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void, + close: *const fn (ptr: *anyopaque) void, + }; + + /// `recv` = the ranks' `send` summed, `n` values of `dtype`. + pub fn allReduce(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + return c.vtable.all_reduce(c.ptr, send, recv, n, dtype, stream); + } + + /// `recv` (world * n values) = every rank's `send` (n values) in rank order. + pub fn allGather(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + return c.vtable.all_gather(c.ptr, send, recv, n, dtype, stream); + } + + /// `root`'s `send` into every rank's `recv`, `n` values. + pub fn broadcast(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void { + return c.vtable.broadcast(c.ptr, send, recv, n, dtype, root, stream); + } + + pub fn close(c: Comm) void { + c.vtable.close(c.ptr); + } +}; + +/// Rank 0's channel to the others: it sends each step, a follower takes them in order. +pub const Link = struct { + ptr: *anyopaque, + vtable: *const VTable, + + pub const VTable = struct { + send: *const fn (ptr: *anyopaque, words: []const u32) LinkError!void, + recv: *const fn (ptr: *anyopaque, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) LinkError!void, + }; + + /// Rank 0: `words` to every follower. + pub fn send(l: Link, words: []const u32) LinkError!void { + return l.vtable.send(l.ptr, words); + } + + /// A follower: rank 0's next message into `out` (cleared first). + pub fn recv(l: Link, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) LinkError!void { + return l.vtable.recv(l.ptr, gpa, out); + } +}; + +/// What a rank holds once it joined its group: the link, and its communicator opened when the engine's GPU is current. +pub const Group = struct { + ptr: *anyopaque, + vtable: *const VTable, + rank: usize, + world: usize, + + pub const VTable = struct { + link: *const fn (ptr: *anyopaque) Link, + open: *const fn (ptr: *anyopaque) Error!Comm, + close: *const fn (ptr: *anyopaque, gpa: std.mem.Allocator) void, + }; + + pub fn link(g: Group) Link { + return g.vtable.link(g.ptr); + } + + /// This rank's communicator: blocks until every rank has opened its own; the engine's device is current. + pub fn open(g: Group) Error!Comm { + return g.vtable.open(g.ptr); + } + + pub fn close(g: Group, gpa: std.mem.Allocator) void { + g.vtable.close(g.ptr, gpa); + } +}; + +test "a comm forwards each collective to its implementation" { + const Fake = struct { + calls: [3]usize = .{ 0, 0, 0 }, + closed: bool = false, + fn reduce(ptr: *anyopaque, _: u64, _: u64, _: usize, _: Dtype, _: abi.Stream) Error!void { + @as(*@This(), @ptrCast(@alignCast(ptr))).calls[0] += 1; + } + fn gather(ptr: *anyopaque, _: u64, _: u64, _: usize, _: Dtype, _: abi.Stream) Error!void { + @as(*@This(), @ptrCast(@alignCast(ptr))).calls[1] += 1; + } + fn cast(ptr: *anyopaque, _: u64, _: u64, _: usize, _: Dtype, _: usize, _: abi.Stream) Error!void { + @as(*@This(), @ptrCast(@alignCast(ptr))).calls[2] += 1; + } + fn shut(ptr: *anyopaque) void { + @as(*@This(), @ptrCast(@alignCast(ptr))).closed = true; + } + }; + var f: Fake = .{}; + const c: Comm = .{ .ptr = &f, .vtable = &.{ .all_reduce = Fake.reduce, .all_gather = Fake.gather, .broadcast = Fake.cast, .close = Fake.shut }, .rank = 1, .world = 2 }; + try c.allReduce(0, 0, 1, .f32, null); + try c.allGather(0, 0, 1, .bf16, null); + try c.allGather(0, 0, 1, .bf16, null); + try c.broadcast(0, 0, 1, .i32, 0, null); + c.close(); + try std.testing.expectEqual([3]usize{ 1, 2, 1 }, f.calls); + try std.testing.expect(f.closed); +} diff --git a/zig/src/hip/comm/group.zig b/zig/src/hip/comm/group.zig deleted file mode 100644 index 9be68e2b7fd..00000000000 --- a/zig/src/hip/comm/group.zig +++ /dev/null @@ -1,36 +0,0 @@ -//! The ranks of a tensor-parallel group: the TCP link that carries rank 0's steps and RCCL's unique id. - -const std = @import("std"); -const rccl_mod = @import("rccl.zig"); -const link_mod = @import("link.zig"); -const Caps = @import("../caps.zig").Caps; -const Policy = @import("../policy.zig").Policy; - -pub const Error = link_mod.Error || error{ NoRccl, NoId }; - -/// RCCL's library stays loaded until the group is closed (its bootstrap thread starts at the id). -pub const Group = struct { - rccl: rccl_mod.Rccl, - link: link_mod.Link, - id: rccl_mod.UniqueId, - - /// Rank 0 listens on `master`:`port`, sends its id and policy; a rank whose GPU differs from rank 0's is refused. - pub fn join(gpa: std.mem.Allocator, io: std.Io, rank: u32, world: u32, master: []const u8, port: u16, caps: Caps, policy: *Policy) Error!*Group { - const g = try gpa.create(Group); - errdefer gpa.destroy(g); - g.rccl = rccl_mod.Rccl.open(policy.rccl_lib.slice()) catch return error.NoRccl; - errdefer g.rccl.close(); - const mine: rccl_mod.UniqueId = if (rank == 0) g.rccl.uniqueId() catch return error.NoId else undefined; - const host = if (std.mem.eql(u8, master, "localhost")) "127.0.0.1" else master; - const pair = try link_mod.Link.open(io, rank, world, host, port, mine, .{ .caps = @import("../device.zig").Device.groupId(caps), .policy = policy.words() }); - g.link, g.id, const hello = pair; - if (rank != 0) policy.* = Policy.fromWords(hello.policy, policy.*); - return g; - } - - pub fn close(g: *Group, gpa: std.mem.Allocator) void { - g.link.close(); - g.rccl.close(); - gpa.destroy(g); - } -}; diff --git a/zig/src/hip/comm/link.zig b/zig/src/hip/comm/link.zig deleted file mode 100644 index 0ec403f56b5..00000000000 --- a/zig/src/hip/comm/link.zig +++ /dev/null @@ -1,136 +0,0 @@ -//! The ranks' TCP link: rank 0 listens, the others connect once, get the communicator's id, take rank 0's commands. - -const std = @import("std"); -const posix = std.posix; -const rccl = @import("rccl.zig"); -const Policy = @import("../policy.zig").Policy; - -pub const Error = error{ SocketFailed, BindFailed, ConnectFailed, LinkClosed, BadRank, MixedGpus } || std.mem.Allocator.Error; - -pub const max_world = 16; - -/// What the ranks agree on at join: the kernels' GPU id (every rank's must match) and rank 0's policy. -pub const Hello = struct { caps: u32, policy: [Policy.word_count]u32 }; - -pub const Link = struct { - rank: usize, - world: usize, - /// Rank 0: the follower of rank r + 1 at index r. A follower: rank 0's socket at index 0. - fds: [max_world - 1]posix.socket_t = undefined, - - /// Rank 0 listens on `host:port`, sends each rank `id` and `hello`; a GPU that differs from rank 0's is refused. - pub fn open(io: std.Io, rank: usize, world: usize, host: []const u8, port: u16, id: rccl.UniqueId, hello: Hello) Error!struct { Link, rccl.UniqueId, Hello } { - if (world < 2 or world > max_world or rank >= world) return error.BadRank; - const ip = std.Io.net.IpAddress.parse(host, port) catch return error.ConnectFailed; - if (ip != .ip4) return error.ConnectFailed; - var addr: posix.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port), .addr = std.mem.readInt(u32, &ip.ip4.bytes, .little) }; - var link: Link = .{ .rank = rank, .world = world }; - if (rank == 0) { - const server = try socket(); - defer _ = posix.system.close(server); - const one: c_int = 1; - posix.setsockopt(server, posix.SOL.SOCKET, posix.SO.REUSEADDR, std.mem.asBytes(&one)) catch return error.SocketFailed; - if (posix.errno(posix.system.bind(server, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) != .SUCCESS) return error.BindFailed; - if (posix.errno(posix.system.listen(server, 16)) != .SUCCESS) return error.BindFailed; - var seen: usize = 0; - while (seen < world - 1) : (seen += 1) { - const rc = posix.system.accept(server, null, null); - if (posix.errno(rc) != .SUCCESS) return error.SocketFailed; - const fd: posix.socket_t = @intCast(rc); - var peer: u32 = undefined; - try readAll(fd, std.mem.asBytes(&peer)); - var caps: u32 = undefined; - try readAll(fd, std.mem.asBytes(&caps)); - if (peer == 0 or peer >= world) return error.BadRank; - link.fds[peer - 1] = fd; - const status: u32 = if (caps == hello.caps) 0 else 1; - try writeAll(fd, std.mem.asBytes(&status)); - if (status != 0) return error.MixedGpus; - try writeAll(fd, std.mem.asBytes(&id)); - try writeAll(fd, std.mem.sliceAsBytes(&hello.policy)); - } - return .{ link, id, hello }; - } - var tries: usize = 0; - while (true) : (tries += 1) { - const fd = try socket(); - if (posix.errno(posix.system.connect(fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) == .SUCCESS) { - link.fds[0] = fd; - break; - } - _ = posix.system.close(fd); - if (tries >= 6000) return error.ConnectFailed; - std.Io.sleep(io, .fromMilliseconds(100), .awake) catch {}; - } - const mine: u32 = @intCast(rank); - try writeAll(link.fds[0], std.mem.asBytes(&mine)); - try writeAll(link.fds[0], std.mem.asBytes(&hello.caps)); - var status: u32 = undefined; - try readAll(link.fds[0], std.mem.asBytes(&status)); - if (status != 0) return error.MixedGpus; - var got: rccl.UniqueId = undefined; - try readAll(link.fds[0], std.mem.asBytes(&got)); - var theirs: Hello = .{ .caps = hello.caps, .policy = undefined }; - try readAll(link.fds[0], std.mem.sliceAsBytes(&theirs.policy)); - return .{ link, got, theirs }; - } - - pub fn close(l: *Link) void { - const n = if (l.rank == 0) l.world - 1 else 1; - for (l.fds[0..n]) |fd| _ = posix.system.close(fd); - } - - /// Rank 0: `words` to every follower, behind their count. - pub fn send(l: *const Link, words: []const u32) Error!void { - const n: u32 = @intCast(words.len); - for (l.fds[0 .. l.world - 1]) |fd| { - try writeAll(fd, std.mem.asBytes(&n)); - try writeAll(fd, std.mem.sliceAsBytes(words)); - } - } - - /// A follower: rank 0's next message, appended to `out` (cleared first). - pub fn recv(l: *const Link, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) Error!void { - var n: u32 = undefined; - try readAll(l.fds[0], std.mem.asBytes(&n)); - out.clearRetainingCapacity(); - try out.resize(gpa, n); - try readAll(l.fds[0], std.mem.sliceAsBytes(out.items)); - } -}; - -fn socket() Error!posix.socket_t { - const rc = posix.system.socket(posix.AF.INET, posix.SOCK.STREAM, 0); - if (posix.errno(rc) != .SUCCESS) return error.SocketFailed; - const fd: posix.socket_t = @intCast(rc); - const one: c_int = 1; - posix.setsockopt(fd, posix.IPPROTO.TCP, posix.TCP.NODELAY, std.mem.asBytes(&one)) catch {}; - return fd; -} - -fn writeAll(fd: posix.socket_t, bytes: []const u8) Error!void { - var at: usize = 0; - while (at < bytes.len) { - const rc = posix.system.write(fd, bytes[at..].ptr, bytes.len - at); - switch (posix.errno(rc)) { - .SUCCESS => at += @intCast(rc), - .INTR => {}, - else => return error.LinkClosed, - } - } -} - -fn readAll(fd: posix.socket_t, bytes: []u8) Error!void { - var at: usize = 0; - while (at < bytes.len) { - const rc = posix.system.read(fd, bytes[at..].ptr, bytes.len - at); - switch (posix.errno(rc)) { - .SUCCESS => { - if (rc == 0) return error.LinkClosed; - at += @intCast(rc); - }, - .INTR => {}, - else => return error.LinkClosed, - } - } -} diff --git a/zig/src/hip/comm/rccl.zig b/zig/src/hip/comm/rccl.zig deleted file mode 100644 index 74ff5e6544e..00000000000 --- a/zig/src/hip/comm/rccl.zig +++ /dev/null @@ -1,125 +0,0 @@ -//! RCCL opened at run time: the tensor-parallel forward's collectives on our streams, as hand-declared exports. - -const std = @import("std"); -const abi = @import("../abi.zig"); - -pub const Error = error{ RcclUnavailable, MissingSymbol, RcclFailed, Invalid }; - -/// ncclUniqueId: the opaque 128 bytes rank 0 makes and every rank passes to its init. -pub const UniqueId = extern struct { internal: [128]u8 }; - -/// ncclDataType_t, RCCL's numbering. -pub const Dtype = enum(c_int) { u8 = 1, i32 = 2, i64 = 4, f16 = 6, f32 = 7, bf16 = 9 }; - -const Handle = ?*anyopaque; -const C = ?*const anyopaque; -const P = ?*anyopaque; - -/// Each field is the library's exact export. -const Api = struct { - ncclGetErrorString: *const fn (c_int) callconv(.c) [*:0]const u8, - ncclGetUniqueId: *const fn (*UniqueId) callconv(.c) c_int, - ncclCommInitRank: *const fn (*Handle, c_int, UniqueId, c_int) callconv(.c) c_int, - ncclCommDestroy: *const fn (Handle) callconv(.c) c_int, - ncclAllReduce: *const fn (C, P, usize, c_int, c_int, Handle, abi.Stream) callconv(.c) c_int, - ncclAllGather: *const fn (C, P, usize, c_int, Handle, abi.Stream) callconv(.c) c_int, - ncclBroadcast: *const fn (C, P, usize, c_int, c_int, Handle, abi.Stream) callconv(.c) c_int, -}; - -const paths = [_][]const u8{ "librccl.so.1", "librccl.so", "/opt/rocm/lib/librccl.so.1" }; - -/// ncclSum: the only reduction the forward uses. -const sum_op: c_int = 0; - -pub const Rccl = struct { - lib: std.DynLib, - api: Api, - - /// `first` (the policy's `rccl_lib`) is tried before the usual places. - pub fn open(first: ?[]const u8) Error!Rccl { - var candidates: [paths.len + 1][]const u8 = undefined; - var n: usize = 0; - if (first) |path| { - candidates[0] = path; - n = 1; - } - for (paths) |path| { - candidates[n] = path; - n += 1; - } - for (candidates[0..n]) |path| { - var lib = std.DynLib.open(path) catch continue; - errdefer lib.close(); - var api: Api = undefined; - const info = @typeInfo(Api).@"struct"; - inline for (info.field_names, info.field_types) |name, T| { - @field(api, name) = lib.lookup(T, name) orelse { - std.log.err("{s} has no {s}", .{ path, name }); - return error.MissingSymbol; - }; - } - return .{ .lib = lib, .api = api }; - } - return error.RcclUnavailable; - } - - pub fn close(r: *Rccl) void { - r.lib.close(); - } - - fn check(r: *const Rccl, code: c_int, what: []const u8) Error!void { - if (code == 0) return; - std.log.err("{s}: RCCL error {d}: {s}", .{ what, code, std.mem.span(r.api.ncclGetErrorString(code)) }); - return error.RcclFailed; - } - - /// A fresh id; rank 0 makes it and hands it to the others. - pub fn uniqueId(r: *const Rccl) Error!UniqueId { - var id: UniqueId = undefined; - try r.check(r.api.ncclGetUniqueId(&id), "ncclGetUniqueId"); - return id; - } -}; - -/// One rank's communicator. Collectives queue on the stream they are given and wait for every rank's matching call. -pub const Comm = struct { - rccl: *const Rccl, - handle: Handle, - rank: usize, - world: usize, - - /// Joins the ranks; blocks until all `world` have called it with the same `id`. The device is current already. - pub fn init(rccl: *const Rccl, id: UniqueId, rank: usize, world: usize) Error!Comm { - if (world < 2 or rank >= world) return error.Invalid; - var h: Handle = null; - try rccl.check(rccl.api.ncclCommInitRank(&h, @intCast(world), id, @intCast(rank)), "ncclCommInitRank"); - return .{ .rccl = rccl, .handle = h, .rank = rank, .world = world }; - } - - pub fn deinit(c: *Comm) void { - _ = c.rccl.api.ncclCommDestroy(c.handle); - c.* = undefined; - } - - /// `recv` = the ranks' `send` summed, `n` values of `dtype` (sum of two ranks is the one add, any order). - pub fn allReduce(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { - if (stream == @import("../launches/util.zig").counting) return; - try c.rccl.check(c.rccl.api.ncclAllReduce(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), sum_op, c.handle, stream), "ncclAllReduce"); - } - - /// `recv` (world * n values) = every rank's `send` (n values) in rank order. - pub fn allGather(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { - if (stream == @import("../launches/util.zig").counting) return; - try c.rccl.check(c.rccl.api.ncclAllGather(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), c.handle, stream), "ncclAllGather"); - } - - /// `root`'s `send` into every rank's `recv`, `n` values. - pub fn broadcast(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void { - if (stream == @import("../launches/util.zig").counting) return; - try c.rccl.check(c.rccl.api.ncclBroadcast(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), @intCast(root), c.handle, stream), "ncclBroadcast"); - } -}; - -test "the unique id is the 128 bytes RCCL passes by value" { - try std.testing.expectEqual(@as(usize, 128), @sizeOf(UniqueId)); -} diff --git a/zig/src/hip/device.zig b/zig/src/hip/device.zig index 7ffe2d982ea..beb3b890875 100644 --- a/zig/src/hip/device.zig +++ b/zig/src/hip/device.zig @@ -5,7 +5,7 @@ const runtime = @import("runtime.zig"); const kernels = @import("kernels.zig"); const Caps = @import("caps.zig").Caps; const Policy = @import("policy.zig").Policy; -const Group = @import("comm/group.zig").Group; +const Group = @import("collective.zig").Group; pub const Device = struct { /// The ordinal among the visible cards. @@ -14,7 +14,7 @@ pub const Device = struct { /// Rank 0's policy; the other ranks adopt it when they join the group. policy: Policy, /// The tensor-parallel group this rank belongs to (null: one rank). - group: ?*Group = null, + group: ?Group = null, /// The card of `rank`: with every card visible rank r takes card r, with one card a process that card. pub fn ordinal(rank: u32) c_int { diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index a94dfe10491..30c9a2c1835 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -13,22 +13,6 @@ pub const Pick = enum { auto, reference }; /// MTP drafting: `--mtp-drafts` and `--mtp-confidence`. pub const Mtp = struct { drafts: u8 = 3, confidence: f64 = 0.3 }; -/// A path a rank reads locally (it never travels with the policy). -pub const Path = struct { - buf: [160]u8 = @splat(0), - - pub fn slice(p: *const Path) ?[]const u8 { - const n = std.mem.indexOfScalar(u8, &p.buf, 0) orelse p.buf.len; - return if (n == 0) null else p.buf[0..n]; - } - - fn set(p: *Path, text: []const u8) error{BadValue}!void { - if (text.len >= p.buf.len) return error.BadValue; - p.buf = @splat(0); - @memcpy(p.buf[0..text.len], text); - } -}; - pub const Policy = struct { matrix: Choice = .auto, attention: Attention = .auto, @@ -48,8 +32,6 @@ pub const Policy = struct { slots: u32 = 8, /// Rank whose graph capture fails on purpose, for the tests of the fallback (-1: none). Local to a rank. graph_fail: i32 = -1, - /// The RCCL library to load first. Local to a rank. - rccl_lib: Path = .{}, pub const Error = error{ UnknownKey, BadValue, StepNotAligned }; @@ -118,7 +100,7 @@ pub const Policy = struct { p.fill_rows = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; } else if (eql(u8, key, "graph_fail")) { p.graph_fail = std.fmt.parseInt(i32, value, 10) catch return error.BadValue; - } else if (eql(u8, key, "rccl_lib")) try p.rccl_lib.set(value) else return error.UnknownKey; + } else return error.UnknownKey; } fn parseEnum(comptime E: type, value: []const u8) Error!E { @@ -133,7 +115,6 @@ pub const Policy = struct { if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); if (p.gdn != .auto) try w.print(",gdn={t}", .{p.gdn}); if (p.graph_fail >= 0) try w.print(",graph_fail={d}", .{p.graph_fail}); - if (p.rccl_lib.slice()) |path| try w.print(",rccl_lib={s}", .{path}); try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); } @@ -151,7 +132,7 @@ pub const Policy = struct { return .{ nibbles[0], nibbles[1] | @as(u32, p.mtp.drafts) << 24, p.prefill_step, @truncate(conf), @intCast(conf >> 32), p.slots, p.fill_rows }; } - /// `local` with every field rank 0 sent; a rank keeps its own graph fault and library path. + /// `local` with every field rank 0 sent; a rank keeps its own graph fault. pub fn fromWords(w: [word_count]u32, local: Policy) Policy { var p = local; var vals: [8]u32 = undefined; diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index 83f2c0f2fe5..b9d896102a3 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -33,15 +33,13 @@ pub const Device = @import("device.zig").Device; pub const Upload = @import("upload.zig").Upload; pub const quant = @import("core").quant; pub const registry = @import("core").registry; -pub const rccl = @import("comm/rccl.zig"); -pub const link = @import("comm/link.zig"); -pub const Group = @import("comm/group.zig").Group; +pub const collective = @import("collective.zig"); +/// Joins this rank's tensor-parallel group; this build has no collectives backend, so one rank only. +pub const joinGroup = collective.noGroup; test { _ = policy; _ = admission; _ = Device; - _ = rccl; - _ = link; - _ = Group; + _ = collective; } diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index e6cb44d1fdc..72b4adb93c0 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -14,7 +14,7 @@ const registry = .{ qwen35.native, qwen35.native_moe }; pub const backends: []const []const u8 = &.{"hip"}; /// The serve flags past the common ones this backend takes (server/cli.zig lists and parses them). -pub const serves: []const []const u8 = &.{ "--tp", "--policy", "--mtp-drafts", "--mtp-confidence", "--checkpoint-slots", "--backend=rocm" }; +pub const serves: []const []const u8 = &.{ "--policy", "--mtp-drafts", "--mtp-confidence", "--checkpoint-slots", "--backend=rocm" }; pub const families: []const api.Family = blk: { var out: [registry.len]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats }; @@ -92,8 +92,9 @@ fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open if (o.mtp_confidence) |c| policy.mtp.confidence = c; if (o.keep) |n| policy.slots = @intCast(@min(n, 1 << 16)); if (matrixRefused(policy, caps)) |why| return refuse(a, problem, "matrix=on: {s}; matrix=auto runs the dot2 tiles", .{why}); - const group: ?*hip.Group = if (o.tp > 1) hip.Group.join(gpa, io, o.rank, o.tp, o.master, o.master_port, caps, &policy) catch |err| return switch (err) { + const group: ?hip.collective.Group = if (o.tp > 1) hip.joinGroup(gpa, io, o.rank, o.tp, o.master, o.master_port, caps, &policy) catch |err| return switch (err) { error.OutOfMemory => error.OutOfMemory, + error.NoTensorParallel => refuse(a, problem, "this build has no tensor parallelism: it comes with the RCCL backend", .{}), error.NoRccl => refuse(a, problem, "tensor parallelism needs RCCL", .{}), error.NoId => refuse(a, problem, "RCCL gave no id", .{}), error.MixedGpus => refuse(a, problem, "the ranks' GPUs differ: a group needs one kind of GPU", .{}), @@ -120,7 +121,7 @@ fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open /// One loaded model behind the lane host: everything the engine thread reads lives here. const Host = struct { gpa: Allocator, - group: ?*hip.Group, + group: ?hip.collective.Group, policy_line: []const u8, family: *anyopaque, release: *const fn (*anyopaque) void, diff --git a/zig/tests/qwen35/check.zig b/zig/tests/qwen35/check.zig index 105a5eaf390..d2acb9d4bc1 100644 --- a/zig/tests/qwen35/check.zig +++ b/zig/tests/qwen35/check.zig @@ -91,7 +91,7 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !u8 { capacity = @max(capacity, check_radix.capacity(o.tokens)); if (o.runs(.accuracy)) capacity = @max(capacity, ids.len + 64); if (o.runs(.speed)) capacity = @max(capacity, check_speed.longest_prefill + 64); - var joined = try o.group.join(io); + var joined = try o.group.join(gpa, io); defer joined.close(); const e = try o.group.engine(gpa, io, o.model, joined, .{ .capacity = capacity, .prompt_rows = capacity, .streams = check_radix.most_streams, .snapshots = check_radix.slots, .batch_rows = rows, .pool_pages = poolPages(capacity, o.tokens) }); defer e.deinit(); @@ -107,7 +107,7 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !u8 { return 0; } var session: lanes_session.Session = undefined; - try session.init(gpa, io, e, if (o.group.world > 1) &joined.link else null); + try session.init(gpa, io, e, joined.link()); defer session.deinit(); var report: check_report.Report = .{}; diff --git a/zig/tests/qwen35/group.zig b/zig/tests/qwen35/group.zig index 09f00b2a6ee..0b5d444f610 100644 --- a/zig/tests/qwen35/group.zig +++ b/zig/tests/qwen35/group.zig @@ -1,4 +1,4 @@ -//! The tensor-parallel group of one test process: its options, the link to the other ranks and the RCCL bootstrap. +//! The tensor-parallel group of one test process: its options, and the group it joins through hip.joinGroup. const std = @import("std"); const hip = @import("hip"); @@ -35,29 +35,28 @@ pub const Group = struct { /// What a group of more than one rank holds besides the engine: close it after the engine. pub const Joined = struct { - rccl: ?hip.rccl.Rccl = null, - link: hip.link.Link = undefined, - id: ?hip.rccl.UniqueId = null, + gpa: std.mem.Allocator, + group: ?hip.collective.Group = null, world: usize = 1, /// What every rank runs under: rank 0's. policy: hip.Policy = .{}, pub fn close(j: *Joined) void { - if (j.world > 1) j.link.close(); - if (j.rccl) |*r| r.close(); + if (j.group) |g| g.close(j.gpa); + } + + /// The link to the other ranks (null: one rank). + pub fn link(j: *const Joined) ?hip.collective.Link { + return if (j.group) |g| g.link() else null; } }; - /// The unique id starts RCCL's bootstrap thread: the library stays loaded until the engine is gone. - pub fn join(g: Group, io: std.Io) !Joined { + /// Joins the other ranks (the group stays open until the engine is gone); one rank joins nothing. + pub fn join(g: Group, gpa: std.mem.Allocator, io: std.Io) !Joined { const found = try resolve(g.policy, @intCast(g.rank)); - var j: Joined = .{ .world = g.world, .policy = found.policy }; + var j: Joined = .{ .gpa = gpa, .world = g.world, .policy = found.policy }; if (g.world < 2) return j; - j.rccl = try hip.rccl.Rccl.open(j.policy.rccl_lib.slice()); - errdefer j.rccl.?.close(); - const pair = try hip.link.Link.open(io, g.rank, g.world, g.master, g.port, if (g.rank == 0) try j.rccl.?.uniqueId() else undefined, .{ .caps = hip.Device.groupId(found.caps), .policy = j.policy.words() }); - j.link, j.id, const hello = pair; - if (g.rank != 0) j.policy = hip.Policy.fromWords(hello.policy, j.policy); + j.group = try hip.joinGroup(gpa, io, @intCast(g.rank), @intCast(g.world), g.master, g.port, found.caps, &j.policy); return j; } @@ -67,7 +66,7 @@ pub const Group = struct { own.device = @intCast(g.rank); own.rank = g.rank; own.world = g.world; - own.id = j.id; + own.group = j.group; own.policy = j.policy; return qwen35.engine.Engine.open(gpa, io, dir, own); } @@ -90,5 +89,5 @@ pub fn resolve(flags: []const u8, device: c_int) !struct { policy: hip.Policy, c pub fn follow(gpa: std.mem.Allocator, e: *qwen35.engine.Engine, j: *const Group.Joined) !void { var w = try qwen35.worker.Worker.init(gpa, e); defer w.deinit(); - return w.follow(&j.link); + return w.follow(j.link().?); } diff --git a/zig/tests/qwen35/lanes_run.zig b/zig/tests/qwen35/lanes_run.zig index b9c55db482b..ebed98cd7ed 100644 --- a/zig/tests/qwen35/lanes_run.zig +++ b/zig/tests/qwen35/lanes_run.zig @@ -38,13 +38,13 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void job.sampling = s; } else return error.UnknownOption; } - var joined = try group.join(io); + var joined = try group.join(gpa, io); defer joined.close(); const e = try group.engine(gpa, io, args[0], joined, .{ .capacity = ids_file.longest(job.prompts) + 2 * max_tokens + 64, .prompt_rows = ids_file.longest(job.prompts) + 2 * max_tokens + 64, .streams = job.prompts.len, .batch_rows = @max(32, job.prompts.len * qwen35.hip_lanes.Hip.max_window) }); defer e.deinit(); if (group.rank > 0) return group_mod.follow(gpa, e, &joined); var s: Session = undefined; - try s.init(gpa, io, e, if (group.world > 1) &joined.link else null); + try s.init(gpa, io, e, joined.link()); defer s.deinit(); if (resume_to != null) s.h.keepPrompts(8, 1 << 30); const done = try s.run(arena, job); diff --git a/zig/tests/qwen35/lanes_session.zig b/zig/tests/qwen35/lanes_session.zig index 1953b7374bd..c80e98f42bd 100644 --- a/zig/tests/qwen35/lanes_session.zig +++ b/zig/tests/qwen35/lanes_session.zig @@ -17,7 +17,7 @@ pub const Session = struct { clock: lanes.backend.WallClock, /// Rank 0 of a group of `link`'s ranks (null: a lone rank) runs the core; the others follow it. - pub fn init(s: *Session, gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, link: ?*const hip.link.Link) !void { + pub fn init(s: *Session, gpa: std.mem.Allocator, io: std.Io, e: *qwen35.engine.Engine, link: ?hip.collective.Link) !void { const h = try Hip.init(gpa, e); errdefer h.deinit(); if (link) |l| h.withLink(l); diff --git a/zig/tests/qwen35/layers.zig b/zig/tests/qwen35/layers.zig index 57b1b88c962..236a318704c 100644 --- a/zig/tests/qwen35/layers.zig +++ b/zig/tests/qwen35/layers.zig @@ -59,23 +59,12 @@ pub fn run(g: Gpu, model_dir: []const u8, dir: []const u8, group: Group) !void { defer ctx.deinit(); // the oracle's sums are the reference kernels': the fixtures pin them whatever the environment says var notes: hip.Policy.Notes = .{}; - const policy = try hip.Policy.resolve("kernels=reference", .none, ¬es); - // the unique id starts RCCL's bootstrap thread: the library stays loaded to the end - var rccl: ?hip.rccl.Rccl = null; - defer if (rccl) |*r| r.close(); - var link: hip.link.Link = undefined; - var comm: hip.rccl.Comm = undefined; - if (group.world > 1) { - rccl = try hip.rccl.Rccl.open(policy.rccl_lib.slice()); - const pair = try hip.link.Link.open(g.io, group.rank, group.world, group.master, group.port, if (group.rank == 0) try rccl.?.uniqueId() else undefined, .{ .caps = hip.Device.groupId(try hip.Device.kernelCaps(@constCast(g.d), @intCast(group.rank))), .policy = policy.words() }); - link = pair[0]; - comm = try hip.rccl.Comm.init(&rccl.?, pair[1], group.rank, group.world); - } - defer if (group.world > 1) { - comm.deinit(); - link.close(); - }; + var policy = try hip.Policy.resolve("kernels=reference", .none, ¬es); const caps = try hip.Device.kernelCaps(@constCast(g.d), @intCast(group.rank)); + // the group stays open to the end: its communicator is the forward's + const joined: ?hip.collective.Group = if (group.world > 1) try hip.joinGroup(g.gpa, g.io, @intCast(group.rank), @intCast(group.world), group.master, group.port, caps, &policy) else null; + defer if (joined) |j| j.close(g.gpa); + const comm: ?hip.collective.Comm = if (joined) |j| try j.open() else null; var lib = try hip.Launcher.load(g.d, policy.choices(), hip.kernels.images); defer lib.unload(); const act: view.Kind = if (caps.act == .f16) .f16 else .bf16; @@ -84,7 +73,7 @@ pub fn run(g: Gpu, model_dir: []const u8, dir: []const u8, group: Group) !void { defer model.deinit(); const br = try qwen35.bridge.Bridge.init(g.gpa, g.d, &model, act); defer br.deinit(); - if (group.world > 1) br.model.tp = comm; + br.model.tp = comm; const m = &br.model; const s = m.spec; var stream = try hip.Stream.init(g.d); From 7f5fd5b4f9290ab06283868d01f8d4cf7950bdc2 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:33:01 +0200 Subject: [PATCH 20/52] build(hip): the HIP server's CLI module takes EXLR8's import, as main's server does since 1.0.8 --- zig/build/hip.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 1eb0e8c4e62..4d3a6233137 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -2,6 +2,7 @@ const std = @import("std"); const caps = @import("../src/hip/caps.zig"); +const exlr8_build = @import("exlr8.zig"); /// hip-host-test (part of `test`), hip-gpu-build and hip-gpu-test, hip-affine-build and hip-affine-test. pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, build_options: *std.Build.Step.Options, test_step: *std.Build.Step) void { @@ -152,7 +153,7 @@ fn server(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, build_opti .target = target, .optimize = .ReleaseSafe, .link_libc = true, - .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{.{ .name = "native_engines", .module = engines }} }) } }, + .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, e.hip.import_table.get("core").?) } }) } }, }) }); exe.root_module.addOptions("build_options", build_options); return exe; From badbb6fd3ecc29872baf189ef5b29201eea58270 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:39:55 +0200 Subject: [PATCH 21/52] feat(qwen3_5): structured output on HIP: the lane core's grammar masks each draw The engine now declares structures, so response_format and the guided_* fields reach it. The lane core's grammar (xgrammar) makes the masks; the backend only applies them: each verify row's allowed bits, and the first token through first_masked from the prompt's last row, kept for structured replies. A masked row is drawn on the host from the whole row with the disallowed tokens at -inf, by the same greedy and keyed draws. held() gives the grammar the MTP drafts as host tokens. --- .../qwen3_5/backend/hip/engine/draw.zig | 37 ++++++++++++++++++- .../qwen3_5/backend/hip/engine/hip_lanes.zig | 34 +++++++++++++++-- .../qwen3_5/backend/hip/engine/sample.zig | 32 ++++++++++++++++ zig/src/native/hip.zig | 2 +- 4 files changed, 99 insertions(+), 6 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/draw.zig b/zig/src/families/qwen3_5/backend/hip/engine/draw.zig index f9296b76194..d520e648891 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/draw.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/draw.zig @@ -8,8 +8,20 @@ const sample = @import("sample.zig"); /// Most candidates a row downloads; wider requests (top_k 0, or past this) download the row and draw on the host. pub const max_candidates = 512; -/// One row's draw: its sampling (null is greedy) and the position that keys it. -pub const Request = struct { sampling: ?lanes.Sampling, position: u64 }; +/// One row's draw: its sampling (null is greedy), the position that keys it, the grammar's allowed bits, a host copy. +pub const Request = struct { + sampling: ?lanes.Sampling, + position: u64, + /// Structured output: only tokens whose bit is set (empty: every token). + mask: []const u32 = &.{}, + /// The row's logits copied here (the prompt's last row, kept for a masked first draw). + keep: ?[]u16 = null, +}; + +/// Whether a row is drawn on the host from the whole row. +fn whole(r: Request) bool { + return r.mask.len > 0 or r.keep != null; +} fn greedy(s: ?lanes.Sampling) bool { return if (s) |x| x.temperature <= 0.0 else true; @@ -79,6 +91,7 @@ pub const Drawer = struct { var any_greedy = false; for (reqs, ks) |r, *k| { k.* = 0; + if (whole(r)) continue; if (greedy(r.sampling)) { any_greedy = true; } else { @@ -100,6 +113,10 @@ pub const Drawer = struct { try stream.synchronize(); const arg = view(i32, host[at.arg..][0 .. rows * 4]); for (reqs, 0..) |r, i| { + if (whole(r)) { + out[i] = try w.drawWhole(stream, logits, i, r); + continue; + } if (greedy(r.sampling)) { out[i] = @intCast(arg[i]); continue; @@ -124,4 +141,20 @@ pub const Drawer = struct { out[i] = @intCast(try lanes.sampling.choose(w.gpa, values[0..n], wide[0..n], r.position, s)); } } + + /// Row `i` downloaded whole: kept if asked, masked if asked, then drawn as an unmasked whole row is. + fn drawWhole(w: *Drawer, stream: hip.Stream, logits: hip.ops.Tensor, i: usize, r: Request) !u32 { + const bytes = w.vocab * 2; + try hip.runtime.check(w.d.api.hipMemcpyDtoHAsync(w.row.bytes.ptr, @ptrFromInt(logits.ptr + i * bytes), bytes, stream.handle)); + try stream.synchronize(); + const row = w.row.slice(u16)[0..w.vocab]; + if (r.keep) |k| @memcpy(k, row); + return w.drawHost(row, r); + } + + /// A host row's token per `r`: its mask applied in place, then greedy or the keyed draw. + pub fn drawHost(w: *const Drawer, row: []u16, r: Request) !u32 { + if (r.mask.len > 0) sample.mask(row, w.dtype, r.mask); + return sample.draw(w.gpa, row, w.dtype, r.sampling, r.position); + } }; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig index 9d12c053226..bed4ee92d07 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -40,6 +40,8 @@ pub const Lane = struct { fill: ?Fill = null, /// The last verify's slot and rows: kept whole unless keep drops some first. pending: ?struct { window: usize, rows: usize } = null, + /// A structured reply's prompt row, kept for its masked first draw (null for the others). + first_row: ?[]u16 = null, }; /// The engine this thread's HIP calls go to. @@ -155,6 +157,8 @@ pub const Hip = struct { .prefill = prefillFn, .prefill_step = prefillStepFn, .first = firstFn, + .first_masked = firstMaskedFn, + .held = heldTokensFn, .queue = queueFn, .read = readFn, .verify = verifyFn, @@ -195,6 +199,7 @@ pub const Hip = struct { h.e.drain(); l.caches.deinit(h.gpa); l.hidden.free(); + if (l.first_row) |row| h.gpa.free(row); h.gpa.destroy(l); } @@ -339,7 +344,10 @@ pub const Hip = struct { const to = prefix.chunkEnd(f.at, limit, if (h.decoding()) h.e.o.policy.fill_rows else prefix.chunk); if (h.link != null) try h.send(&.{ @backingInt(worker.Op.fill), lane.id, @intCast(to) }); if (to == prompt.len) { - _ = h.take(try h.e.prefill(&lane.caches, prompt, f.at, lane.hidden, .{ .sampling = sampling(s), .position = prompt.len }, null)); + // a structured reply keeps the prompt's last row: its first token is drawn again under the grammar + if (s.grammar != null and lane.first_row == null) lane.first_row = try h.gpa.alloc(u16, h.e.drawer.vocab); + const keep = if (s.grammar != null) lane.first_row else null; + _ = h.take(try h.e.prefill(&lane.caches, prompt, f.at, lane.hidden, .{ .sampling = sampling(s), .position = prompt.len, .keep = keep }, null)); lane.fill = null; return true; } @@ -362,6 +370,24 @@ pub const Hip = struct { return h.next - 1; } + /// The first token among the grammar's allowed ones, from the prompt row the pass kept. + fn firstMaskedFn(ptr: *anyopaque, s: *lanes.Stream, position: u64, bits: []const u32) anyerror!u64 { + const h = of(ptr); + if (position != s.prompt_len) return error.PositionMismatch; + const lane = h.lanes.get(s) orelse return error.UnknownStream; + const kept = lane.first_row orelse return error.StructuresUnsupported; + const row = try h.gpa.dupe(u16, kept); + defer h.gpa.free(row); + return h.take(try h.e.drawer.drawHost(row, .{ .sampling = sampling(s), .position = position, .mask = bits })); + } + + /// The drafts the head holds for the stream, as host tokens (a grammar walks them). + fn heldTokensFn(ptr: *anyopaque, s: *lanes.Stream, out: []u32) anyerror!void { + const lane = of(ptr).lanes.get(s) orelse return error.UnknownStream; + if (out.len > lane.held_n) return error.NoHeldDrafts; + @memcpy(out, lane.held[0..out.len]); + } + fn queueFn(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { _ = ptr; _ = s; @@ -412,8 +438,10 @@ pub const Hip = struct { var total: usize = 0; for (windows) |w| { if (total + w.positions.len > reqs.len) return error.WindowTooWide; - for (w.positions) |p| { - reqs[total] = .{ .sampling = sampling(w.stream), .position = p }; + // structured output: each row's allowed bits, rows x words + const words = if (w.masks.len > 0) w.masks.len / w.positions.len else 0; + for (w.positions, 0..) |p, r| { + reqs[total] = .{ .sampling = sampling(w.stream), .position = p, .mask = w.masks[r * words ..][0..words] }; total += 1; } } diff --git a/zig/src/families/qwen3_5/backend/hip/engine/sample.zig b/zig/src/families/qwen3_5/backend/hip/engine/sample.zig index 602d503555b..d0939841de2 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/sample.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/sample.zig @@ -31,6 +31,19 @@ pub fn argmax(row: []const u16, dtype: Dtype) u32 { return @intCast(best); } +/// Structured output: every token whose bit is clear in `bits` (32 a word, token i in word i / 32) becomes -inf. +pub fn mask(row: []u16, dtype: Dtype, bits: []const u32) void { + const minus_inf: u16 = switch (dtype) { + .f16 => 0xFC00, + .bf16 => 0xFF80, + }; + for (row, 0..) |*v, i| { + const word = i / 32; + const allowed = word < bits.len and (bits[word] >> @intCast(i % 32)) & 1 == 1; + if (!allowed) v.* = minus_inf; + } +} + const Candidate = struct { value: f32, id: u32 }; fn larger(_: void, a: Candidate, b: Candidate) bool { @@ -90,3 +103,22 @@ test "greedy draws the argmax" { const row = [_]u16{ 0x3c00, 0x4000, 0x3e00 }; try std.testing.expectEqual(@as(u32, 1), try draw(std.testing.allocator, &row, .f16, null, 0)); } + +test "a masked row draws only allowed tokens, greedy and sampled" { + const bf: u16 = 0x3f80; // 1.0 + const big: u16 = 0x4000; // 2.0 + var row = [_]u16{ big, bf, 0, bf, big }; + // tokens 1 and 3 allowed: the largest allowed is 1 (first of equals), not 0 or 4 + mask(&row, .bf16, &.{0b01010}); + try std.testing.expectEqual(@as(u32, 1), argmax(&row, .bf16)); + try std.testing.expectEqual(@as(u16, 0xFF80), row[0]); + const s: lanes.Sampling = .{ .seed = 3, .temperature = 1.0 }; + for (0..32) |p| { + const t = try draw(std.testing.allocator, &row, .bf16, s, p); + try std.testing.expect(t == 1 or t == 3); + } + // a mask shorter than the row disallows the rest + var tail = [_]u16{ bf, bf, big }; + mask(&tail, .f16, &.{}); + try std.testing.expectEqual(@as(u16, 0xFC00), tail[2]); +} diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index 72b4adb93c0..0ae934640a1 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -181,7 +181,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O h.clock = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.cfg, loaded.backend, h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = @intCast(loaded.streams), .context_window = @intCast(r.options.window), .prefill_step = F.prefill_step, .policy = h.policy_line, .startup = loaded.startup }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = @intCast(loaded.streams), .context_window = @intCast(r.options.window), .prefill_step = F.prefill_step, .policy = h.policy_line, .startup = loaded.startup, .structures = true }); h.host.memory = .{ .read = readMemory }; try h.host.start(); served = true; From 13961db23d0f5aa2f4cf195654db5829ad18c7ae Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Sun, 11 Oct 2026 06:58:26 +0200 Subject: [PATCH 22/52] feat(hip): tensor parallelism over RCCL, behind hip/collective.zig comm/rccl.zig opens RCCL at run time (librccl.so.1, or the policy's rccl_lib first) and runs all-reduce, all-gather and broadcast on the engine's streams; comm/link.zig is the ranks' TCP link (rank 0 listens, sends the communicator's id and its policy; a rank whose GPU differs is refused) and carries rank 0's steps; comm/group.zig joins the two into a collective.Group, and hip.joinGroup is its join. The server lists --tp again (1, 2, 4 or 8 ranks, --rank, --master, --master-port), and tf-qwen35-test's --tp checks run. RCCL's and HIP's threads do not start under Zig's per-thread alternate signal stack: the HIP build's native module sets std_options without it, which the server root takes through the backend's std options (its own commit, server/std_options.zig). --- zig/src/hip/comm/group.zig | 92 +++++++++++++++++++++++++ zig/src/hip/comm/link.zig | 136 +++++++++++++++++++++++++++++++++++++ zig/src/hip/comm/rccl.zig | 125 ++++++++++++++++++++++++++++++++++ zig/src/hip/policy.zig | 23 ++++++- zig/src/hip/root.zig | 7 +- zig/src/native/hip.zig | 4 +- 6 files changed, 382 insertions(+), 5 deletions(-) create mode 100644 zig/src/hip/comm/group.zig create mode 100644 zig/src/hip/comm/link.zig create mode 100644 zig/src/hip/comm/rccl.zig diff --git a/zig/src/hip/comm/group.zig b/zig/src/hip/comm/group.zig new file mode 100644 index 00000000000..d5c0bbac5f4 --- /dev/null +++ b/zig/src/hip/comm/group.zig @@ -0,0 +1,92 @@ +//! A tensor-parallel group over RCCL: the TCP link that carries rank 0's steps and RCCL's id, behind collective.zig. + +const std = @import("std"); +const collective = @import("../collective.zig"); +const rccl_mod = @import("rccl.zig"); +const link_mod = @import("link.zig"); +const Caps = @import("../caps.zig").Caps; +const Policy = @import("../policy.zig").Policy; +const Device = @import("../device.zig").Device; + +/// RCCL's library stays loaded until the group is closed (its bootstrap thread starts at the id). +const Joined = struct { + rccl: rccl_mod.Rccl, + link: link_mod.Link, + id: rccl_mod.UniqueId, + rank: usize, + world: usize, + comm: ?rccl_mod.Comm = null, +}; + +/// Rank 0 listens on `master`:`port`, sends its id and policy; a rank whose GPU differs from rank 0's is refused. +pub fn join(gpa: std.mem.Allocator, io: std.Io, rank: u32, world: u32, master: []const u8, port: u16, caps: Caps, policy: *Policy) collective.JoinError!collective.Group { + const g = try gpa.create(Joined); + errdefer gpa.destroy(g); + g.rccl = rccl_mod.Rccl.open(policy.rccl_lib.slice()) catch return error.NoRccl; + errdefer g.rccl.close(); + const mine: rccl_mod.UniqueId = if (rank == 0) g.rccl.uniqueId() catch return error.NoId else undefined; + const host = if (std.mem.eql(u8, master, "localhost")) "127.0.0.1" else master; + const pair = try link_mod.Link.open(io, rank, world, host, port, mine, .{ .caps = Device.groupId(caps), .policy = policy.words() }); + g.link, g.id, const hello = pair; + g.rank = rank; + g.world = world; + g.comm = null; + if (rank != 0) policy.* = Policy.fromWords(hello.policy, policy.*); + return .{ .ptr = g, .vtable = &group_vtable, .rank = rank, .world = world }; +} + +fn of(ptr: *anyopaque) *Joined { + return @ptrCast(@alignCast(ptr)); +} + +const group_vtable: collective.Group.VTable = .{ .link = linkOf, .open = open, .close = close }; +const link_vtable: collective.Link.VTable = .{ .send = send, .recv = recv }; +const comm_vtable: collective.Comm.VTable = .{ .all_reduce = allReduce, .all_gather = allGather, .broadcast = broadcast, .close = closeComm }; + +fn linkOf(ptr: *anyopaque) collective.Link { + return .{ .ptr = &of(ptr).link, .vtable = &link_vtable }; +} + +/// The rank's communicator, opened once: ncclCommInitRank blocks until every rank has called it. +fn open(ptr: *anyopaque) collective.Error!collective.Comm { + const g = of(ptr); + if (g.comm == null) g.comm = rccl_mod.Comm.init(&g.rccl, g.id, g.rank, g.world) catch return error.CollectiveFailed; + return .{ .ptr = &g.comm.?, .vtable = &comm_vtable, .rank = g.rank, .world = g.world }; +} + +fn close(ptr: *anyopaque, gpa: std.mem.Allocator) void { + const g = of(ptr); + if (g.comm) |*c| c.deinit(); + g.link.close(); + g.rccl.close(); + gpa.destroy(g); +} + +fn send(ptr: *anyopaque, words: []const u32) collective.LinkError!void { + const l: *const link_mod.Link = @ptrCast(@alignCast(ptr)); + l.send(words) catch return error.LinkFailed; +} + +fn recv(ptr: *anyopaque, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) collective.LinkError!void { + const l: *const link_mod.Link = @ptrCast(@alignCast(ptr)); + l.recv(gpa, out) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.LinkFailed; +} + +fn comm(ptr: *anyopaque) *rccl_mod.Comm { + return @ptrCast(@alignCast(ptr)); +} + +fn allReduce(ptr: *anyopaque, s: u64, r: u64, n: usize, dtype: collective.Dtype, stream: @import("../abi.zig").Stream) collective.Error!void { + comm(ptr).allReduce(s, r, n, dtype, stream) catch return error.CollectiveFailed; +} + +fn allGather(ptr: *anyopaque, s: u64, r: u64, n: usize, dtype: collective.Dtype, stream: @import("../abi.zig").Stream) collective.Error!void { + comm(ptr).allGather(s, r, n, dtype, stream) catch return error.CollectiveFailed; +} + +fn broadcast(ptr: *anyopaque, s: u64, r: u64, n: usize, dtype: collective.Dtype, root: usize, stream: @import("../abi.zig").Stream) collective.Error!void { + comm(ptr).broadcast(s, r, n, dtype, root, stream) catch return error.CollectiveFailed; +} + +/// The communicator lives with the group; the group's close destroys it. +fn closeComm(_: *anyopaque) void {} diff --git a/zig/src/hip/comm/link.zig b/zig/src/hip/comm/link.zig new file mode 100644 index 00000000000..0ec403f56b5 --- /dev/null +++ b/zig/src/hip/comm/link.zig @@ -0,0 +1,136 @@ +//! The ranks' TCP link: rank 0 listens, the others connect once, get the communicator's id, take rank 0's commands. + +const std = @import("std"); +const posix = std.posix; +const rccl = @import("rccl.zig"); +const Policy = @import("../policy.zig").Policy; + +pub const Error = error{ SocketFailed, BindFailed, ConnectFailed, LinkClosed, BadRank, MixedGpus } || std.mem.Allocator.Error; + +pub const max_world = 16; + +/// What the ranks agree on at join: the kernels' GPU id (every rank's must match) and rank 0's policy. +pub const Hello = struct { caps: u32, policy: [Policy.word_count]u32 }; + +pub const Link = struct { + rank: usize, + world: usize, + /// Rank 0: the follower of rank r + 1 at index r. A follower: rank 0's socket at index 0. + fds: [max_world - 1]posix.socket_t = undefined, + + /// Rank 0 listens on `host:port`, sends each rank `id` and `hello`; a GPU that differs from rank 0's is refused. + pub fn open(io: std.Io, rank: usize, world: usize, host: []const u8, port: u16, id: rccl.UniqueId, hello: Hello) Error!struct { Link, rccl.UniqueId, Hello } { + if (world < 2 or world > max_world or rank >= world) return error.BadRank; + const ip = std.Io.net.IpAddress.parse(host, port) catch return error.ConnectFailed; + if (ip != .ip4) return error.ConnectFailed; + var addr: posix.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port), .addr = std.mem.readInt(u32, &ip.ip4.bytes, .little) }; + var link: Link = .{ .rank = rank, .world = world }; + if (rank == 0) { + const server = try socket(); + defer _ = posix.system.close(server); + const one: c_int = 1; + posix.setsockopt(server, posix.SOL.SOCKET, posix.SO.REUSEADDR, std.mem.asBytes(&one)) catch return error.SocketFailed; + if (posix.errno(posix.system.bind(server, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) != .SUCCESS) return error.BindFailed; + if (posix.errno(posix.system.listen(server, 16)) != .SUCCESS) return error.BindFailed; + var seen: usize = 0; + while (seen < world - 1) : (seen += 1) { + const rc = posix.system.accept(server, null, null); + if (posix.errno(rc) != .SUCCESS) return error.SocketFailed; + const fd: posix.socket_t = @intCast(rc); + var peer: u32 = undefined; + try readAll(fd, std.mem.asBytes(&peer)); + var caps: u32 = undefined; + try readAll(fd, std.mem.asBytes(&caps)); + if (peer == 0 or peer >= world) return error.BadRank; + link.fds[peer - 1] = fd; + const status: u32 = if (caps == hello.caps) 0 else 1; + try writeAll(fd, std.mem.asBytes(&status)); + if (status != 0) return error.MixedGpus; + try writeAll(fd, std.mem.asBytes(&id)); + try writeAll(fd, std.mem.sliceAsBytes(&hello.policy)); + } + return .{ link, id, hello }; + } + var tries: usize = 0; + while (true) : (tries += 1) { + const fd = try socket(); + if (posix.errno(posix.system.connect(fd, @ptrCast(&addr), @sizeOf(posix.sockaddr.in))) == .SUCCESS) { + link.fds[0] = fd; + break; + } + _ = posix.system.close(fd); + if (tries >= 6000) return error.ConnectFailed; + std.Io.sleep(io, .fromMilliseconds(100), .awake) catch {}; + } + const mine: u32 = @intCast(rank); + try writeAll(link.fds[0], std.mem.asBytes(&mine)); + try writeAll(link.fds[0], std.mem.asBytes(&hello.caps)); + var status: u32 = undefined; + try readAll(link.fds[0], std.mem.asBytes(&status)); + if (status != 0) return error.MixedGpus; + var got: rccl.UniqueId = undefined; + try readAll(link.fds[0], std.mem.asBytes(&got)); + var theirs: Hello = .{ .caps = hello.caps, .policy = undefined }; + try readAll(link.fds[0], std.mem.sliceAsBytes(&theirs.policy)); + return .{ link, got, theirs }; + } + + pub fn close(l: *Link) void { + const n = if (l.rank == 0) l.world - 1 else 1; + for (l.fds[0..n]) |fd| _ = posix.system.close(fd); + } + + /// Rank 0: `words` to every follower, behind their count. + pub fn send(l: *const Link, words: []const u32) Error!void { + const n: u32 = @intCast(words.len); + for (l.fds[0 .. l.world - 1]) |fd| { + try writeAll(fd, std.mem.asBytes(&n)); + try writeAll(fd, std.mem.sliceAsBytes(words)); + } + } + + /// A follower: rank 0's next message, appended to `out` (cleared first). + pub fn recv(l: *const Link, gpa: std.mem.Allocator, out: *std.ArrayList(u32)) Error!void { + var n: u32 = undefined; + try readAll(l.fds[0], std.mem.asBytes(&n)); + out.clearRetainingCapacity(); + try out.resize(gpa, n); + try readAll(l.fds[0], std.mem.sliceAsBytes(out.items)); + } +}; + +fn socket() Error!posix.socket_t { + const rc = posix.system.socket(posix.AF.INET, posix.SOCK.STREAM, 0); + if (posix.errno(rc) != .SUCCESS) return error.SocketFailed; + const fd: posix.socket_t = @intCast(rc); + const one: c_int = 1; + posix.setsockopt(fd, posix.IPPROTO.TCP, posix.TCP.NODELAY, std.mem.asBytes(&one)) catch {}; + return fd; +} + +fn writeAll(fd: posix.socket_t, bytes: []const u8) Error!void { + var at: usize = 0; + while (at < bytes.len) { + const rc = posix.system.write(fd, bytes[at..].ptr, bytes.len - at); + switch (posix.errno(rc)) { + .SUCCESS => at += @intCast(rc), + .INTR => {}, + else => return error.LinkClosed, + } + } +} + +fn readAll(fd: posix.socket_t, bytes: []u8) Error!void { + var at: usize = 0; + while (at < bytes.len) { + const rc = posix.system.read(fd, bytes[at..].ptr, bytes.len - at); + switch (posix.errno(rc)) { + .SUCCESS => { + if (rc == 0) return error.LinkClosed; + at += @intCast(rc); + }, + .INTR => {}, + else => return error.LinkClosed, + } + } +} diff --git a/zig/src/hip/comm/rccl.zig b/zig/src/hip/comm/rccl.zig new file mode 100644 index 00000000000..467549903d1 --- /dev/null +++ b/zig/src/hip/comm/rccl.zig @@ -0,0 +1,125 @@ +//! RCCL opened at run time: the tensor-parallel forward's collectives on our streams, as hand-declared exports. + +const std = @import("std"); +const abi = @import("../abi.zig"); + +pub const Error = error{ RcclUnavailable, MissingSymbol, RcclFailed, Invalid }; + +/// ncclUniqueId: the opaque 128 bytes rank 0 makes and every rank passes to its init. +pub const UniqueId = extern struct { internal: [128]u8 }; + +/// ncclDataType_t: collective.zig's numbering is RCCL's. +pub const Dtype = @import("../collective.zig").Dtype; + +const Handle = ?*anyopaque; +const C = ?*const anyopaque; +const P = ?*anyopaque; + +/// Each field is the library's exact export. +const Api = struct { + ncclGetErrorString: *const fn (c_int) callconv(.c) [*:0]const u8, + ncclGetUniqueId: *const fn (*UniqueId) callconv(.c) c_int, + ncclCommInitRank: *const fn (*Handle, c_int, UniqueId, c_int) callconv(.c) c_int, + ncclCommDestroy: *const fn (Handle) callconv(.c) c_int, + ncclAllReduce: *const fn (C, P, usize, c_int, c_int, Handle, abi.Stream) callconv(.c) c_int, + ncclAllGather: *const fn (C, P, usize, c_int, Handle, abi.Stream) callconv(.c) c_int, + ncclBroadcast: *const fn (C, P, usize, c_int, c_int, Handle, abi.Stream) callconv(.c) c_int, +}; + +const paths = [_][]const u8{ "librccl.so.1", "librccl.so", "/opt/rocm/lib/librccl.so.1" }; + +/// ncclSum: the only reduction the forward uses. +const sum_op: c_int = 0; + +pub const Rccl = struct { + lib: std.DynLib, + api: Api, + + /// `first` (the policy's `rccl_lib`) is tried before the usual places. + pub fn open(first: ?[]const u8) Error!Rccl { + var candidates: [paths.len + 1][]const u8 = undefined; + var n: usize = 0; + if (first) |path| { + candidates[0] = path; + n = 1; + } + for (paths) |path| { + candidates[n] = path; + n += 1; + } + for (candidates[0..n]) |path| { + var lib = std.DynLib.open(path) catch continue; + errdefer lib.close(); + var api: Api = undefined; + const info = @typeInfo(Api).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + @field(api, name) = lib.lookup(T, name) orelse { + std.log.err("{s} has no {s}", .{ path, name }); + return error.MissingSymbol; + }; + } + return .{ .lib = lib, .api = api }; + } + return error.RcclUnavailable; + } + + pub fn close(r: *Rccl) void { + r.lib.close(); + } + + fn check(r: *const Rccl, code: c_int, what: []const u8) Error!void { + if (code == 0) return; + std.log.err("{s}: RCCL error {d}: {s}", .{ what, code, std.mem.span(r.api.ncclGetErrorString(code)) }); + return error.RcclFailed; + } + + /// A fresh id; rank 0 makes it and hands it to the others. + pub fn uniqueId(r: *const Rccl) Error!UniqueId { + var id: UniqueId = undefined; + try r.check(r.api.ncclGetUniqueId(&id), "ncclGetUniqueId"); + return id; + } +}; + +/// One rank's communicator. Collectives queue on the stream they are given and wait for every rank's matching call. +pub const Comm = struct { + rccl: *const Rccl, + handle: Handle, + rank: usize, + world: usize, + + /// Joins the ranks; blocks until all `world` have called it with the same `id`. The device is current already. + pub fn init(rccl: *const Rccl, id: UniqueId, rank: usize, world: usize) Error!Comm { + if (world < 2 or rank >= world) return error.Invalid; + var h: Handle = null; + try rccl.check(rccl.api.ncclCommInitRank(&h, @intCast(world), id, @intCast(rank)), "ncclCommInitRank"); + return .{ .rccl = rccl, .handle = h, .rank = rank, .world = world }; + } + + pub fn deinit(c: *Comm) void { + _ = c.rccl.api.ncclCommDestroy(c.handle); + c.* = undefined; + } + + /// `recv` = the ranks' `send` summed, `n` values of `dtype` (sum of two ranks is the one add, any order). + pub fn allReduce(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + if (stream == @import("../launches/util.zig").counting) return; + try c.rccl.check(c.rccl.api.ncclAllReduce(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), sum_op, c.handle, stream), "ncclAllReduce"); + } + + /// `recv` (world * n values) = every rank's `send` (n values) in rank order. + pub fn allGather(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, stream: abi.Stream) Error!void { + if (stream == @import("../launches/util.zig").counting) return; + try c.rccl.check(c.rccl.api.ncclAllGather(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), c.handle, stream), "ncclAllGather"); + } + + /// `root`'s `send` into every rank's `recv`, `n` values. + pub fn broadcast(c: Comm, send: u64, recv: u64, n: usize, dtype: Dtype, root: usize, stream: abi.Stream) Error!void { + if (stream == @import("../launches/util.zig").counting) return; + try c.rccl.check(c.rccl.api.ncclBroadcast(@ptrFromInt(send), @ptrFromInt(recv), n, @backingInt(dtype), @intCast(root), c.handle, stream), "ncclBroadcast"); + } +}; + +test "the unique id is the 128 bytes RCCL passes by value" { + try std.testing.expectEqual(@as(usize, 128), @sizeOf(UniqueId)); +} diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index 30c9a2c1835..a94dfe10491 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -13,6 +13,22 @@ pub const Pick = enum { auto, reference }; /// MTP drafting: `--mtp-drafts` and `--mtp-confidence`. pub const Mtp = struct { drafts: u8 = 3, confidence: f64 = 0.3 }; +/// A path a rank reads locally (it never travels with the policy). +pub const Path = struct { + buf: [160]u8 = @splat(0), + + pub fn slice(p: *const Path) ?[]const u8 { + const n = std.mem.indexOfScalar(u8, &p.buf, 0) orelse p.buf.len; + return if (n == 0) null else p.buf[0..n]; + } + + fn set(p: *Path, text: []const u8) error{BadValue}!void { + if (text.len >= p.buf.len) return error.BadValue; + p.buf = @splat(0); + @memcpy(p.buf[0..text.len], text); + } +}; + pub const Policy = struct { matrix: Choice = .auto, attention: Attention = .auto, @@ -32,6 +48,8 @@ pub const Policy = struct { slots: u32 = 8, /// Rank whose graph capture fails on purpose, for the tests of the fallback (-1: none). Local to a rank. graph_fail: i32 = -1, + /// The RCCL library to load first. Local to a rank. + rccl_lib: Path = .{}, pub const Error = error{ UnknownKey, BadValue, StepNotAligned }; @@ -100,7 +118,7 @@ pub const Policy = struct { p.fill_rows = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; } else if (eql(u8, key, "graph_fail")) { p.graph_fail = std.fmt.parseInt(i32, value, 10) catch return error.BadValue; - } else return error.UnknownKey; + } else if (eql(u8, key, "rccl_lib")) try p.rccl_lib.set(value) else return error.UnknownKey; } fn parseEnum(comptime E: type, value: []const u8) Error!E { @@ -115,6 +133,7 @@ pub const Policy = struct { if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); if (p.gdn != .auto) try w.print(",gdn={t}", .{p.gdn}); if (p.graph_fail >= 0) try w.print(",graph_fail={d}", .{p.graph_fail}); + if (p.rccl_lib.slice()) |path| try w.print(",rccl_lib={s}", .{path}); try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); } @@ -132,7 +151,7 @@ pub const Policy = struct { return .{ nibbles[0], nibbles[1] | @as(u32, p.mtp.drafts) << 24, p.prefill_step, @truncate(conf), @intCast(conf >> 32), p.slots, p.fill_rows }; } - /// `local` with every field rank 0 sent; a rank keeps its own graph fault. + /// `local` with every field rank 0 sent; a rank keeps its own graph fault and library path. pub fn fromWords(w: [word_count]u32, local: Policy) Policy { var p = local; var vals: [8]u32 = undefined; diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index b9d896102a3..66335e2eb1d 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -34,12 +34,15 @@ pub const Upload = @import("upload.zig").Upload; pub const quant = @import("core").quant; pub const registry = @import("core").registry; pub const collective = @import("collective.zig"); -/// Joins this rank's tensor-parallel group; this build has no collectives backend, so one rank only. -pub const joinGroup = collective.noGroup; +/// Joins this rank's tensor-parallel group: RCCL's (comm/), behind collective.zig. +pub const joinGroup = @import("comm/group.zig").join; test { _ = policy; _ = admission; _ = Device; _ = collective; + _ = @import("comm/rccl.zig"); + _ = @import("comm/link.zig"); + _ = @import("comm/group.zig"); } diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index 72b4adb93c0..763d82e881c 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -13,8 +13,10 @@ const modelContext = admission.modelContext; const registry = .{ qwen35.native, qwen35.native_moe }; pub const backends: []const []const u8 = &.{"hip"}; +/// No per-thread alternate signal stack: its thread-local leaves RCCL's and HIP's threads too little stack to start. +pub const std_options: std.Options = .{ .signal_stack_size = null }; /// The serve flags past the common ones this backend takes (server/cli.zig lists and parses them). -pub const serves: []const []const u8 = &.{ "--policy", "--mtp-drafts", "--mtp-confidence", "--checkpoint-slots", "--backend=rocm" }; +pub const serves: []const []const u8 = &.{ "--tp", "--policy", "--mtp-drafts", "--mtp-confidence", "--checkpoint-slots", "--backend=rocm" }; pub const families: []const api.Family = blk: { var out: [registry.len]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats }; From ba0bc3c2071181b72ba73619ff09db984221629f Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 06:50:29 +0200 Subject: [PATCH 23/52] feat(hip): the graph cache by shape in the hip module, for every HIP family --- zig/src/families/qwen3_5/backend/hip/engine/mtp.zig | 2 +- .../qwen3_5/backend/hip/engine/round_graphs.zig | 2 +- .../backend/hip/engine => hip}/graph_cache.zig | 13 +++++++------ zig/src/hip/root.zig | 1 + 4 files changed, 10 insertions(+), 8 deletions(-) rename zig/src/{families/qwen3_5/backend/hip/engine => hip}/graph_cache.zig (87%) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig index 605d9bfaa84..2dcd8caeba6 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig @@ -9,7 +9,7 @@ const bridge = @import("../model/bridge.zig"); const fwd = @import("../forward/forward.zig"); const draw = @import("draw.zig"); const plan = @import("../forward/plan.zig"); -const graph_cache = @import("graph_cache.zig"); +const graph_cache = hip.graph_cache; const pops = hip.plan_ops; const Ops = hip.ops.Ops; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig index 4228302d0bf..d42ed86ed93 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig @@ -2,7 +2,7 @@ const hip = @import("hip"); const plan = @import("../forward/plan.zig"); -const graph_cache = @import("graph_cache.zig"); +const graph_cache = hip.graph_cache; /// What a replay hands back: the forward's outputs and where the arena stands after it. pub const Out = struct { hidden: hip.ops.Tensor, y: hip.ops.Tensor, used: usize }; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig b/zig/src/hip/graph_cache.zig similarity index 87% rename from zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig rename to zig/src/hip/graph_cache.zig index 9d46c078663..8b9be16aa07 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/graph_cache.zig +++ b/zig/src/hip/graph_cache.zig @@ -1,7 +1,8 @@ //! Captured graphs by shape: a launch sequence recorded the second time its shape is met, replayed on every later one. const std = @import("std"); -const hip = @import("hip"); +const hip_graph = @import("graph.zig"); +const Stream = @import("stream.zig").Stream; /// Shapes kept at once; the least recently used one is dropped for a new one. const max_entries = 64; @@ -16,7 +17,7 @@ pub fn Cache(comptime Key: type, comptime Out: type) type { pub const Entry = struct { key: Key, state: State = .seen, - exec: ?hip.graph.Exec = null, + exec: ?hip_graph.Exec = null, out: Out = undefined, tick: u64 = 0, }; @@ -69,10 +70,10 @@ pub fn Cache(comptime Key: type, comptime Out: type) type { } /// `body(ctx)` recorded on `stream`: its outputs and the graph (nothing ran), or null when the capture failed. - pub fn record(stream: hip.Stream, ctx: anytype, comptime body: fn (@TypeOf(ctx)) anyerror!Out) !?struct { out: Out, graph: hip.graph.Graph } { - hip.graph.beginCapture(stream, .thread_local) catch return null; + pub fn record(stream: Stream, ctx: anytype, comptime body: fn (@TypeOf(ctx)) anyerror!Out) !?struct { out: Out, graph: hip_graph.Graph } { + hip_graph.beginCapture(stream, .thread_local) catch return null; const recorded = body(ctx); - const graph = hip.graph.endCapture(stream) catch return null; + const graph = hip_graph.endCapture(stream) catch return null; const out = recorded catch |err| { var g = graph; g.deinit(); @@ -82,7 +83,7 @@ pub fn Cache(comptime Key: type, comptime Out: type) type { } /// Instantiates a capture that just ended, keeps it with its outputs, and uploads it. - pub fn keep(g: *Self, e: *Entry, graph: hip.graph.Graph, stream: hip.Stream, out: Out) !void { + pub fn keep(g: *Self, e: *Entry, graph: hip_graph.Graph, stream: Stream, out: Out) !void { var tmp = graph; defer tmp.deinit(); errdefer e.state = .failed; diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index 66335e2eb1d..d3ef4888e0c 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -15,6 +15,7 @@ pub const Module = @import("module.zig").Module; pub const Function = @import("module.zig").Function; pub const launch = @import("launch.zig"); pub const graph = @import("graph.zig"); +pub const graph_cache = @import("graph_cache.zig"); pub const Arena = @import("arena.zig").Arena; pub const caps = @import("caps.zig"); pub const Caps = caps.Caps; From 905d9e971c5e0fe321181ecfd61043ca68166ab8 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:36:38 +0200 Subject: [PATCH 24/52] feat(hip): a step recorded as graphs cut at its collectives, the collectives issued between replays --- zig/src/hip/graph_split.zig | 137 +++++++++++++++++++++++ zig/src/hip/kernel_tests.zig | 1 + zig/src/hip/kernel_tests/graph_split.zig | 77 +++++++++++++ zig/src/hip/root.zig | 1 + 4 files changed, 216 insertions(+) create mode 100644 zig/src/hip/graph_split.zig create mode 100644 zig/src/hip/kernel_tests/graph_split.zig diff --git a/zig/src/hip/graph_split.zig b/zig/src/hip/graph_split.zig new file mode 100644 index 00000000000..c1a154344e5 --- /dev/null +++ b/zig/src/hip/graph_split.zig @@ -0,0 +1,137 @@ +//! A step recorded as graphs cut at its collectives: the collectives run between the graphs' replays, never inside one. +const std = @import("std"); +const abi = @import("abi.zig"); +const graph = @import("graph.zig"); +const collective = @import("collective.zig"); +const Stream = @import("stream.zig").Stream; + +/// One collective of a step, with the buffers it was recorded with (the graphs' addresses stay fixed too). +pub const Call = struct { + what: enum { all_reduce, all_gather, broadcast }, + send: u64, + recv: u64, + n: usize, + dtype: collective.Dtype, + root: usize = 0, + + fn issue(c: Call, comm: collective.Comm, stream: abi.Stream) collective.Error!void { + switch (c.what) { + .all_reduce => try comm.allReduce(c.send, c.recv, c.n, c.dtype, stream), + .all_gather => try comm.allGather(c.send, c.recv, c.n, c.dtype, stream), + .broadcast => try comm.broadcast(c.send, c.recv, c.n, c.dtype, c.root, stream), + } + } +}; + +pub const Piece = union(enum) { graph: graph.Exec, call: Call }; + +/// A recorded step: its graphs and collectives in order, replayed on the stream it was recorded on. +pub const Split = struct { + gpa: std.mem.Allocator, + pieces: []Piece, + comm: ?collective.Comm, + + pub fn deinit(s: *Split) void { + for (s.pieces) |*p| switch (p.*) { + .graph => |*x| x.deinit(), + .call => {}, + }; + s.gpa.free(s.pieces); + s.* = undefined; + } + + pub fn launchOn(s: Split, stream: Stream) !void { + for (s.pieces) |p| switch (p) { + .graph => |x| try x.launchOn(stream), + .call => |c| try c.issue(s.comm orelse return error.CollectiveFailed, stream.handle), + }; + } +}; + +/// Records a step from `begin` to `finish`: launches go into graphs, cut wherever a collective goes through `comm()`. +pub const Recorder = struct { + gpa: std.mem.Allocator, + stream: Stream, + /// The step's communicator (null: one rank, no collectives). + inner: ?collective.Comm, + pieces: std.ArrayList(Piece) = .empty, + /// A cut failed: the step is not kept and its launches must run eagerly. + failed: bool = false, + capturing: bool = false, + + const vtable: collective.Comm.VTable = .{ .all_reduce = allReduce, .all_gather = allGather, .broadcast = broadcast, .close = close }; + + pub fn begin(r: *Recorder) !void { + try graph.beginCapture(r.stream, .thread_local); + r.capturing = true; + } + + /// The communicator the step uses while it records: each call ends a graph and starts the next. + pub fn comm(r: *Recorder) ?collective.Comm { + const c = r.inner orelse return null; + return .{ .ptr = r, .vtable = &vtable, .rank = c.rank, .world = c.world }; + } + + /// The recorded step, or null when a cut failed; the recorder is empty after either. + pub fn finish(r: *Recorder) !?Split { + if (!r.failed) r.closePiece() catch { + r.failed = true; + }; + if (r.capturing) { + if (graph.endCapture(r.stream)) |g| { + var x = g; + x.deinit(); + } else |_| {} + r.capturing = false; + } + if (r.failed) { + for (r.pieces.items) |*p| if (p.* == .graph) p.graph.deinit(); + r.pieces.deinit(r.gpa); + r.pieces = .empty; + return null; + } + const pieces = try r.pieces.toOwnedSlice(r.gpa); + return .{ .gpa = r.gpa, .pieces = pieces, .comm = r.inner }; + } + + fn closePiece(r: *Recorder) !void { + var g = try graph.endCapture(r.stream); + r.capturing = false; + defer g.deinit(); + var x = try g.instantiate(); + errdefer x.deinit(); + try x.upload(r.stream); + try r.pieces.append(r.gpa, .{ .graph = x }); + } + + fn cut(ptr: *anyopaque, call: Call) collective.Error!void { + const r: *Recorder = @ptrCast(@alignCast(ptr)); + if (r.failed) return error.CollectiveFailed; + r.closePiece() catch { + r.failed = true; + return error.CollectiveFailed; + }; + r.pieces.append(r.gpa, .{ .call = call }) catch { + r.failed = true; + return error.CollectiveFailed; + }; + r.begin() catch { + r.failed = true; + return error.CollectiveFailed; + }; + } + + fn allReduce(ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: collective.Dtype, _: abi.Stream) collective.Error!void { + return cut(ptr, .{ .what = .all_reduce, .send = send, .recv = recv, .n = n, .dtype = dtype }); + } + + fn allGather(ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: collective.Dtype, _: abi.Stream) collective.Error!void { + return cut(ptr, .{ .what = .all_gather, .send = send, .recv = recv, .n = n, .dtype = dtype }); + } + + fn broadcast(ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: collective.Dtype, root: usize, _: abi.Stream) collective.Error!void { + return cut(ptr, .{ .what = .broadcast, .send = send, .recv = recv, .n = n, .dtype = dtype, .root = root }); + } + + fn close(_: *anyopaque) void {} +}; diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 94641edc08e..73b676b975d 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -26,4 +26,5 @@ test { _ = @import("kernel_tests/tp.zig"); _ = @import("kernel_tests/affine/affine.zig"); _ = @import("kernel_tests/affine/rows.zig"); + _ = @import("kernel_tests/graph_split.zig"); } diff --git a/zig/src/hip/kernel_tests/graph_split.zig b/zig/src/hip/kernel_tests/graph_split.zig new file mode 100644 index 00000000000..ef8da790a3f --- /dev/null +++ b/zig/src/hip/kernel_tests/graph_split.zig @@ -0,0 +1,77 @@ +//! A step recorded as graphs cut at its collectives, replayed with new inputs: the collectives run between the graphs. +const std = @import("std"); +const rig = @import("rig.zig"); +const collective = @import("../collective.zig"); +const split = @import("../graph_split.zig"); +const abi = @import("../abi.zig"); +const runtime = @import("../runtime.zig"); + +/// One rank's "all-gather": a copy of `send` into `recv` on the stream, counted. +const Copy = struct { + r: *const runtime.Runtime, + calls: usize = 0, + + const vtable: collective.Comm.VTable = .{ .all_reduce = never, .all_gather = gather, .broadcast = never2, .close = close }; + + fn gather(ptr: *anyopaque, send: u64, recv: u64, n: usize, dtype: collective.Dtype, s: abi.Stream) collective.Error!void { + const c: *Copy = @ptrCast(@alignCast(ptr)); + if (dtype != .f32) return error.CollectiveFailed; + c.calls += 1; + runtime.check(c.r.api.hipMemcpyDtoDAsync(@ptrFromInt(recv), @ptrFromInt(send), 4 * n, s)) catch return error.CollectiveFailed; + } + + fn never(_: *anyopaque, _: u64, _: u64, _: usize, _: collective.Dtype, _: abi.Stream) collective.Error!void { + return error.CollectiveFailed; + } + + fn never2(_: *anyopaque, _: u64, _: u64, _: usize, _: collective.Dtype, _: usize, _: abi.Stream) collective.Error!void { + return error.CollectiveFailed; + } + + fn close(_: *anyopaque) void {} +}; + +test "a step cut at its collective: nothing runs while it records, each replay runs the graphs and the call in order" { + const t = try rig.Rig.open(1 << 20); + defer t.close(); + const n = 1000; + var a = try t.alloc(4 * n); + defer a.free(); + var b = try t.alloc(4 * n); + defer b.free(); + var c = try t.alloc(4 * n); + defer c.free(); + var d = try t.alloc(4 * n); + defer d.free(); + var host: [n]f32 = undefined; + for (&host, 0..) |*x, i| x.* = @floatFromInt(i); + try runtime.check(t.r.api.hipMemcpyHtoD(@ptrFromInt(a.base()), @ptrCast(&host), 4 * n)); + const zeros: [n]f32 = @splat(0); + try runtime.check(t.r.api.hipMemcpyHtoD(@ptrFromInt(d.base()), @ptrCast(&zeros), 4 * n)); + var copy: Copy = .{ .r = &t.r }; + const inner: collective.Comm = .{ .ptr = ©, .vtable = &Copy.vtable, .rank = 0, .world = 1 }; + var rec: split.Recorder = .{ .gpa = rig.gpa, .stream = t.stream, .inner = inner }; + try rec.begin(); + const via = rec.comm().?; + // a -> b, the call b -> c, c -> d + try t.on.tf_cast(@ptrFromInt(a.base()), 0, @ptrFromInt(b.base()), 0, n, t.stream.handle); + try via.allGather(b.base(), c.base(), n, .f32, t.stream.handle); + try t.on.tf_cast(@ptrFromInt(c.base()), 0, @ptrFromInt(d.base()), 0, n, t.stream.handle); + var s = (try rec.finish()) orelse return error.TestUnexpectedResult; + defer s.deinit(); + try t.stream.synchronize(); + try std.testing.expectEqual(@as(usize, 3), s.pieces.len); + try std.testing.expectEqual(@as(usize, 0), copy.calls); + var got: [n]f32 = undefined; + try runtime.check(t.r.api.hipMemcpyDtoH(@ptrCast(&got), @ptrFromInt(d.base()), 4 * n)); + for (got) |x| try std.testing.expectEqual(@as(f32, 0), x); + for (0..3) |round| { + for (&host, 0..) |*x, i| x.* = @floatFromInt(i * (round + 2)); + try runtime.check(t.r.api.hipMemcpyHtoD(@ptrFromInt(a.base()), @ptrCast(&host), 4 * n)); + try s.launchOn(t.stream); + try t.stream.synchronize(); + try runtime.check(t.r.api.hipMemcpyDtoH(@ptrCast(&got), @ptrFromInt(d.base()), 4 * n)); + try std.testing.expectEqualSlices(f32, &host, &got); + } + try std.testing.expectEqual(@as(usize, 3), copy.calls); +} diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index d3ef4888e0c..385edb8fe09 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -16,6 +16,7 @@ pub const Function = @import("module.zig").Function; pub const launch = @import("launch.zig"); pub const graph = @import("graph.zig"); pub const graph_cache = @import("graph_cache.zig"); +pub const graph_split = @import("graph_split.zig"); pub const Arena = @import("arena.zig").Arena; pub const caps = @import("caps.zig"); pub const Caps = caps.Caps; From 548005519ece0e593baaa582b449d3d476395694 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:37:03 +0200 Subject: [PATCH 25/52] feat(hip): the graph cache over any replayable step, a caller's own kept with hold --- zig/src/hip/graph_cache.zig | 35 ++++++++++++++++++++++++++++++++++- zig/src/hip/root.zig | 1 + 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/zig/src/hip/graph_cache.zig b/zig/src/hip/graph_cache.zig index 8b9be16aa07..4bc7d586e8a 100644 --- a/zig/src/hip/graph_cache.zig +++ b/zig/src/hip/graph_cache.zig @@ -11,13 +11,18 @@ pub const State = enum { seen, ready, failed }; /// A cache of graphs keyed by `Key` (plain integers and booleans), each with the `Out` its capture produced. pub fn Cache(comptime Key: type, comptime Out: type) type { + return CacheOf(Key, Out, hip_graph.Exec); +} + +/// The same over any replayable `Exec` (a graph, or a step's graphs between collectives): it has `deinit`. +pub fn CacheOf(comptime Key: type, comptime Out: type, comptime Exec: type) type { return struct { const Self = @This(); pub const Entry = struct { key: Key, state: State = .seen, - exec: ?hip_graph.Exec = null, + exec: ?Exec = null, out: Out = undefined, tick: u64 = 0, }; @@ -82,6 +87,14 @@ pub fn Cache(comptime Key: type, comptime Out: type) type { return .{ .out = out, .graph = graph }; } + /// Keeps `exec`, made by the caller, as the shape's replay with its outputs. + pub fn hold(g: *Self, e: *Entry, exec: Exec, out: Out) void { + e.exec = exec; + e.out = out; + e.state = .ready; + g.captured += 1; + } + /// Instantiates a capture that just ended, keeps it with its outputs, and uploads it. pub fn keep(g: *Self, e: *Entry, graph: hip_graph.Graph, stream: Stream, out: Out) !void { var tmp = graph; @@ -97,3 +110,23 @@ pub fn Cache(comptime Key: type, comptime Out: type) type { } }; } + +test "a held replay is the shape's until the cache drops it" { + const Fake = struct { + drops: *usize, + fn deinit(f: *@This()) void { + f.drops.* += 1; + } + }; + var drops: usize = 0; + var c = CacheOf(u32, u8, Fake).init(std.testing.allocator); + const e = try c.find(7); + c.hold(e, .{ .drops = &drops }, 3); + const again = try c.find(7); + try std.testing.expectEqual(State.ready, again.state); + try std.testing.expectEqual(@as(u8, 3), again.out); + c.revoke(again); + try std.testing.expectEqual(@as(usize, 1), drops); + try std.testing.expectEqual(State.failed, (try c.find(7)).state); + c.deinit(); +} diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index 385edb8fe09..b47ff9dc83c 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -44,6 +44,7 @@ test { _ = admission; _ = Device; _ = collective; + _ = graph_cache; _ = @import("comm/rccl.zig"); _ = @import("comm/link.zig"); _ = @import("comm/group.zig"); From ebe69eb2875df62c9590b272b96804571b727b82 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:59:01 +0200 Subject: [PATCH 26/52] feat(qwen3_5): HIP rounds record split graphs: the collectives run between a round's graphs, not inside one --- .../qwen3_5/backend/hip/engine/round.zig | 42 ++++++++++++------- .../backend/hip/engine/round_graphs.zig | 4 +- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round.zig b/zig/src/families/qwen3_5/backend/hip/engine/round.zig index 10be7123eef..53d3d237017 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/round.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/round.zig @@ -180,24 +180,11 @@ fn run(e: *Engine, c: Chosen, r: win.Round) !round_graphs.Out { } } -const Recording = struct { e: *Engine, r: win.Round }; - -fn record(ctx: Recording) anyerror!round_graphs.Out { - return body(ctx.e, ctx.r); -} - -/// Records the round into a graph and launches it; a capture that fails on any rank runs eagerly on every rank. +/// Records the round and launches it; a rank that cannot record makes every rank run it eagerly. fn capture(e: *Engine, entry: *round_graphs.Entry, r: win.Round) !round_graphs.Out { - var kept = false; - var out: round_graphs.Out = undefined; const at = e.rounds.mark(); const began = nowNs(); - if (try round_graphs.Graphs.record(e.stream, Recording{ .e = e, .r = r }, record)) |rec| { - out = rec.out; - kept = if (e.graphs.keep(entry, rec.graph, e.stream, rec.out)) true else |_| false; - } - // the policy's `graph_fail` makes that rank's capture fail, to check that every rank falls back - if (e.o.policy.graph_fail >= 0 and @as(usize, @intCast(e.o.policy.graph_fail)) == e.o.rank) kept = false; + const kept = try record(e, entry, r); e.graphs.capture_ns += nowNs() - began; const all = if (e.o.world > 1) try agreed(e, kept) else kept; if (!all) { @@ -206,7 +193,30 @@ fn capture(e: *Engine, entry: *round_graphs.Entry, r: win.Round) !round_graphs.O return body(e, r); } try entry.exec.?.launchOn(e.stream); - return out; + return entry.out; +} + +/// The round recorded into `entry` (nothing runs), its collectives left between the graphs: whether this rank kept it. +fn record(e: *Engine, entry: *round_graphs.Entry, r: win.Round) !bool { + const m = &e.bridge.model; + var rec: hip.graph_split.Recorder = .{ .gpa = e.gpa, .stream = e.stream, .inner = m.tp }; + rec.begin() catch return false; + const tp = m.tp; + m.tp = rec.comm(); + const got = body(e, r); + m.tp = tp; + var split = (try rec.finish()) orelse return false; + const out = got catch |err| { + split.deinit(); + return if (err == error.OutOfDeviceMemory) err else false; + }; + // the policy's `graph_fail` makes that rank's capture fail, to check that every rank falls back + if (e.o.policy.graph_fail >= 0 and @as(usize, @intCast(e.o.policy.graph_fail)) == e.o.rank) { + split.deinit(); + return false; + } + e.graphs.hold(entry, split, out); + return true; } /// Whether every rank says yes (an all-gather of one word each). diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig index d42ed86ed93..333699c2ced 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/round_graphs.zig @@ -1,4 +1,4 @@ -//! Captured lane rounds: a round's forward recorded once per plan shape and replayed on any later round of it. +//! Captured lane rounds: a round recorded once per plan shape as graphs cut at its collectives, replayed after. const hip = @import("hip"); const plan = @import("../forward/plan.zig"); @@ -7,6 +7,6 @@ const graph_cache = hip.graph_cache; /// What a replay hands back: the forward's outputs and where the arena stands after it. pub const Out = struct { hidden: hip.ops.Tensor, y: hip.ops.Tensor, used: usize }; -pub const Graphs = graph_cache.Cache(plan.Shape, Out); +pub const Graphs = graph_cache.CacheOf(plan.Shape, Out, hip.graph_split.Split); pub const Entry = Graphs.Entry; From 10926cf39bc78a2dd76f3a1604b9a09ff3236718 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:00:58 +0200 Subject: [PATCH 27/52] feat(qwen3_5): HIP rounds replay split graphs at any world size, RCCL outside them; graphs=off turns them off --- .../qwen3_5/backend/hip/engine/engine.zig | 9 +++------ zig/src/hip/policy.zig | 20 +++++++++---------- zig/tests/qwen35/check_invariants.zig | 2 -- 3 files changed, 12 insertions(+), 19 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index f7c770d8ea9..2ebb5a2435f 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -88,8 +88,6 @@ pub const Engine = struct { /// Tensor parallelism: this rank's communicator. comm: hip.collective.Comm = undefined, graphs: round_graphs.Graphs, - /// The draft head's batches replay graphs (the head holds no collective, so under tp too unless graphs=off). - head_graphs: bool = true, /// The lane rounds' plan, graph choice and keep. round: lane_round.State = undefined, @@ -100,9 +98,8 @@ pub const Engine = struct { e.gpa = gpa; e.o = o; e.sized = false; - // rounds replay graphs as the policy says; under tensor parallelism only when it is `graphs=on` - e.o.graphs = o.graphs and o.policy.graphsOn(o.world); - e.head_graphs = o.graphs and o.policy.graphsOn(1); + // rounds and the draft head's batches replay graphs unless the policy says `graphs=off`, at any world size + e.o.graphs = o.graphs and o.policy.graphsOn(); e.graphs = round_graphs.Graphs.init(gpa); e.driver = try hip.Runtime.open(); errdefer e.driver.close(); @@ -282,7 +279,7 @@ pub const Engine = struct { /// Whether the draft head's greedy batches replay graphs. pub fn headGraphs(e: *const Engine) bool { - return if (e.o.world > 1) e.head_graphs else e.o.graphs; + return e.o.graphs; } /// Waits for the stream, before caches are freed (a round may still be running on them). diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index a94dfe10491..f040d6109d1 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -88,13 +88,9 @@ pub const Policy = struct { return p.attention != .f32; } - /// Whether rounds replay captured graphs on a group of `world` ranks. - pub fn graphsOn(p: *const Policy, world: usize) bool { - return switch (p.graphs) { - .on => true, - .off => false, - .auto => world == 1, - }; + /// Whether rounds replay captured graphs, on one rank or a group: only `graphs=off` turns them off. + pub fn graphsOn(p: *const Policy) bool { + return p.graphs != .off; } /// Applies `key=value,key=value` (`--policy`'s and TF_POLICY's syntax) over this policy, all of it or none. @@ -243,16 +239,18 @@ test "TF_POLICY speaks after the flags, and the reference switches" { const p = try Policy.resolve("matrix=off", env, ¬es); try std.testing.expectEqual(Choice.on, p.matrix); try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and p.chunked() and !p.wideAttention()); - try std.testing.expect(!p.graphsOn(1) and !p.graphsOn(2)); + try std.testing.expect(!p.graphsOn()); try std.testing.expect(std.mem.indexOf(u8, notes.text(), "TF_POLICY=") != null); var reference: Policy = .{}; try reference.apply("kernels=reference"); try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused() and !reference.chunked()); } -test "graphs follow the group unless the policy says" { +test "graphs are on at any world size unless the policy turns them off" { var p: Policy = .{}; - try std.testing.expect(p.graphsOn(1) and !p.graphsOn(2)); + try std.testing.expect(p.graphsOn()); try p.apply("graphs=on"); - try std.testing.expect(p.graphsOn(2)); + try std.testing.expect(p.graphsOn()); + try p.apply("graphs=off"); + try std.testing.expect(!p.graphsOn()); } diff --git a/zig/tests/qwen35/check_invariants.zig b/zig/tests/qwen35/check_invariants.zig index aaaa3907308..abf78473565 100644 --- a/zig/tests/qwen35/check_invariants.zig +++ b/zig/tests/qwen35/check_invariants.zig @@ -93,7 +93,6 @@ fn lanesSet(c: *Ctx, set: []const u8, prompts: []const ids_file.Prompt) void { /// `graph` ran with the engine's graphs; the same job again with every round eager. fn graphs(c: *Ctx, name: []const u8, job: Session.Job, graph: Session.Done) void { - if (c.tp()) return c.report.skip(name, "rounds under tp run eager unless --policy graphs=on"); if (!c.e.o.graphs) return c.report.skip(name, "graphs are off"); if (graph.replayed == 0) return c.report.skip(name, "no round of the run replayed a graph"); c.e.o.graphs = false; @@ -128,7 +127,6 @@ fn resumed(c: *Ctx) void { /// A drafted run of every stream at once, the third time: once its shapes are met, rounds replay graphs. fn replayShare(c: *Ctx) void { const name = "lanes short greedy: rounds replayed"; - if (c.tp() and !c.e.o.graphs) return c.report.skip(name, "rounds under tp run eager unless the policy says graphs=on"); if (!c.e.o.graphs) return c.report.skip(name, "graphs are off"); const job: Session.Job = .{ .prompts = c.short, .max_new = c.tokens }; var done: Session.Done = undefined; From 66d8a19bae96445b48af44b3ca458d13b5fd44b4 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:19:37 +0200 Subject: [PATCH 28/52] fix(qwen3_5): every rank sizes its streams for rank 0's window, so a prompt past a follower's default no longer stops it A follower started without --context sized its streams for the 32768-token default while rank 0 served a longer window; the first prompt past it sent a page table larger than the follower's, and rank 1 stopped with Invalid. Engine.first gives every rank rank 0's values over the same all-gather as least. --- .../families/qwen3_5/backend/hip/engine/engine.zig | 12 +++++++++++- .../families/qwen3_5/backend/hip/engine/native.zig | 10 ++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index 2ebb5a2435f..641272ee43f 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -178,8 +178,17 @@ pub const Engine = struct { return e.sizedBytes(try e.arenaBytes(rows, prompt_rows, capacity), rows, prompt_rows, pool_pages); } - /// The least of each value over the ranks, the same on every rank (a window and a prompt cache they all fit). + /// The least of each value over the ranks, the same on every rank (the streams and a prompt cache they all fit). pub fn least(e: *Engine, mine: [2]u64) ![2]u64 { + return e.agree(mine, .least); + } + + /// Rank 0's values on every rank: what rank 0 was asked for, such as the window its page tables cover. + pub fn first(e: *Engine, mine: [2]u64) ![2]u64 { + return e.agree(mine, .first); + } + + fn agree(e: *Engine, mine: [2]u64, how: enum { least, first }) ![2]u64 { if (e.o.world < 2) return mine; const world = e.o.world; var host = try hip.HostBuffer.alloc(&e.driver, 16 * (1 + world)); @@ -193,6 +202,7 @@ pub const Engine = struct { try e.comm.allGather(send.base(), recv.base(), 2, .i64, e.stream.handle); try recv.downloadAsync(0, host.view(16, 16 * (1 + world)), e.stream); try e.stream.synchronize(); + if (how == .first) return host.slice(u64)[2..4].*; var out = mine; for (host.slice(u64)[2 .. 2 * (1 + world)], 0..) |v, i| out[i % 2] = @min(out[i % 2], v); return out; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig index 9ef3064454b..70deee419ce 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -110,7 +110,9 @@ fn prepare(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.De const after = e.budget(io) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)}); const room = after.room(model); const reserve = after.reserve; - const capacity = o.window + rows + 1; + // a follower sizes its streams for rank 0's window: the page tables rank 0 sends cover that many positions + const window: usize = if (o.world > 1) @intCast((e.first(.{ o.window, 0 }) catch |err| return refuse(a, problem, "the ranks could not agree on the window ({s})", .{@errorName(err)}))[0]) else o.window; + const capacity = window + rows + 1; // the most streams up to the ones asked whose bytes fit, then the least of that over the ranks var streams = o.streams; while (streams > 0) : (streams -= 1) { @@ -119,11 +121,11 @@ fn prepare(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.De if (o.world > 1) streams = (e.least(.{ streams, 0 }) catch |err| return refuse(a, problem, "the ranks could not agree on the streams ({s})", .{@errorName(err)}))[0]; if (streams == 0) { const one = served(e, 1, capacity) catch 0; - return refuse(a, problem, "the HIP memory budget fits no stream: one at a {d}-token window takes {d:.2} GiB, and {d:.2} GiB is left after the model's {d:.2} GiB and the {d:.1} GiB reserve; lower --context, add ranks (--tp), or free device memory", .{ o.window, gibs(one), gibs(room), gibs(model), gibs(reserve) }); + return refuse(a, problem, "the HIP memory budget fits no stream: one at a {d}-token window takes {d:.2} GiB, and {d:.2} GiB is left after the model's {d:.2} GiB and the {d:.1} GiB reserve; lower --context, add ranks (--tp), or free device memory", .{ window, gibs(one), gibs(room), gibs(model), gibs(reserve) }); } if (streams < o.streams and o.fixed) { const asked = served(e, o.streams, capacity) catch 0; - return refuse(a, problem, "--parallel {d} needs {d:.2} GiB at a {d}-token window, and the HIP memory budget leaves {d:.2} GiB: serve --parallel {d}, or lower --context", .{ o.streams, gibs(asked), o.window, gibs(room), streams }); + return refuse(a, problem, "--parallel {d} needs {d:.2} GiB at a {d}-token window, and the HIP memory budget leaves {d:.2} GiB: serve --parallel {d}, or lower --context", .{ o.streams, gibs(asked), window, gibs(room), streams }); } const need = served(e, streams, capacity) catch |err| return refuse(a, problem, "the native HIP engine cannot count its scratch ({s})", .{@errorName(err)}); // the prompt cache: --prompt-cache-gib, else what the streams leave @@ -146,7 +148,7 @@ fn prepare(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.De return refuse(a, problem, "the native HIP engine cannot allocate its scratch and pages ({s})", .{@errorName(err)}); const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size())); const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompt cache {d:.2} GiB ({d} pages, {d} snapshots); prompts in {d}-row chunks", .{ - hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), streams, if (streams == 1) "" else "s", lane, o.window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, + hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), streams, if (streams == 1) "" else "s", lane, window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk, }); return .{ .e = e, .streams = streams, .cache = cache, .startup = startup }; } From d47b0f899bea77d5284c0db1fff51eaf8ae18e56 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:24:33 +0200 Subject: [PATCH 29/52] perf(qwen3_5): the HIP loader drops each part's mapped pages once it is uploaded The loader read every tensor through the checkpoint's mapping and kept the pages mapped until the load ended, so a rank's resident set grew to the whole checkpoint. After the embedding, norm and head, each layer and the MTP head, their pages leave the mapping (madvise DONTNEED); the page cache keeps them, and a later read faults them back. --- .../qwen3_5/backend/hip/model/weights.zig | 4 +++ .../families/qwen3_5/weights/checkpoint.zig | 12 +++++++ zig/src/families/qwen3_5/weights/shard.zig | 32 +++++++++++++++++++ zig/src/families/qwen3_5/weights/table.zig | 11 +++++++ 4 files changed, 59 insertions(+) diff --git a/zig/src/families/qwen3_5/backend/hip/model/weights.zig b/zig/src/families/qwen3_5/backend/hip/model/weights.zig index 1a2c40f8914..468d7e87d3a 100644 --- a/zig/src/families/qwen3_5/backend/hip/model/weights.zig +++ b/zig/src/families/qwen3_5/backend/hip/model/weights.zig @@ -216,6 +216,8 @@ pub const Model = struct { if (rank) |r| { m.head = try u.projection(try slicing.vocabRows(scratch.allocator(), head orelse embed, whole.vocab, r)); } else if (head) |h| m.head = try u.projection(h); + // each part's mapped pages go once it is up: a rank holds one layer of the checkpoint at a time, not all of it + ck.release(null); var list: std.ArrayList(Layer) = .empty; errdefer list.deinit(gpa); for (0..@min(limit, m.spec.n_layers)) |i| { @@ -223,6 +225,7 @@ pub const Model = struct { defer host_layer.deinit(); if (rank) |r| try slicing.layer(&host_layer, whole, r); try list.append(gpa, try u.layer(host_layer)); + ck.release(i); } m.layers = try list.toOwnedSlice(gpa); // under tp only rank 0 drafts: its head is whole, logits rows included (its own or the model's whole head) @@ -232,6 +235,7 @@ pub const Model = struct { defer h.deinit(); if (rank != null and h.head == null) h.head = head orelse embed; m.mtp = try u.mtp(h); + ck.main.release("mtp."); }; return m; } diff --git a/zig/src/families/qwen3_5/weights/checkpoint.zig b/zig/src/families/qwen3_5/weights/checkpoint.zig index 62300bb1c2f..61c06a719da 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint.zig @@ -58,6 +58,18 @@ pub const Checkpoint = struct { return try projection.projection(a, &c.main, "language_model.lm_head"); } + /// Drops the mapped pages of layer `index` once it is uploaded (null: the embedding, norm and head). + pub fn release(c: *const Checkpoint, index: ?usize) void { + if (index) |i| { + var name: [128]u8 = undefined; + c.main.release(std.fmt.bufPrint(&name, prefix ++ "layers.{d}.", .{i}) catch return); + } else { + c.main.release(prefix ++ "embed_tokens"); + c.main.release(prefix ++ "norm."); + c.main.release("language_model.lm_head"); + } + } + /// Layer `index`, read and converted; free it with `deinit`. pub fn layer(c: *const Checkpoint, index: usize) !host.Layer { const s = c.spec(); diff --git a/zig/src/families/qwen3_5/weights/shard.zig b/zig/src/families/qwen3_5/weights/shard.zig index e09e502bc97..b216f016c95 100644 --- a/zig/src/families/qwen3_5/weights/shard.zig +++ b/zig/src/families/qwen3_5/weights/shard.zig @@ -1,6 +1,7 @@ //! One safetensors file mapped read-only; tensors above core's max rank and unnamed dtypes stay out of its index. const std = @import("std"); +const builtin = @import("builtin"); const Io = std.Io; const st = @import("core").safetensors; @@ -35,6 +36,16 @@ pub const Shard = struct { s.* = undefined; } + /// Drops data bytes [begin, end) (their whole pages) from this mapping; the page cache keeps them, a read refaults. + pub fn release(s: *const Shard, begin: usize, end: usize) void { + if (builtin.os.tag != .linux or end <= begin) return; + const page = std.heap.pageSize(); + const lo = std.mem.alignBackward(usize, s.data + begin, page); + const hi = @min(std.mem.alignForward(usize, s.data + end, page), s.map.memory.len); + if (hi <= lo) return; + _ = std.os.linux.madvise(s.map.memory.ptr + lo, hi - lo, std.os.linux.MADV.DONTNEED); + } + pub fn get(s: *const Shard, name: []const u8) ?Tensor { const e = s.names.get(name) orelse return null; return .{ .dtype = e.dtype, .rank = e.rank, .shape = e.shape, .bytes = s.map.memory[s.data + e.begin .. s.data + e.end] }; @@ -79,3 +90,24 @@ test "a tensor above the max rank and an unknown dtype are left out" { try std.testing.expectEqual(@as(usize, 1), h.count()); try std.testing.expect(h.contains("a")); } + +test "released pages read back the same bytes" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + const n = 3 * 4096; + const header = "{\"t\":{\"dtype\":\"BF16\",\"shape\":[6144],\"data_offsets\":[0,12288]}}"; + var bytes: [8 + header.len + n]u8 = undefined; + std.mem.writeInt(u64, bytes[0..8], header.len, .little); + @memcpy(bytes[8..][0..header.len], header); + for (bytes[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i *% 31); + try tmp.dir.writeFile(io, .{ .sub_path = "s.safetensors", .data = &bytes }); + const path = try tmp.dir.realPathFileAlloc(io, "s.safetensors", std.testing.allocator); + defer std.testing.allocator.free(path); + var s = try Shard.open(std.testing.allocator, io, path); + defer s.close(io); + const before = try std.testing.allocator.dupe(u8, s.get("t").?.bytes); + defer std.testing.allocator.free(before); + s.release(0, n); + try std.testing.expectEqualSlices(u8, before, s.get("t").?.bytes); +} diff --git a/zig/src/families/qwen3_5/weights/table.zig b/zig/src/families/qwen3_5/weights/table.zig index 0bb3936a081..f0c20ed82c7 100644 --- a/zig/src/families/qwen3_5/weights/table.zig +++ b/zig/src/families/qwen3_5/weights/table.zig @@ -49,6 +49,17 @@ pub const Table = struct { t.* = undefined; } + /// Releases the mapped pages of every tensor whose key starts with `key_prefix` (`Shard.release`). + pub fn release(t: *const Table, key_prefix: []const u8) void { + var it = t.where.iterator(); + while (it.next()) |kv| { + if (!std.mem.startsWith(u8, kv.key_ptr.*, key_prefix)) continue; + const shard = &t.files[kv.value_ptr.file]; + const e = shard.names.get(kv.value_ptr.stored) orelse continue; + shard.release(e.begin, e.end); + } + } + pub fn has(t: *const Table, key: []const u8) bool { return t.where.contains(key); } From 996c0983052f2a0d62f51a115c015f6dfb78d4c5 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:32:29 +0200 Subject: [PATCH 30/52] fix(core): MLX affine dequant reads any code width from 2 to 8 bits, across words, as the reference does --- zig/src/core/quant/mlx.zig | 43 +++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/zig/src/core/quant/mlx.zig b/zig/src/core/quant/mlx.zig index f2334eb01a6..fdc05d347d0 100644 --- a/zig/src/core/quant/mlx.zig +++ b/zig/src/core/quant/mlx.zig @@ -209,7 +209,7 @@ pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void { }; } -/// MLX affine words and tables as fp32 [R, K] the way torch computes them (product rounded, then sum), widths 2, 4, 8. +/// MLX affine words and tables as fp32 [R, K] the way torch computes them (product rounded, then sum), widths 2 to 8. pub fn dequant(a: Allocator, words: Tensor, scale: Tensor, bias: Tensor, group: usize) convert.Error![]f32 { if (words.rank != 2 or scale.rank != 2 or bias.rank != 2 or !std.mem.eql(usize, scale.shape[0..2], bias.shape[0..2])) return error.UnexpectedTensor; if (words.dtype != .u32 and words.dtype != .i32) return error.UnexpectedTensor; @@ -218,14 +218,18 @@ pub fn dequant(a: Allocator, words: Tensor, scale: Tensor, bias: Tensor, group: const k = scale.shape[1] * group; if (k == 0 or 32 * words.shape[1] / k == 0) return error.UnexpectedTensor; const bits = 32 * words.shape[1] / k; - if (bits != 2 and bits != 4 and bits != 8) return error.UnsupportedQuantization; - const per = 32 / bits; - if (words.shape[1] * per != k or scale.shape[0] != n_rows) return error.UnexpectedTensor; + if (bits < 2 or bits > 8) return error.UnsupportedQuantization; + const row_words = words.shape[1]; + if (row_words * 32 != k * bits or scale.shape[0] != n_rows) return error.UnexpectedTensor; const out = try a.alloc(f32, n_rows * k); - const mask: u32 = (@as(u32, 1) << @intCast(bits)) - 1; + const mask: u64 = (@as(u64, 1) << @intCast(bits)) - 1; for (0..n_rows) |r| for (0..k) |c| { - const word = std.mem.readInt(u32, words.bytes[4 * (r * words.shape[1] + c / per) ..][0..4], .little); - const code: f32 = @floatFromInt((word >> @intCast(bits * (c % per))) & mask); + // a code may run into the next word (3, 5, 6 and 7 bits): read the pair + const bit = c * bits; + const at = r * row_words + (bit >> 5); + const lo: u64 = std.mem.readInt(u32, words.bytes[4 * at ..][0..4], .little); + const hi: u64 = if ((bit & 31) + bits > 32) std.mem.readInt(u32, words.bytes[4 * (at + 1) ..][0..4], .little) else 0; + const code: f32 = @floatFromInt(((lo | hi << 32) >> @intCast(bit & 31)) & mask); const g = r * scale.shape[1] + c / group; const s = convert.load(scale.dtype, scale.bytes, g); const b = convert.load(bias.dtype, bias.bytes, g); @@ -280,6 +284,31 @@ test "dequant unpacks 4-bit words low nibble first" { try std.testing.expectEqualSlices(f32, &.{ -1, 1, 3, 5, 7, 9, 11, 13 }, out); } +test "dequant reads 3- and 6-bit codes across words as the reference does" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + inline for (.{ 3, 6 }) |bits| { + // one row of 32 codes, code i = i % 2^bits, packed little-endian + var words: [bits]u32 = @splat(0); + for (0..32) |i| { + const bit = i * bits; + const v: u64 = @as(u64, i % (1 << bits)) << @intCast(bit & 31); + words[bit >> 5] |= @truncate(v); + if ((bit & 31) + bits > 32) words[(bit >> 5) + 1] |= @truncate(v >> 32); + } + var scale = [_]u16{0x4000}; // 2.0 + var bias = [_]u16{0xBF80}; // -1.0 + const h = hostOf(&words, &scale, &bias, 1, bits, 32); + const out = try dequant(arena.allocator(), h.words, h.scales, h.biases, 32); + var want: [32]f64 = undefined; + try reference(h, &want); + for (out, want, 0..) |x, y, i| { + try std.testing.expectEqual(@as(f32, @floatFromInt(i % (1 << bits))) * 2 - 1, x); + try std.testing.expectEqual(@as(f64, x), y); + } + } +} + test "a projection splits its words and group tables on the same boundary" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); From 7aa8722fe4edb254725a9d6639d3a3c583704fc4 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:17:08 +0200 Subject: [PATCH 31/52] refactor(hip): the memory budget in admission.zig, where every HIP family reads it The Qwen3.5 engine's budget (free memory, the reserve, TENSORFOLD_HIP_MEMORY_LIMIT_GB) moves unchanged into hip.admission.budget, so Flash Next's admission counts the card the same way; Engine.budget calls it. --- .../qwen3_5/backend/hip/engine/engine.zig | 13 +------------ zig/src/hip/admission.zig | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index 641272ee43f..b070ded67cb 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -219,14 +219,7 @@ pub const Engine = struct { /// The memory a plan may take, as the native backends count it: free (host's when integrated), reserve and cap. pub fn budget(e: *const Engine, io: std.Io) !admission.Pool { - const unified = (try e.ctx.attribute(.integrated)) != 0; - const card = try e.ctx.memInfo(); - const text = if (unified) admission.procText(e.gpa, io, "/proc/meminfo") else null; - defer if (text) |t| e.gpa.free(t); - const counts = admission.counts(unified, .{ .total = card.total, .available = card.free }, text) catch return error.HostMemoryUnavailable; - const reserve = admission.reserveBytes(getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), counts.total, unified) catch return error.BadReserve; - const limit = admission.limitBytes(getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB")) catch return error.BadLimit; - return .{ .free = counts.available, .total = counts.total, .reserve = reserve, .limit = limit, .unified = unified }; + return admission.budget(e.gpa, io, e.ctx); } /// Load and size in one: `o.capacity` positions, refused when the plan does not fit the memory. @@ -405,7 +398,3 @@ pub const Engine = struct { try lane_round.flush(e); } }; - -fn getenv(name: [:0]const u8) ?[]const u8 { - return std.mem.span(std.c.getenv(name) orelse return null); -} diff --git a/zig/src/hip/admission.zig b/zig/src/hip/admission.zig index 2082b5b49de..2edbcfa84cd 100644 --- a/zig/src/hip/admission.zig +++ b/zig/src/hip/admission.zig @@ -1,6 +1,7 @@ //! What the HIP engine may serve: the CUDA path's memory rules (cuda_memory.zig) and the window and weights it reads. const std = @import("std"); const memory = @import("cuda_memory"); +const Context = @import("context.zig").Context; const Allocator = std.mem.Allocator; pub const MemInfo = memory.MemInfo; @@ -45,6 +46,22 @@ pub fn weightBytes(io: std.Io, dir: []const u8) u64 { return total; } +/// What a plan may take on `ctx`'s GPU, as the native backends count it: free (host's if integrated), reserve, cap. +pub fn budget(gpa: Allocator, io: std.Io, ctx: Context) !Pool { + const unified = (try ctx.attribute(.integrated)) != 0; + const card = try ctx.memInfo(); + const text = if (unified) procText(gpa, io, "/proc/meminfo") else null; + defer if (text) |t| gpa.free(t); + const c = counts(unified, .{ .total = card.total, .available = card.free }, text) catch return error.HostMemoryUnavailable; + const reserve = reserveBytes(getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), c.total, unified) catch return error.BadReserve; + const limit = limitBytes(getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB")) catch return error.BadLimit; + return .{ .free = c.available, .total = c.total, .reserve = reserve, .limit = limit, .unified = unified }; +} + +fn getenv(name: [:0]const u8) ?[]const u8 { + return std.mem.span(std.c.getenv(name) orelse return null); +} + /// A /proc file's text, streamed: procfs reports size 0, and a positional read (readFileAlloc) stops there. pub fn procText(a: Allocator, io: std.Io, path: []const u8) ?[]u8 { var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null; From 9c1a8416482ac11f26f23ed14fb1a900b7a3aa24 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:17:00 +0200 Subject: [PATCH 32/52] refactor(flashnext): the affine spec in a file of its own, so a backend module reads the config without core config.zig took Spec from affine.zig, which reads safetensors entries through core. A module that imports core as a module (the HIP engine's) cannot also hold core's files by path, so the spec moves to spec.zig; affine.zig re-exports it and the Metal build sees the same declarations. --- zig/src/families/flashnext/affine.zig | 22 +--------------------- zig/src/families/flashnext/config.zig | 2 +- zig/src/families/flashnext/spec.zig | 24 ++++++++++++++++++++++++ 3 files changed, 26 insertions(+), 22 deletions(-) create mode 100644 zig/src/families/flashnext/spec.zig diff --git a/zig/src/families/flashnext/affine.zig b/zig/src/families/flashnext/affine.zig index 6152735775e..3a99223d540 100644 --- a/zig/src/families/flashnext/affine.zig +++ b/zig/src/families/flashnext/affine.zig @@ -2,27 +2,7 @@ const std = @import("std"); const st = @import("../../core/safetensors.zig"); -pub const Spec = struct { - bits: u8, - group: usize, - - pub fn init(bits: usize, group: usize) !Spec { - if (bits != 2 and bits != 3 and bits != 4 and bits != 5 and bits != 6 and bits != 8) return error.UnsupportedAffineBits; - if (group != 32 and group != 64 and group != 128) return error.UnsupportedAffineGroup; - return .{ .bits = @intCast(bits), .group = group }; - } - - pub fn words(s: Spec, k: usize) !usize { - if (k == 0 or k % s.group != 0) return error.InvalidAffineWidth; - const count = try std.math.mul(usize, k, s.bits); - if (count % 32 != 0) return error.InvalidAffineWidth; - return count / 32; - } - - pub fn checkFlashKernel(s: Spec) !void { - if (s.bits != 6 or s.group != 32) return error.UnsupportedFlashAffineKernel; - } -}; +pub const Spec = @import("spec.zig").Spec; pub const Shape = struct { experts: usize, n: usize, k: usize, words: usize, groups: usize, dtype: st.DType }; diff --git a/zig/src/families/flashnext/config.zig b/zig/src/families/flashnext/config.zig index 7241ee0b548..7e723654271 100644 --- a/zig/src/families/flashnext/config.zig +++ b/zig/src/families/flashnext/config.zig @@ -1,6 +1,6 @@ //! FlashNext text dimensions and quantization declarations are checked before weight or cache allocation. const std = @import("std"); -const affine = @import("affine.zig"); +const affine = @import("spec.zig"); pub const Kind = enum { linear_attention, sparse_attention }; pub const Gate = enum { sigmoid, silu }; diff --git a/zig/src/families/flashnext/spec.zig b/zig/src/families/flashnext/spec.zig new file mode 100644 index 00000000000..115bdfcb283 --- /dev/null +++ b/zig/src/families/flashnext/spec.zig @@ -0,0 +1,24 @@ +//! The affine bits and group a checkpoint declares; no checkpoint file is read, so any backend's module takes it. +const std = @import("std"); + +pub const Spec = struct { + bits: u8, + group: usize, + + pub fn init(bits: usize, group: usize) !Spec { + if (bits != 2 and bits != 3 and bits != 4 and bits != 5 and bits != 6 and bits != 8) return error.UnsupportedAffineBits; + if (group != 32 and group != 64 and group != 128) return error.UnsupportedAffineGroup; + return .{ .bits = @intCast(bits), .group = group }; + } + + pub fn words(s: Spec, k: usize) !usize { + if (k == 0 or k % s.group != 0) return error.InvalidAffineWidth; + const count = try std.math.mul(usize, k, s.bits); + if (count % 32 != 0) return error.InvalidAffineWidth; + return count / 32; + } + + pub fn checkFlashKernel(s: Spec) !void { + if (s.bits != 6 or s.group != 32) return error.UnsupportedFlashAffineKernel; + } +}; From 1356ecb49f390234d8e957778acc17a821a8f4b7 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:22:03 +0200 Subject: [PATCH 33/52] refactor(hip): the routed MoE and the tensor-parallel reduce in the hip module, for every HIP family Qwen3.5's forward/moe.zig (router, pick, plan, gate and up, activation, down, combine; a rank's own experts under tp) and forward/reduce.zig (ranks' fp32 shares summed in rank order, logits slices gathered) move into the hip module as hip.moe and hip.reduce, with the Experts and Routed views they read. They take the activation kind and the communicator instead of Qwen3.5's model; Qwen3.5's forward calls them unchanged, and Flash Next's experts (512 and a shared one, top 10) take the same path. --- .../qwen3_5/backend/hip/engine/engine.zig | 2 +- .../qwen3_5/backend/hip/forward/forward.zig | 11 ++-- .../qwen3_5/backend/hip/forward/window.zig | 4 +- .../qwen3_5/backend/hip/model/view.zig | 28 +-------- zig/src/families/qwen3_5/hip.zig | 4 +- .../backend/hip/forward => hip}/moe.zig | 59 ++++++++++++++----- .../backend/hip/forward => hip}/reduce.zig | 20 +++---- zig/src/hip/root.zig | 4 ++ 8 files changed, 72 insertions(+), 60 deletions(-) rename zig/src/{families/qwen3_5/backend/hip/forward => hip}/moe.zig (72%) rename zig/src/{families/qwen3_5/backend/hip/forward => hip}/reduce.zig (69%) diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index b070ded67cb..13e2ac9e803 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -12,7 +12,7 @@ const sample = @import("sample.zig"); const memory = @import("memory.zig"); const draw = @import("draw.zig"); const slicing = @import("../../../weights/slicing.zig"); -const reduce = @import("../forward/reduce.zig"); +const reduce = hip.reduce; const round_graphs = @import("round_graphs.zig"); const lane_round = @import("round.zig"); const scratch = @import("scratch.zig"); diff --git a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig index 6205c2b7525..f2d9c973e56 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig @@ -4,8 +4,8 @@ const std = @import("std"); const hip = @import("hip"); const view = @import("../model/view.zig"); const state = @import("state.zig"); -const moe = @import("moe.zig"); -const reduce = @import("reduce.zig"); +const moe = hip.moe; +const reduce = hip.reduce; const Ops = hip.ops.Ops; const Tensor = hip.ops.Tensor; @@ -16,7 +16,10 @@ pub const SPAN = 2048; pub const Error = reduce.Error || error{Cancelled}; -pub const residual = reduce.residual; +/// x += y on the residual rows, a tp rank's fp32 share summed over the ranks first. +pub fn residual(o: Ops, m: *const view.Model, x: Tensor, y: Tensor, n: usize) Error!void { + return reduce.residual(o, m.tp, x, y, n); +} /// A device buffer of `n` values of `kind` from the arena. pub fn take(o: Ops, kind: Kind, n: usize) Error!Tensor { @@ -172,7 +175,7 @@ pub fn gatedOut(o: Ops, m: *const view.Model, l: view.Linear, y: u64, z: Tensor, /// _mlp: gate and up, silu(gate) * up, down; or the routed experts (`prefill` is the span's length above one). pub fn mlpRows(o: Ops, m: *const view.Model, mlp: view.Mlp, x: Tensor, rows: usize, prefill: bool) Error!Tensor { switch (mlp) { - .moe => |r| return moe.run(o, m, r, x, rows, prefill and rows > 1), + .moe => |r| return moe.run(o, m.act, r, x, rows, prefill and rows > 1), .dense => |d| { var outs: [4]Tensor = undefined; const gate, const up = if (try o.projectGroup(x, &.{ d.gate, d.up }, rows, &outs)) diff --git a/zig/src/families/qwen3_5/backend/hip/forward/window.zig b/zig/src/families/qwen3_5/backend/hip/forward/window.zig index 46e0e6ac28f..6bfb6591467 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/window.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/window.zig @@ -4,7 +4,7 @@ const std = @import("std"); const hip = @import("hip"); const view = @import("../model/view.zig"); const fwd = @import("forward.zig"); -const moe = @import("moe.zig"); +const moe = hip.moe; const Ops = hip.ops.Ops; const Tensor = hip.ops.Tensor; @@ -67,7 +67,7 @@ pub fn forward(ops: Ops, m: *const view.Model, r: Round, trace: ?fwd.Trace) fwd. } switch (mlp) { .moe => |rt| if (merge and rt.remap == 0) { - const parts = try moe.parts(o, m, rt, normed, total); + const parts = try moe.parts(o, m.act, rt, normed, total); try o.moeTail(x, parts.y, parts.wts, next_norm, dest, total, parts.slots, s.hidden, eps); } else { const z = try fwd.mlpRows(o, m, mlp, normed, total, true); diff --git a/zig/src/families/qwen3_5/backend/hip/model/view.zig b/zig/src/families/qwen3_5/backend/hip/model/view.zig index 4663e038c43..062f1135c20 100644 --- a/zig/src/families/qwen3_5/backend/hip/model/view.zig +++ b/zig/src/families/qwen3_5/backend/hip/model/view.zig @@ -14,31 +14,9 @@ pub fn convChannels(s: Spec) usize { return 2 * s.keyWidth() + s.valueWidth(); } -/// A layer's experts, shared expert last: gate and up stacked as one (E + 1, 2 NI, ...) weight, down (E + 1, D, ...). -pub const Experts = struct { - fused: Projection, - down: Projection, - count: usize, - width: usize, - dims: usize, - limit: f32 = 0, -}; - -/// The router's rows in fp32 (E + 1, D), the shared expert's gate last, and the experts. -pub const Routed = struct { - rows32: u64, - experts: Experts, - top_k: usize, - /// The router's rows, E + 1: the model's expert count, whatever share of the experts this rank holds. - rows: usize, - /// A rank's expert ids (int32, E + 1): each id's place among its own, -1 for another rank's; zero on one rank. - remap: u64 = 0, - - /// Routed experts, the shared one not counted. - pub fn count(r: Routed) usize { - return r.rows - 1; - } -}; +/// A layer's experts and router rows (hip/moe.zig). +pub const Experts = hip.moe.Experts; +pub const Routed = hip.moe.Routed; pub const Mlp = union(enum) { dense: struct { gate: Projection, up: Projection, down: Projection }, diff --git a/zig/src/families/qwen3_5/hip.zig b/zig/src/families/qwen3_5/hip.zig index a6a583a4ba4..087a99a57f6 100644 --- a/zig/src/families/qwen3_5/hip.zig +++ b/zig/src/families/qwen3_5/hip.zig @@ -15,7 +15,7 @@ pub const pages = @import("backend/hip/forward/pages.zig"); pub const forward = @import("backend/hip/forward/forward.zig"); pub const window = @import("backend/hip/forward/window.zig"); pub const plan = @import("backend/hip/forward/plan.zig"); -pub const moe = @import("backend/hip/forward/moe.zig"); +pub const moe = @import("hip").moe; pub const sample = @import("backend/hip/engine/sample.zig"); pub const draw = @import("backend/hip/engine/draw.zig"); pub const bridge = @import("backend/hip/model/bridge.zig"); @@ -27,7 +27,7 @@ pub const hip_lanes = @import("backend/hip/engine/hip_lanes.zig"); pub const mtp = @import("backend/hip/engine/mtp.zig"); pub const worker = @import("backend/hip/engine/worker.zig"); pub const slicing = @import("weights/slicing.zig"); -pub const reduce = @import("backend/hip/forward/reduce.zig"); +pub const reduce = @import("hip").reduce; pub const native_engine = @import("backend/hip/engine/native.zig"); /// The registry entries of the native server: the dense and the sparse checkpoints. pub const native = native_engine.Native("qwen3_5"); diff --git a/zig/src/families/qwen3_5/backend/hip/forward/moe.zig b/zig/src/hip/moe.zig similarity index 72% rename from zig/src/families/qwen3_5/backend/hip/forward/moe.zig rename to zig/src/hip/moe.zig index 4825f72089c..628ffc14776 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/moe.zig +++ b/zig/src/hip/moe.zig @@ -1,11 +1,38 @@ //! The routed MoE of MLX affine experts: router, pick rule, plan, gate and up, activation, down, slots summed in order. const std = @import("std"); -const hip = @import("hip"); -const view = @import("../model/view.zig"); +const ops = @import("ops/ops.zig"); -const Ops = hip.ops.Ops; -const Tensor = hip.ops.Tensor; +const Ops = ops.Ops; +const Tensor = ops.Tensor; +const Kind = ops.Kind; +const Projection = ops.Projection; + +/// A layer's experts, shared expert last: gate and up stacked as one (E + 1, 2 NI, ...) weight, down (E + 1, D, ...). +pub const Experts = struct { + fused: Projection, + down: Projection, + count: usize, + width: usize, + dims: usize, + limit: f32 = 0, +}; + +/// The router's rows in fp32 (E + 1, D), the shared expert's gate last, and the experts. +pub const Routed = struct { + rows32: u64, + experts: Experts, + top_k: usize, + /// The router's rows, E + 1: the model's expert count, whatever share of the experts this rank holds. + rows: usize, + /// A rank's expert ids (int32, E + 1): each id's place among its own, -1 for another rank's; zero on one rank. + remap: u64 = 0, + + /// Routed experts, the shared one not counted. + pub fn count(r: Routed) usize { + return r.rows - 1; + } +}; /// experts.py: the decode tile's most rows, the GEMM tile's rows and where it starts, items' pair cap. const LANE_ROWS = 8; @@ -30,7 +57,7 @@ fn tileFor(o: Ops, rows: usize) usize { } /// `x` (rows, D) to (rows, D) in its dtype: the top-k experts plus the shared one; a tp rank returns its fp32 share. -pub fn run(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, prefill: bool) hip.ops.Error!Tensor { +pub fn run(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, prefill: bool) ops.Error!Tensor { _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tile comes from tile_for) const ex = r.experts; const slots = r.top_k + 1; @@ -54,8 +81,8 @@ pub fn run(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, try o.moeRoute(local, pairs, r.rows, tile, members, items, cap); try o.moeForeignItems(items, cap, ex.count); const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows)); - const act = try o.arena.take(pairs * ex.width * m.act.size()); - const act_t: Tensor = .{ .ptr = act, .kind = m.act }; + const act = try o.arena.take(pairs * ex.width * kind.size()); + const act_t: Tensor = .{ .ptr = act, .kind = kind }; try o.moeAct(both, act_t, pairs, ex.width, ex.limit); const y = try o.projectRouted(act_t, ex.down, items, count, members, pairs, 1, @min(tile, rows)); try o.moeZeroForeign(y, local, ex.count, pairs, ex.dims); @@ -63,16 +90,16 @@ pub fn run(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, try o.moeCombine(y, wts, .{ .ptr = share, .kind = .f32 }, rows, slots, ex.dims); return .{ .ptr = share, .kind = .f32 }; } - const p = try expertParts(o, m, r, x, rows, logits, pick, wts, items, members, cap); - const out = try o.arena.take(rows * ex.dims * m.act.size()); - try o.moeCombine(p.y, wts, .{ .ptr = out, .kind = m.act }, rows, slots, ex.dims); - return .{ .ptr = out, .kind = m.act }; + const p = try expertParts(o, kind, r, x, rows, logits, pick, wts, items, members, cap); + const out = try o.arena.take(rows * ex.dims * kind.size()); + try o.moeCombine(p.y, wts, .{ .ptr = out, .kind = kind }, rows, slots, ex.dims); + return .{ .ptr = out, .kind = kind }; } /// The routed slots a row (fp32) and their weights before the sum: a single rank only. pub const Parts = struct { y: u64, wts: u64, slots: usize }; -pub fn parts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize) hip.ops.Error!Parts { +pub fn parts(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize) ops.Error!Parts { const slots = r.top_k + 1; const size = bucket(rows); const cap = capacity(size * slots, r.rows); @@ -82,12 +109,12 @@ pub fn parts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usiz const items = try o.arena.of(i32, cap * 3); const members = try o.arena.of(i32, size * slots); try o.moeRouter(x, r.rows32, logits, rows, r.experts.dims, r.rows); - const p = try expertParts(o, m, r, x, rows, logits, pick, wts, items, members, cap); + const p = try expertParts(o, kind, r, x, rows, logits, pick, wts, items, members, cap); return .{ .y = p.y, .wts = wts, .slots = slots }; } /// Select, plan, gate and up, the activation and down: the rows' slots before the combine. -fn expertParts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: usize, logits: u64, pick: u64, wts: u64, items: u64, members: u64, cap: usize) hip.ops.Error!struct { y: u64 } { +fn expertParts(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, logits: u64, pick: u64, wts: u64, items: u64, members: u64, cap: usize) ops.Error!struct { y: u64 } { const ex = r.experts; const slots = r.top_k + 1; const pairs = rows * slots; @@ -105,8 +132,8 @@ fn expertParts(o: Ops, m: *const view.Model, r: view.Routed, x: Tensor, rows: us // the gate and up's activation is the launch's epilogue when the tile takes the shape const act_t: Tensor = if (try o.projectRoutedAct(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows), ex.limit)) |t| t else blk: { const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows)); - const act = try o.arena.take(pairs * ex.width * m.act.size()); - const t: Tensor = .{ .ptr = act, .kind = m.act }; + const act = try o.arena.take(pairs * ex.width * kind.size()); + const t: Tensor = .{ .ptr = act, .kind = kind }; try o.moeAct(both, t, pairs, ex.width, ex.limit); break :blk t; }; diff --git a/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig b/zig/src/hip/reduce.zig similarity index 69% rename from zig/src/families/qwen3_5/backend/hip/forward/reduce.zig rename to zig/src/hip/reduce.zig index 7e20ac30113..d763def2e37 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/reduce.zig +++ b/zig/src/hip/reduce.zig @@ -1,16 +1,16 @@ //! The tensor-parallel reduce: ranks' fp32 shares summed before each residual add, logits slices joined in rank order. const std = @import("std"); -const hip = @import("hip"); -const view = @import("../model/view.zig"); +const ops = @import("ops/ops.zig"); +const collective = @import("collective.zig"); -const Ops = hip.ops.Ops; -const Tensor = hip.ops.Tensor; +const Ops = ops.Ops; +const Tensor = ops.Tensor; -pub const Error = hip.ops.Error || hip.collective.Error; +pub const Error = ops.Error || collective.Error; /// `n` fp32 values summed over the ranks in rank order, so a row's sum does not depend on the rows sharing the call. -pub fn sum(o: Ops, c: hip.collective.Comm, y: u64, n: usize) Error!u64 { +pub fn sum(o: Ops, c: collective.Comm, y: u64, n: usize) Error!u64 { const out = try o.arena.of(f32, n); if (c.world == 2) { try c.allReduce(y, out, n, .f32, o.stream); @@ -25,14 +25,14 @@ pub fn sum(o: Ops, c: hip.collective.Comm, y: u64, n: usize) Error!u64 { } /// x += y on the residual rows: an activation-dtype `y` as one rank adds it, an fp32 share summed over the ranks first. -pub fn residual(o: Ops, m: *const view.Model, x: Tensor, y: Tensor, n: usize) Error!void { +pub fn residual(o: Ops, tp: ?collective.Comm, x: Tensor, y: Tensor, n: usize) Error!void { if (y.kind != .f32) return o.add(x, y, x, n); - const total = try sum(o, m.tp.?, y.ptr, n); + const total = try sum(o, tp.?, y.ptr, n); try o.addWide(x, total, x, n); } /// The ranks' logits slices (world, rows, width) of the activation dtype, gathered into `out`. -pub fn gather(o: Ops, c: hip.collective.Comm, slice: Tensor, out: u64, n: usize) Error!void { - const dtype: hip.collective.Dtype = if (slice.kind == .f16) .f16 else .bf16; +pub fn gather(o: Ops, c: collective.Comm, slice: Tensor, out: u64, n: usize) Error!void { + const dtype: collective.Dtype = if (slice.kind == .f16) .f16 else .bf16; try c.allGather(slice.ptr, out, n, dtype, o.stream); } diff --git a/zig/src/hip/root.zig b/zig/src/hip/root.zig index b47ff9dc83c..9c6614f2453 100644 --- a/zig/src/hip/root.zig +++ b/zig/src/hip/root.zig @@ -36,6 +36,8 @@ pub const Upload = @import("upload.zig").Upload; pub const quant = @import("core").quant; pub const registry = @import("core").registry; pub const collective = @import("collective.zig"); +pub const moe = @import("moe.zig"); +pub const reduce = @import("reduce.zig"); /// Joins this rank's tensor-parallel group: RCCL's (comm/), behind collective.zig. pub const joinGroup = @import("comm/group.zig").join; @@ -45,6 +47,8 @@ test { _ = Device; _ = collective; _ = graph_cache; + _ = moe; + _ = reduce; _ = @import("comm/rccl.zig"); _ = @import("comm/link.zig"); _ = @import("comm/group.zig"); From a3f02b34f095ad92b28f313e3e81b6b4a7da911f Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:17:08 +0200 Subject: [PATCH 34/52] feat(flashnext): native HIP routing for qwen4_exp behind admission: format, tensors and a rank's bytes The family's HIP module (families/flashnext/hip.zig) reads the family's config and index checks. Its plan counts a rank's weights as tensor parallelism splits them (routed experts by rank, heads, value heads and the head's vocabulary rows; hyper-connections, routers and indexers on every rank; the n-gram tables in host memory), a position's keys and a stream's state, and matches the published 3-, 4- and 6-bit checkpoints' text bytes exactly. The server routes qwen4_exp to it; it refuses what does not fit with the window that would, and refuses the rest until the forward lands. --- zig/build/hip.zig | 14 +- zig/src/families/flashnext/hip.zig | 15 ++ zig/src/families/flashnext/hip/native.zig | 142 ++++++++++++++++++ zig/src/families/flashnext/hip/plan.zig | 174 ++++++++++++++++++++++ zig/src/native/hip.zig | 4 +- 5 files changed, 345 insertions(+), 4 deletions(-) create mode 100644 zig/src/families/flashnext/hip.zig create mode 100644 zig/src/families/flashnext/hip/native.zig create mode 100644 zig/src/families/flashnext/hip/plan.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index bed0c9257b5..81c89004d57 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -89,6 +89,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil const host = engineModules(b, b.graph.host, .Debug, stub_kernels, null); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.hip })).step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.family })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.flashnext })).step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve })).step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native })).step); // the GPU programs compile on any host against stub kernels, so `test` catches what only they reach @@ -111,7 +112,7 @@ fn checksExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil }) }); } -const Engine = struct { hip: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, serve: *std.Build.Module, family: *std.Build.Module, native: *std.Build.Module }; +const Engine = struct { hip: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, serve: *std.Build.Module, family: *std.Build.Module, flashnext: *std.Build.Module, native: *std.Build.Module }; /// The HIP backend, the Qwen3.5 family over it and the native engines, on `kernels` (a stub on the host). fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, kernels: *std.Build.Module, hip_include: ?[]const u8) Engine { @@ -140,14 +141,21 @@ fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. .link_libc = true, .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "core", .module = core }, .{ .name = "lanes", .module = lanes }, .{ .name = "engine_api", .module = api }, .{ .name = "hip_serve", .module = serve } }, }); + const flashnext = b.createModule(.{ + .root_source_file = b.path("zig/src/families/flashnext/hip.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "lanes", .module = lanes } }, + }); const native = b.createModule(.{ .root_source_file = b.path("zig/src/native/hip.zig"), .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "qwen3_5", .module = family } }, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "qwen3_5", .module = family }, .{ .name = "flashnext", .module = flashnext } }, }); - return .{ .hip = hip, .lanes = lanes, .api = api, .serve = serve, .family = family, .native = native }; + return .{ .hip = hip, .lanes = lanes, .api = api, .serve = serve, .family = family, .flashnext = flashnext, .native = native }; } /// The server over the HIP engines, as the CUDA build makes it: the HTTP side keeps its safety checks. diff --git a/zig/src/families/flashnext/hip.zig b/zig/src/families/flashnext/hip.zig new file mode 100644 index 00000000000..8d293b01cd2 --- /dev/null +++ b/zig/src/families/flashnext/hip.zig @@ -0,0 +1,15 @@ +//! Qwen3.8 Flash Next for the native HIP engine: the family's config and index checks, the plan of a rank's bytes. +pub const config = @import("config.zig"); +pub const Config = config.Config; +pub const index = @import("index.zig"); +pub const Spec = @import("spec.zig").Spec; +pub const plan = @import("hip/plan.zig"); +/// The registry entry of the native server. +pub const native = @import("hip/native.zig"); + +test { + _ = config; + _ = index; + _ = plan; + _ = native; +} diff --git a/zig/src/families/flashnext/hip/native.zig b/zig/src/families/flashnext/hip/native.zig new file mode 100644 index 00000000000..1718e0a5c96 --- /dev/null +++ b/zig/src/families/flashnext/hip/native.zig @@ -0,0 +1,142 @@ +//! Flash Next for the native server on HIP: the checkpoint and its rank's bytes admitted before anything loads. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const config = @import("../config.zig"); +const index = @import("../index.zig"); +const plan = @import("plan.zig"); +const Spec = @import("../spec.zig").Spec; + +pub const model_type = "qwen4_exp"; +/// The MLX affine checkpoints the plan admits; the HIP products read 2- to 8-bit codes in groups of 32 to 128. +pub const formats: []const []const u8 = &.{ "mlx-q3g32", "mlx-q4g32", "mlx-q6g32" }; +/// Positions a stream holds when neither --context nor the checkpoint's config names a window. +pub const default_context: i64 = 32768; +/// The engine cuts prompts itself. +pub const prefill_step: u32 = 0; +/// Device bytes a rank keeps for the forward's scratch until the engine counts its own. +pub const scratch_bytes: u64 = 2 << 30; + +/// What the native server drives, as the other HIP families hand it over. +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + streams: usize, + startup: []const u8, +}; + +pub const Refused = error{Refused}; + +fn refuse(a: std.mem.Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) Refused { + problem.* = std.fmt.allocPrint(a, fmt, args) catch fmt; + return error.Refused; +} + +fn gibs(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +/// The checkpoint's verdict: its format and tensors, and whether a rank's share and one stream fit `room`. +pub const Verdict = struct { + spec: Spec, + weights: u64, + host: u64, + /// The longest window one stream may hold beside the weights and scratch. + most: u64, + fits: bool, +}; + +/// Admits `c` with the index text `index_json` on rank `rank` of `world` at `window` positions in `room` bytes. +pub fn admit(a: std.mem.Allocator, gpa: std.mem.Allocator, c: *const config.Config, index_json: []const u8, world: u32, rank: u32, window: u64, room: u64, problem: *[]const u8) Refused!Verdict { + const spec = c.global_affine; + if (spec.group != 32) return refuse(a, problem, "Flash Next on HIP reads group-32 MLX affine checkpoints; this one has groups of {d}", .{spec.group}); + _ = index.admit(gpa, index_json, c) catch |err| return refuse(a, problem, "the checkpoint's index lacks a Flash Next tensor ({s})", .{@errorName(err)}); + const w = plan.weights(c, spec, world) catch |err| return refuse(a, problem, "--tp {d} does not split Flash Next's heads, experts and vocabulary evenly ({s})", .{ world, @errorName(err) }); + const token = plan.tokenBytes(c, world, 2) catch return refuse(a, problem, "Flash Next's layer types are unreadable", .{}); + const stream = plan.streamBytes(c, world) catch return refuse(a, problem, "Flash Next's DeltaNet heads do not split over --tp {d}", .{world}); + const most = plan.Fit.window(room, w.device(rank), scratch_bytes, token, stream); + return .{ .spec = spec, .weights = w.device(rank), .host = w.host, .most = most, .fits = most >= window }; +} + +fn readIndex(a: std.mem.Allocator, io: std.Io, dir: []const u8) ![]u8 { + const path = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); + return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 26)); +} + +/// The bytes this rank's card grants a plan. +fn cardRoom(gpa: std.mem.Allocator, io: std.Io, dev: hip.Device) !u64 { + var r = try hip.Runtime.open(); + defer r.close(); + var ctx = try hip.Context.init(&r, dev.index); + defer ctx.deinit(); + const pool = try hip.admission.budget(gpa, io, ctx); + return pool.room(hip.usage(false).device); +} + +/// Admission, then the refusal that stands until the forward lands: the server says what fits and why it stops. +fn check(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) Refused { + var c = config.Config.read(gpa, io, dir) catch |err| return refuse(a, problem, "{s} is not a Flash Next checkpoint the HIP engine reads ({s})", .{ dir, @errorName(err) }); + defer c.deinit(); + const text = readIndex(a, io, dir) catch |err| return refuse(a, problem, "cannot read {s}/model.safetensors.index.json ({s})", .{ dir, @errorName(err) }); + const bytes = cardRoom(gpa, io, dev) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)}); + const v = admit(a, gpa, &c, text, o.world, o.rank, o.window, bytes, problem) catch |err| return err; + if (!v.fits) return refuse(a, problem, "Flash Next {d}-bit on {d} rank(s) holds {d:.2} GiB of weights a rank ({d:.1} GiB of n-gram tables in host memory); {d:.2} GiB is left for a {d}-token window, which allows {d} tokens: lower --context, add ranks (--tp), or use a lower-bit checkpoint", .{ v.spec.bits, o.world, gibs(v.weights), gibs(v.host), gibs(bytes -| v.weights), o.window, v.most }); + return refuse(a, problem, "Flash Next {d}-bit fits rank {d} of {d} ({d:.2} GiB of weights, windows up to {d} tokens), but the HIP forward is not in this build yet", .{ v.spec.bits, o.rank, o.world, gibs(v.weights), v.most }); +} + +/// The engine for `dir` on `dev`; under tensor parallelism this is rank 0, which serves. +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) anyerror!Loaded { + return check(a, gpa, io, dev, dir, o, problem); +} + +/// A rank above 0: holds its share of the model and runs rank 0's steps until rank 0 stops. +pub fn follow(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) anyerror!void { + return check(a, gpa, io, dev, dir, o, problem); +} + +const gib: u64 = 1 << 30; + +fn fixture(bits: u8) !config.Config { + var buf: [16]u8 = undefined; + const text = try std.mem.replaceOwned(u8, std.testing.allocator, @embedFile("../fixtures/config.json"), "\"bits\": 6", try std.fmt.bufPrint(&buf, "\"bits\": {d}", .{bits})); + defer std.testing.allocator.free(text); + return config.parse(std.testing.allocator, text); +} + +test "admission: the 4-bit checkpoint on four V620s takes the model's window, on one it is refused with a reason" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var c = try fixture(4); + defer c.deinit(); + const idx = @embedFile("../fixtures/index.json"); + var problem: []const u8 = ""; + const four = try admit(a, std.testing.allocator, &c, idx, 4, 0, 262144, 28 * gib, &problem); + try std.testing.expect(four.fits and four.most >= 262144); + const one = try admit(a, std.testing.allocator, &c, idx, 1, 0, 4096, 28 * gib, &problem); + try std.testing.expect(!one.fits and one.most == 0); + try std.testing.expectError(error.Refused, admit(a, std.testing.allocator, &c, idx, 3, 0, 4096, 28 * gib, &problem)); + try std.testing.expect(std.mem.indexOf(u8, problem, "--tp 3") != null); + try std.testing.expectError(error.Refused, admit(a, std.testing.allocator, &c, "{\"weight_map\": {\"x\": \"a.safetensors\"}}", 4, 0, 4096, 28 * gib, &problem)); + try std.testing.expect(std.mem.indexOf(u8, problem, "lacks") != null); +} + +test "admission: on two W7800s the 3-bit checkpoint takes the model's window and the 4-bit one a shorter window" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const idx = @embedFile("../fixtures/index.json"); + var problem: []const u8 = ""; + var q3 = try fixture(3); + defer q3.deinit(); + var q4 = try fixture(4); + defer q4.deinit(); + const three = try admit(a, std.testing.allocator, &q3, idx, 2, 0, 262144, 43 * gib, &problem); + const four = try admit(a, std.testing.allocator, &q4, idx, 2, 0, 262144, 43 * gib, &problem); + try std.testing.expect(three.fits); + try std.testing.expect(!four.fits and four.most >= 65536); + try std.testing.expect(four.weights > three.weights and four.host > three.host); +} diff --git a/zig/src/families/flashnext/hip/plan.zig b/zig/src/families/flashnext/hip/plan.zig new file mode 100644 index 00000000000..1289a1df70c --- /dev/null +++ b/zig/src/families/flashnext/hip/plan.zig @@ -0,0 +1,174 @@ +//! Flash Next's bytes on one HIP rank: the weights as tensor parallelism splits them, a token's keys, a stream's state. +const std = @import("std"); +const config = @import("../config.zig"); +const Spec = @import("../spec.zig").Spec; +const Config = config.Config; + +/// Where a checkpoint's text weights live on a rank of `world`. +pub const Weights = struct { + /// On every rank: hyper-connections, routers, the embedding, indexers, the PLE projections, norms. + replicated: u64 = 0, + /// This rank's share: routed experts by rank, heads and value heads, the vocabulary rows of the head. + split: u64 = 0, + /// Rank 0 alone: the shared experts. + shared: u64 = 0, + /// The n-gram tables, read from host memory a few rows a token. + host: u64 = 0, + + pub fn device(w: Weights, rank: u32) u64 { + return w.replicated + w.split + if (rank == 0) w.shared else 0; + } + + pub fn total(w: Weights, world: u32) u64 { + return w.replicated + w.split * world + w.shared + w.host; + } +}; + +/// Bytes of an MLX affine matrix: packed codes, then a bf16 scale and bias a group. +fn affine(s: Spec, n: u64, k: u64) u64 { + return n * k * s.bits / 8 + 4 * n * (k / s.group); +} + +const bf16 = 2; + +fn even(n: u64, world: u32) !u64 { + if (n % world != 0) return error.UnevenSplit; + return n / world; +} + +/// One decoder layer's bytes; `kind` names its mixer, as the config's layer types do. +fn layer(c: *const Config, s: Spec, kind: config.Kind, world: u32, w: *Weights) !void { + const d: u64 = c.hidden; + const wide: u64 = try c.wide(); + for (0..2) |_| w.replicated += 2 * affine(s, c.hc_lowrank, wide) + affine(s, c.hc_count, wide) + wide * bf16; + w.replicated += c.experts * d * bf16; // the router is stored in bf16 + w.shared += 3 * affine(s, c.shared_width, d) + affine(s, 1, d); + w.split += try even(c.experts, world) * 3 * affine(s, c.expert_width, d); + if (kind == .linear_attention) { + const keys: u64 = try c.keyWidth(); + const values: u64 = try c.valueWidth(); + const heads = try even(c.value_heads, world); + _ = try even(c.key_heads, world); + const conv = (2 * keys + values) / world; + w.split += affine(s, conv, d) + affine(s, values / world, d) + 2 * affine(s, heads, d) + affine(s, d, values / world); + w.split += conv * c.conv * bf16 + 2 * heads * bf16; + w.replicated += c.value_dim * bf16; + } else { + const hd: u64 = c.head_dim; + const heads = try even(c.heads, world); + const kv: u64 = c.kv_heads / @min(world, c.kv_heads); + w.split += affine(s, 2 * heads * hd, d) + affine(s, d, heads * hd) + 2 * affine(s, kv * hd, d); + w.replicated += affine(s, (c.index_heads + c.index_kv_heads) * c.index_dim, d) + 2 * hd * bf16 + 2 * c.index_dim * bf16; + } +} + +/// The weights of `c` with every matrix at `s` on one rank of `world` (none of the vision tower). +pub fn weights(c: *const Config, s: Spec, world: u32) !Weights { + var w: Weights = .{}; + const d: u64 = c.hidden; + const wide: u64 = try c.wide(); + w.replicated += affine(s, c.vocab, d) + 2 * affine(s, c.hc_lowrank, wide) + wide * bf16; + w.split += affine(s, try even(c.vocab, world), d); + for (0..c.layers) |i| { + try layer(c, s, try c.kind(i), world, &w); + if (!c.ple[i]) continue; + const heads: u64 = try c.ngramHeadCount(); + w.replicated += affine(s, wide, c.ple_dim) + affine(s, d, c.ple_dim) + 3 * wide * bf16 + wide * c.ple_conv * bf16 + (3 + 2 * heads) * 8; + w.host += c.ngram_shards * affine(s, try tableRows(c), c.ple_dim / heads); + } + if (c.mtp.layers > 0) { + w.replicated += 2 * affine(s, d, d) + (d + wide) * bf16 + 2 * affine(s, c.hc_lowrank, wide) + wide * bf16; + for (c.mtp.kinds[0..c.mtp.layers]) |kind| try layer(c, s, kind, world, &w); + } + return w; +} + +/// Rows of one n-gram table shard: the heads' prime table sizes, together, cut in `ngram_shards` equal parts. +pub fn tableRows(c: *const Config) !u64 { + const ref = try config.pleRef(c); + var rows: u64 = 0; + for (ref.sizes) |n| rows += @intCast(n); + return std.math.divCeil(u64, rows, c.ngram_shards); +} + +/// A position's cache bytes on one rank: keys and values (kv_dtype bytes), the indexer's raw and pooled keys (bf16). +pub fn tokenBytes(c: *const Config, world: u32, kv_dtype: u64) !u64 { + var layers: u64 = c.mtp.layers; + for (0..c.layers) |i| layers += @intFromBool(try c.kind(i) == .sparse_attention); + const kv: u64 = c.kv_heads / @min(world, c.kv_heads); + const index: u64 = c.index_kv_heads * c.index_dim * bf16; + return layers * (2 * kv * c.head_dim * kv_dtype + index + index / c.index_ratio); +} + +/// A stream's state on one rank: the DeltaNet recurrences (fp32) and conv tails, the PLE conv tail and history. +pub fn streamBytes(c: *const Config, world: u32) !u64 { + var linear: u64 = 0; + for (0..c.layers) |i| linear += @intFromBool(try c.kind(i) == .linear_attention); + const heads = try even(c.value_heads, world); + const conv: u64 = (try c.convWidth()) / world; + const ple: u64 = c.ple_count * c.ngram * (c.ple_conv - 1) * (try c.wide()) * bf16; + return linear * (heads * c.key_dim * c.value_dim * 4 + (c.conv - 1) * conv * bf16) + ple; +} + +/// What a rank needs at `window` positions for `streams` streams, past its weights and `scratch`, against `room`. +pub const Fit = struct { + weights: u64, + lanes: u64, + room: u64, + + pub fn fits(f: Fit) bool { + return f.weights + f.lanes <= f.room; + } + + /// Positions one stream may hold in what the weights and `scratch` leave of `room`, or 0. + pub fn window(room: u64, weights_bytes: u64, scratch: u64, token: u64, stream: u64) u64 { + const fixed = weights_bytes + scratch + stream; + return if (fixed >= room) 0 else (room - fixed) / token; + } +}; + +pub fn fit(c: *const Config, s: Spec, world: u32, rank: u32, window: u64, streams: u64, scratch: u64, room: u64) !Fit { + const w = try weights(c, s, world); + const lanes = streams * (window * try tokenBytes(c, world, bf16) + try streamBytes(c, world)) + scratch; + return .{ .weights = w.device(rank), .lanes = lanes, .room = room }; +} + +test "the plan counts every text byte of the 3-, 4- and 6-bit checkpoints, and splits them without loss" { + const fixture = @embedFile("../fixtures/config.json"); + // the published checkpoints' safetensors headers, less the vision tower + const totals = [_]struct { bits: []const u8, bytes: u64 }{ .{ .bits = "6", .bytes = 157182349016 }, .{ .bits = "4", .bytes = 112311293016 }, .{ .bits = "3", .bytes = 89875765016 } }; + for (totals) |t| { + var buf: [16]u8 = undefined; + const text = try std.mem.replaceOwned(u8, std.testing.allocator, fixture, "\"bits\": 6", try std.fmt.bufPrint(&buf, "\"bits\": {s}", .{t.bits})); + defer std.testing.allocator.free(text); + var c = try config.parse(std.testing.allocator, text); + defer c.deinit(); + const one = try weights(&c, c.global_affine, 1); + try std.testing.expectEqual(t.bytes, one.total(1)); + for ([_]u32{ 2, 4 }) |world| { + const w = try weights(&c, c.global_affine, world); + try std.testing.expectEqual(one.host, w.host); + try std.testing.expectEqual(one.shared, w.shared); + try std.testing.expect(w.total(world) >= one.total(1)); // replicated parts add, nothing is lost + } + } +} + +test "a 4-bit checkpoint fits four 30 GiB cards at the model's window; 4-bit on two 45 GiB cards leaves a shorter one" { + var c = try config.parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + const q4 = try Spec.init(4, 32); + const q3 = try Spec.init(3, 32); + const gib: u64 = 1 << 30; + const v620: u64 = 28 * gib; // a V620's free memory less its reserve, near enough + const w7800: u64 = 43 * gib; + try std.testing.expect((try fit(&c, q4, 4, 0, 262144, 1, 2 * gib, v620)).fits()); + try std.testing.expect(!(try fit(&c, q4, 1, 0, 4096, 1, 2 * gib, v620)).fits()); + try std.testing.expect(!(try fit(&c, q4, 2, 0, 262144, 1, 2 * gib, w7800)).fits()); + try std.testing.expect((try fit(&c, q4, 2, 0, 65536, 1, 2 * gib, w7800)).fits()); + try std.testing.expect((try fit(&c, q3, 2, 0, 262144, 1, 2 * gib, w7800)).fits()); + try std.testing.expectError(error.UnevenSplit, weights(&c, q4, 3)); + // the KV and indexer bytes of a position: 13 attention layers (12 and the MTP head's), one kv head a rank past one + try std.testing.expectEqual(@as(u64, 13 * (2 * 2 * 256 * 2 + 256 + 64)), try tokenBytes(&c, 1, 2)); + try std.testing.expectEqual(@as(u64, 13 * (2 * 1 * 256 * 2 + 256 + 64)), try tokenBytes(&c, 4, 2)); +} diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index df7134eee2b..1a0223850a7 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -5,12 +5,13 @@ const hip = @import("hip"); const api = @import("engine_api"); const lanes = @import("lanes"); const qwen35 = @import("qwen3_5"); +const flashnext = @import("flashnext"); const Allocator = std.mem.Allocator; const admission = hip.admission; const modelContext = admission.modelContext; /// The HIP families: namespaces with `model_type`, `formats`, `default_context`, `prefill_step`, `open` and `follow`. -const registry = .{ qwen35.native, qwen35.native_moe }; +const registry = .{ qwen35.native, qwen35.native_moe, flashnext.native }; pub const backends: []const []const u8 = &.{"hip"}; /// No per-thread alternate signal stack: its thread-local leaves RCCL's and HIP's threads too little stack to start. @@ -214,6 +215,7 @@ test "every registered family is listed for capabilities" { try std.testing.expectEqual(@as(usize, registry.len), families.len); try std.testing.expectEqualStrings("qwen3_5", families[0].model_type); try std.testing.expectEqualStrings("qwen3_5_moe", families[1].model_type); + try std.testing.expectEqualStrings("qwen4_exp", families[2].model_type); } test "the group flags: one rank source, a supported world, a master past one rank, a rank inside the world" { From 6be673363e9069bd95136d750d8daed4dad29377 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:22:37 +0200 Subject: [PATCH 35/52] refactor(hip): the token draw from logits rows in hip_serve, a module every HIP family imports Qwen3.5's Drawer (argmax for greedy rows, top_k + margin candidates for sampled ones, whole rows for grammar masks and kept prompt rows) and its keyed sampling move unchanged from the family's engine into zig/src/hip_serve, a module over hip and the lane core. Qwen3.5 imports it; Flash Next's HIP lanes will draw the same way, structured output included. --- zig/build/hip.zig | 14 +++++++++++--- .../families/qwen3_5/backend/hip/engine/engine.zig | 4 ++-- .../qwen3_5/backend/hip/engine/hip_costs.zig | 2 +- .../qwen3_5/backend/hip/engine/hip_lanes.zig | 2 +- .../families/qwen3_5/backend/hip/engine/mtp.zig | 2 +- .../families/qwen3_5/backend/hip/engine/round.zig | 2 +- .../families/qwen3_5/backend/hip/engine/worker.zig | 2 +- zig/src/families/qwen3_5/hip.zig | 4 ++-- .../backend/hip/engine => hip_serve}/draw.zig | 0 .../backend/hip/engine => hip_serve}/sample.zig | 0 zig/src/hip_serve/serve.zig | 8 ++++++++ 11 files changed, 28 insertions(+), 12 deletions(-) rename zig/src/{families/qwen3_5/backend/hip/engine => hip_serve}/draw.zig (100%) rename zig/src/{families/qwen3_5/backend/hip/engine => hip_serve}/sample.zig (100%) create mode 100644 zig/src/hip_serve/serve.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 4d3a6233137..614fb0bdf60 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -89,6 +89,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil const host = engineModules(b, b.graph.host, .Debug, stub_kernels, null); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.hip })).step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.family })).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve })).step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native })).step); // the GPU programs compile on any host against stub kernels, so `test` catches what only they reach test_step.dependOn(&checksExe(b, b.graph.host, .Debug, host).step); @@ -110,7 +111,7 @@ fn checksExe(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil }) }); } -const Engine = struct { hip: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, family: *std.Build.Module, native: *std.Build.Module }; +const Engine = struct { hip: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module, serve: *std.Build.Module, family: *std.Build.Module, native: *std.Build.Module }; /// The HIP backend, the Qwen3.5 family over it and the native engines, on `kernels` (a stub on the host). fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, kernels: *std.Build.Module, hip_include: ?[]const u8) Engine { @@ -125,12 +126,19 @@ fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. } const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const serve = b.createModule(.{ + .root_source_file = b.path("zig/src/hip_serve/serve.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "lanes", .module = lanes } }, + }); const family = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/hip.zig"), .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "core", .module = core }, .{ .name = "lanes", .module = lanes }, .{ .name = "engine_api", .module = api } }, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "core", .module = core }, .{ .name = "lanes", .module = lanes }, .{ .name = "engine_api", .module = api }, .{ .name = "hip_serve", .module = serve } }, }); const native = b.createModule(.{ .root_source_file = b.path("zig/src/native/hip.zig"), @@ -139,7 +147,7 @@ fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. .link_libc = true, .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "qwen3_5", .module = family } }, }); - return .{ .hip = hip, .lanes = lanes, .api = api, .family = family, .native = native }; + return .{ .hip = hip, .lanes = lanes, .api = api, .serve = serve, .family = family, .native = native }; } /// The server over the HIP engines, as the CUDA build makes it: the HTTP side keeps its safety checks. diff --git a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig index 13e2ac9e803..fb9d16637db 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/engine.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/engine.zig @@ -8,9 +8,9 @@ const pages = @import("../forward/pages.zig"); const fwd = @import("../forward/forward.zig"); const weights = @import("../model/weights.zig"); const bridge = @import("../model/bridge.zig"); -const sample = @import("sample.zig"); +const sample = @import("hip_serve").sample; const memory = @import("memory.zig"); -const draw = @import("draw.zig"); +const draw = @import("hip_serve").draw; const slicing = @import("../../../weights/slicing.zig"); const reduce = hip.reduce; const round_graphs = @import("round_graphs.zig"); diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig index c40170a2694..0fd6318a3ce 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_costs.zig @@ -5,7 +5,7 @@ const hip = @import("hip"); const lanes = @import("lanes"); const Engine = @import("engine.zig").Engine; const state = @import("../forward/state.zig"); -const draw = @import("draw.zig"); +const draw = @import("hip_serve").draw; const mtp = @import("mtp.zig"); const Cost = lanes.config.Cost; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig index bed4ee92d07..f2501325300 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig @@ -5,7 +5,7 @@ const hip = @import("hip"); const lanes = @import("lanes"); const Engine = @import("engine.zig").Engine; const state = @import("../forward/state.zig"); -const draw = @import("draw.zig"); +const draw = @import("hip_serve").draw; const mtp = @import("mtp.zig"); const costs = @import("hip_costs.zig"); const prefix = @import("prefix.zig"); diff --git a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig index 2dcd8caeba6..6faf58b864b 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/mtp.zig @@ -7,7 +7,7 @@ const view = @import("../model/view.zig"); const weights = @import("../model/weights.zig"); const bridge = @import("../model/bridge.zig"); const fwd = @import("../forward/forward.zig"); -const draw = @import("draw.zig"); +const draw = @import("hip_serve").draw; const plan = @import("../forward/plan.zig"); const graph_cache = hip.graph_cache; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/round.zig b/zig/src/families/qwen3_5/backend/hip/engine/round.zig index 53d3d237017..5bfcc60b84a 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/round.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/round.zig @@ -7,7 +7,7 @@ const win = @import("../forward/window.zig"); const fwd = @import("../forward/forward.zig"); const plan = @import("../forward/plan.zig"); const view = @import("../model/view.zig"); -const draw = @import("draw.zig"); +const draw = @import("hip_serve").draw; const round_graphs = @import("round_graphs.zig"); const Engine = @import("engine.zig").Engine; diff --git a/zig/src/families/qwen3_5/backend/hip/engine/worker.zig b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig index b390ca80442..d0f0fb963f0 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/worker.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/worker.zig @@ -5,7 +5,7 @@ const hip = @import("hip"); const Engine = @import("engine.zig").Engine; const Pick = @import("engine.zig").Pick; const state = @import("../forward/state.zig"); -const draw = @import("draw.zig"); +const draw = @import("hip_serve").draw; /// A message's first word: rank 0 decides every match, eviction, page and slot, and a rank only applies it. pub const Op = enum(u32) { stop, prefill, verify, keep, release, fill, pages, snap, copy }; diff --git a/zig/src/families/qwen3_5/hip.zig b/zig/src/families/qwen3_5/hip.zig index 087a99a57f6..63b4fd93080 100644 --- a/zig/src/families/qwen3_5/hip.zig +++ b/zig/src/families/qwen3_5/hip.zig @@ -16,8 +16,8 @@ pub const forward = @import("backend/hip/forward/forward.zig"); pub const window = @import("backend/hip/forward/window.zig"); pub const plan = @import("backend/hip/forward/plan.zig"); pub const moe = @import("hip").moe; -pub const sample = @import("backend/hip/engine/sample.zig"); -pub const draw = @import("backend/hip/engine/draw.zig"); +pub const sample = @import("hip_serve").sample; +pub const draw = @import("hip_serve").draw; pub const bridge = @import("backend/hip/model/bridge.zig"); pub const engine = @import("backend/hip/engine/engine.zig"); pub const memory = @import("backend/hip/engine/memory.zig"); diff --git a/zig/src/families/qwen3_5/backend/hip/engine/draw.zig b/zig/src/hip_serve/draw.zig similarity index 100% rename from zig/src/families/qwen3_5/backend/hip/engine/draw.zig rename to zig/src/hip_serve/draw.zig diff --git a/zig/src/families/qwen3_5/backend/hip/engine/sample.zig b/zig/src/hip_serve/sample.zig similarity index 100% rename from zig/src/families/qwen3_5/backend/hip/engine/sample.zig rename to zig/src/hip_serve/sample.zig diff --git a/zig/src/hip_serve/serve.zig b/zig/src/hip_serve/serve.zig new file mode 100644 index 00000000000..fc348f1e9ad --- /dev/null +++ b/zig/src/hip_serve/serve.zig @@ -0,0 +1,8 @@ +//! What every HIP family's lane backend shares beside the kernels: tokens drawn from logits rows, greedy or keyed. +pub const draw = @import("draw.zig"); +pub const sample = @import("sample.zig"); + +test { + _ = draw; + _ = sample; +} From fd3baad5bcb151b9e180d058993cd2a7d177e38c Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:48:26 +0200 Subject: [PATCH 36/52] perf(hip): the MoE route's expert starts and tile ends by a block scan, not one thread tf_moe_route laid out each expert's members and tiles after thread 0 summed the counts of every expert in turn: at 513 experts (Flash Next's 512 and a shared one) that loop was most of the launch's 32 us a decode step, 48 times a token. The block now scans each thread's run of experts; the starts and ends are the same integers. The route test adds 513 experts at one decode row's 11 pairs and at a prompt's 2,816. --- zig/kernels/hip/ops/moe.hpp | 34 ++++++++++++++++++++++++-------- zig/src/hip/kernel_tests/ops.zig | 2 +- zig/src/hip/launches/moe.zig | 5 ++++- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/zig/kernels/hip/ops/moe.hpp b/zig/kernels/hip/ops/moe.hpp index 885f8881021..3d723ddafd0 100644 --- a/zig/kernels/hip/ops/moe.hpp +++ b/zig/kernels/hip/ops/moe.hpp @@ -34,14 +34,32 @@ extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts 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; - } + // starts: the counts' exclusive sums; ends: the tiles' inclusive sums; a thread's experts, then the block's scan + int* scan_c = reinterpret_cast(seg + segs * experts + (segs * experts) % 2); + int* scan_n = scan_c + blockDim.x; + const int per = (experts + blockDim.x - 1) / blockDim.x; + const int lo = min(experts, t * per), hi = min(experts, lo + per); + int own_c = 0, own_n = 0; + for (int e = lo; e < hi; ++e) { + own_c += counts[e]; + own_n += (counts[e] + tile - 1) / tile; + } + scan_c[t] = own_c; + scan_n[t] = own_n; + __syncthreads(); + for (int off = 1; off < static_cast(blockDim.x); off <<= 1) { + const int vc = t >= off ? scan_c[t - off] : 0, vn = t >= off ? scan_n[t - off] : 0; + __syncthreads(); + scan_c[t] += vc; + scan_n[t] += vn; + __syncthreads(); + } + int start = scan_c[t] - own_c, end = scan_n[t] - own_n; + for (int e = lo; e < hi; ++e) { + starts[e] = start; + start += counts[e]; + end += (counts[e] + tile - 1) / tile; + ends[e] = end; } __syncthreads(); if (t < segs) { diff --git a/zig/src/hip/kernel_tests/ops.zig b/zig/src/hip/kernel_tests/ops.zig index 3556bbb1387..90745fcc768 100644 --- a/zig/src/hip/kernel_tests/ops.zig +++ b/zig/src/hip/kernel_tests/ops.zig @@ -181,7 +181,7 @@ test "the MoE route sorts pairs by expert, stably, into items of at most a tile" 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| { + for ([_][3]usize{ .{ 257, 512, 16 }, .{ 128, 37, 4 }, .{ 64, 1000, 64 }, .{ 513, 11, 8 }, .{ 513, 2816, 8 } }) |shape| { const experts = shape[0]; const pairs = shape[1]; const tile = shape[2]; diff --git a/zig/src/hip/launches/moe.zig b/zig/src/hip/launches/moe.zig index c998a43b094..86411c0a383 100644 --- a/zig/src/hip/launches/moe.zig +++ b/zig/src/hip/launches/moe.zig @@ -1,5 +1,6 @@ //! MoE launches: router, select, plan, activation and combine. +const std = @import("std"); const Launcher = @import("../launches.zig").Launcher; const util = @import("util.zig"); const S = util.S; @@ -118,5 +119,7 @@ pub fn tf_moe_route(l: *const Launcher, picks: CI, pairs: c_int, experts: c_int, 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); + // and the block's scan of two ints a thread, past the segments (4-byte aligned) + const seg_bytes = std.mem.alignForward(usize, segs * ex * 2, 4); + try l.go(l.op.moe_route, dim(1, 1, 1), dim(256, 1, 1), @intCast(3 * ex * 4 + seg_bytes + 2 * 256 * 4), s, &a); } From 6c8c96d5f478f497f26c347aa5ba80c3f8384d13 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:48:35 +0200 Subject: [PATCH 37/52] feat(hip): Flash Next's kernels: residual streams and their tp sums, n-gram rows, the indexer and sparse attention --- zig/build/hip.zig | 17 +- zig/kernels/hip/flashnext/flashnext.hip | 6 + zig/kernels/hip/flashnext/indexer.hpp | 181 ++++++++++ zig/kernels/hip/flashnext/ngram.hpp | 40 +++ zig/kernels/hip/flashnext/sparse.hpp | 139 ++++++++ zig/kernels/hip/flashnext/streams.hpp | 184 ++++++++++ zig/src/hip/kernel_tests.zig | 2 + zig/src/hip/kernel_tests/flashnext.zig | 363 ++++++++++++++++++++ zig/src/hip/kernel_tests/flashnext_attn.zig | 293 ++++++++++++++++ zig/src/hip/kernels.zig | 2 +- zig/src/hip/launches.zig | 17 + zig/src/hip/launches/flashnext.zig | 157 +++++++++ 12 files changed, 1392 insertions(+), 9 deletions(-) create mode 100644 zig/kernels/hip/flashnext/flashnext.hip create mode 100644 zig/kernels/hip/flashnext/indexer.hpp create mode 100644 zig/kernels/hip/flashnext/ngram.hpp create mode 100644 zig/kernels/hip/flashnext/sparse.hpp create mode 100644 zig/kernels/hip/flashnext/streams.hpp create mode 100644 zig/src/hip/kernel_tests/flashnext.zig create mode 100644 zig/src/hip/kernel_tests/flashnext_attn.zig create mode 100644 zig/src/hip/launches/flashnext.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 614fb0bdf60..bed0c9257b5 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -168,22 +168,23 @@ fn server(b: *std.Build, target: std.Build.ResolvedTarget, e: Engine, build_opti } /// 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", "recurrence/gdn_prefill.hip", "decode/decode.hip", "decode/plan.hip", "tiles/dot2_tiles.hip", "tiles/dot2.hip" }; +const groups = [_][]const u8{ "ops/ops.hip", "ops/act.hip", "attention/attention.hip", "recurrence/gated_delta.hip", "attention/prefill.hip", "recurrence/gdn_prefill.hip", "decode/decode.hip", "decode/plan.hip", "tiles/dot2_tiles.hip", "tiles/dot2.hip", "flashnext/flashnext.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/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", - "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", - "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", - "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", "tiles/gemm_kp.hpp", - "tiles/matrix_gemm.hpp", "tiles/plan.hpp", "tiles/stream.hpp", + "attention/attention_fa.hip", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", + "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", + "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", + "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", + "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", "tiles/gemm_kp.hpp", + "tiles/matrix_gemm.hpp", "tiles/plan.hpp", "tiles/stream.hpp", "flashnext/streams.hpp", "flashnext/ngram.hpp", + "flashnext/indexer.hpp", "flashnext/sparse.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: [10][]align(8) const u8 = @splat(&.{});\n"; +const stub = "pub const arch = \"\";\npub const images: [11][]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 { diff --git a/zig/kernels/hip/flashnext/flashnext.hip b/zig/kernels/hip/flashnext/flashnext.hip new file mode 100644 index 00000000000..19260651c6c --- /dev/null +++ b/zig/kernels/hip/flashnext/flashnext.hip @@ -0,0 +1,6 @@ +// Flash Next's own kernels as one code object: residual streams, n-gram hashes, the indexer and sparse attention. + +#include "streams.hpp" +#include "ngram.hpp" +#include "indexer.hpp" +#include "sparse.hpp" diff --git a/zig/kernels/hip/flashnext/indexer.hpp b/zig/kernels/hip/flashnext/indexer.hpp new file mode 100644 index 00000000000..6960ca8ec05 --- /dev/null +++ b/zig/kernels/hip/flashnext/indexer.hpp @@ -0,0 +1,181 @@ +#pragma once + +#include "streams.hpp" + +// The sparse attention's indexer: pooled block keys, each row's block scores, and the blocks a row attends. + +namespace { + +constexpr int kSelectThreads = 1024; +constexpr int kSelectWaves = kSelectThreads / 32; + +// Block b: the mean of its ratio raw keys, RMS-normed with scale and rotated at its first position, as tf_qk_rope. +// With `pos`, launch x is a row: the block it completes (if any) goes to slot b of `pooled`; else block first + x to x. +extern "C" __global__ void __launch_bounds__(kFnThreads) +tf_fn_idx_pool(const void* raw, void* pooled, const float* scale, int kind, int first, const int* pos, int dims, + int ratio, int rotary, float theta, float eps) { + __shared__ float scratch[kFnWaves]; + __shared__ float normed[kFnThreads]; + const int end = pos ? pos[blockIdx.x] + 1 : 0; + if (pos && end % ratio != 0) return; + const int b = pos ? end / ratio - 1 : first + blockIdx.x, d = threadIdx.x; + const long long slot = pos ? b : blockIdx.x; + float x = 0.f; + if (d < dims) { + float m = 0.f; + for (int k = 0; k < ratio; ++k) m += load(raw, kind, (static_cast(b) * ratio + k) * dims + d); + x = rounded(m / static_cast(ratio), kind); + } + const float rinv = rsqrtf(fn_block_sum(x * x, scratch) / static_cast(dims) + eps); + if (d < dims) normed[d] = rounded(x * rinv * scale[d], kind); + __syncthreads(); + if (d >= dims) return; + const int half = rotary >> 1; + float y = normed[d]; + if (d < rotary) { + const int f = d < half ? d : d - half; + const float freq = 1.f / powf(theta, static_cast(f) / static_cast(half)); + const float ang = static_cast(b * ratio) * freq; + const float c = cosf(ang), s = sinf(ang); + y = d < half ? normed[f] * c - normed[f + half] * s : normed[f] * s + normed[f + half] * c; + } + store(pooled, kind, slot * dims + d, rounded(y, kind)); +} + +// Wave w of block (x, y) scores block 8 x + w for rows 8 y ..: the sum over heads of relu(q . key) / sqrt(dims). +extern "C" __global__ void __launch_bounds__(kFnThreads) +tf_fn_idx_scores(const float* q, const void* pooled, const int* complete, float* scores, int kind, int rows, int heads, + int dims, int blocks, long long stride, int top) { + constexpr int kMost = 8; + const int lane = threadIdx.x & 31; + const int b = blockIdx.x * kFnWaves + (threadIdx.x >> 5); + const int r0 = blockIdx.y * 8, r1 = min(rows, r0 + 8); + bool wanted = false; // a graph launches over a bound of blocks: those no row scores read nothing + for (int r = r0; r < r1; ++r) wanted = wanted || (complete[r] > top && b < complete[r]); + if (b >= blocks || !wanted) return; + float key[kMost]; +#pragma unroll + for (int i = 0; i < kMost; ++i) { + const int d = lane + 32 * i; + key[i] = d < dims ? load(pooled, kind, static_cast(b) * dims + d) : 0.f; + } + const float norm = sqrtf(static_cast(dims)); + for (int r = r0; r < r1; ++r) { + if (complete[r] <= top || b >= complete[r]) continue; + float total = 0.f; + for (int h = 0; h < heads; ++h) { + const float* qh = q + (static_cast(r) * heads + h) * dims; + float dot = 0.f; +#pragma unroll + for (int i = 0; i < kMost; ++i) { + const int d = lane + 32 * i; + if (d < dims) dot += qh[d] * key[i]; + } +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) dot += __shfl_xor(dot, mask, 32); + total += fmaxf(dot, 0.f); + } + if (lane == 0) scores[r * stride + b] = total / norm; + } +} + +// An order-keeping unsigned key of a float: larger floats, larger keys. +__device__ __forceinline__ unsigned fn_order(float v) { + const unsigned u = __float_as_uint(v); + return (u & 0x80000000u) ? ~u : (u | 0x80000000u); +} + +// The block's exclusive prefix sum of one count a thread, and the total through `total`. +__device__ int fn_scan(int v, int* waves, int* total) { + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + int x = v; +#pragma unroll + for (int off = 1; off < 32; off <<= 1) { + const int y = __shfl_up(x, off, 32); + if (lane >= off) x += y; + } + __syncthreads(); + if (lane == 31) waves[wave] = x; + __syncthreads(); + if (wave == 0) { + int w = lane < kSelectWaves ? waves[lane] : 0; +#pragma unroll + for (int off = 1; off < 32; off <<= 1) { + const int y = __shfl_up(w, off, 32); + if (lane >= off) w += y; + } + if (lane < kSelectWaves) waves[lane] = w; + } + __syncthreads(); + *total = waves[kSelectWaves - 1]; + return x - v + (wave > 0 ? waves[wave - 1] : 0); +} + +// Block r: past top complete blocks, the top best (ties: lower id) in block order, then the tail; else keys < ends. +extern "C" __global__ void __launch_bounds__(kSelectThreads) +tf_fn_idx_select(const float* scores, long long stride, const int* complete, const int* ends, int* keys, + long long key_stride, int* count, int* sparse, int top, int ratio) { + __shared__ int hist[256]; + __shared__ int waves[kSelectWaves]; + __shared__ unsigned cut_s; + __shared__ int need_s; + const int r = blockIdx.x, t = threadIdx.x; + const int nb = complete[r], end = ends[r]; + if (nb <= top) { + if (t == 0) { + count[r] = end; + sparse[r] = 0; + } + return; + } + const float* sc = scores + r * stride; + unsigned prefix = 0, mask = 0; + int need = top; + for (int shift = 24; shift >= 0; shift -= 8) { + for (int i = t; i < 256; i += kSelectThreads) hist[i] = 0; + __syncthreads(); + for (int b = t; b < nb; b += kSelectThreads) { + const unsigned k = fn_order(sc[b]); + if ((k & mask) == prefix) atomicAdd(&hist[(k >> shift) & 255u], 1); + } + __syncthreads(); + if (t == 0) { + int above = 0, bin = 255; + while (above + hist[bin] < need) above += hist[bin--]; + cut_s = prefix | (static_cast(bin) << shift); + need_s = need - above; + } + __syncthreads(); + prefix = cut_s; + need = need_s; + mask |= 255u << shift; + } + const int chunk = (nb + kSelectThreads - 1) / kSelectThreads; + const int lo = min(nb, t * chunk), hi = min(nb, lo + chunk); + int above = 0, equal = 0; + for (int b = lo; b < hi; ++b) { + const unsigned k = fn_order(sc[b]); + above += k > prefix; + equal += k == prefix; + } + int above_total = 0, equal_total = 0; + int pa = fn_scan(above, waves, &above_total); + int pe = fn_scan(equal, waves, &equal_total); + int out = pa + min(pe, need); + int* row = keys + r * key_stride; + for (int b = lo; b < hi; ++b) { + const unsigned k = fn_order(sc[b]); + bool take = k > prefix; + if (k == prefix) take = pe++ < need; + if (!take) continue; + for (int j = 0; j < ratio; ++j) row[out * ratio + j] = b * ratio + j; + ++out; + } + for (int k = nb * ratio + t; k < end; k += kSelectThreads) row[top * ratio + k - nb * ratio] = k; + if (t == 0) { + count[r] = top * ratio + end - nb * ratio; + sparse[r] = 1; + } +} + +} // namespace diff --git a/zig/kernels/hip/flashnext/ngram.hpp b/zig/kernels/hip/flashnext/ngram.hpp new file mode 100644 index 00000000000..ff01b4853f7 --- /dev/null +++ b/zig/kernels/hip/flashnext/ngram.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include "../ops/common.hpp" + +// The n-gram table rows of a window: each head hashes the last n tokens of the row's segment into its prime table. + +namespace { + +// The tokens before a window the hashes may read: the n-gram size less one, at most. +constexpr int kNgramHistory = 2; + +// meta (int64): history (kNgramHistory, oldest first), eos, multipliers (n), table sizes (heads), offsets (heads). +extern "C" __global__ void tf_fn_ngram_ids(const int* tokens, const long long* meta, unsigned* ids, int rows, + int heads, int per, int n) { + const long long i = gid(); + if (i >= static_cast(rows) * heads || n - 1 > kNgramHistory) return; + const int row = static_cast(i / heads), head = static_cast(i % heads); + const long long eos = meta[kNgramHistory]; + const long long* mult = meta + kNgramHistory + 1; + const long long* sizes = mult + n; + const long long* offsets = sizes + heads; + const int at = kNgramHistory + row; + auto token = [&](int k) -> long long { + return k < kNgramHistory ? meta[k] : static_cast(tokens[k - kNgramHistory]); + }; + int in_segment = 0; // tokens of the row's segment before it, counted up to n - 1 + while (in_segment < n - 1 && token(at - 1 - in_segment) != eos) ++in_segment; + const int span = 2 + head / per; // head h hashes 2 + h / per tokens, those before the segment read as eos + unsigned long long mixed = 0; + for (int q = 0; q < span; ++q) { + const long long t = in_segment >= q ? token(at - q) : eos; + const unsigned long long term = static_cast(t) * static_cast(mult[q]); + mixed = q == 0 ? term : (mixed ^ term); + } + long long mod = static_cast(mixed) % sizes[head]; + if (mod < 0) mod += sizes[head]; + ids[i] = static_cast(mod + offsets[head]); +} + +} // namespace diff --git a/zig/kernels/hip/flashnext/sparse.hpp b/zig/kernels/hip/flashnext/sparse.hpp new file mode 100644 index 00000000000..5d1b46d5bd5 --- /dev/null +++ b/zig/kernels/hip/flashnext/sparse.hpp @@ -0,0 +1,139 @@ +#pragma once + +#include "../ops/common.hpp" + +// Attention over a row's listed keys (the indexer's), or its first n keys, in parts merged in part order. + +namespace { + +constexpr int kSparseWaves = 8; +constexpr int kSparseMostDims = 256; +constexpr int kSparsePer = kSparseMostDims / 32; + +// Keys a block stages at a time, and the padded row of the staged keys (rows read by distinct lanes, no conflicts). +constexpr int kSparseTile = 32; +constexpr int kSparseRow = kSparseMostDims + 1; + +// Block (g, r, p): kv head g's query heads (G at most), row r, part p of its keys, 32 keys staged at a time. +template +__device__ void sparse_parts(const float* q, const void* k, const void* v, int cache_kind, const int* ids, + long long id_stride, const int* count, const int* sparse, float* parts_o, float* parts_ms, + int heads, int kv_heads, int dims, long long cap, float scale, int parts) { + __shared__ float qs[kSparseGroup][kSparseMostDims]; + __shared__ float kt[kSparseTile][kSparseRow]; + __shared__ float ps[kSparseGroup][kSparseTile]; + __shared__ float fs[kSparseGroup], m[kSparseGroup], l[kSparseGroup]; + __shared__ long long keys[kSparseTile]; + const int g = blockIdx.x, r = blockIdx.y, part = blockIdx.z; + const int group = heads / kv_heads; + const int t = threadIdx.x, lane = t & 31, wave = t >> 5; + const int n = count[r]; + const bool listed = ids != nullptr && sparse != nullptr && sparse[r] != 0; + const int lo = static_cast(static_cast(part) * n / parts); + const int hi = static_cast(static_cast(part + 1) * n / parts); + const long long head_base = static_cast(g) * cap * dims; + for (int i = t; i < group * dims; i += kSparseWaves * 32) { + const int h = i / dims, d = i % dims; + qs[h][d] = q[(static_cast(r) * heads + g * group + h) * dims + d] * scale; + } + if (t < kSparseGroup) { + m[t] = -INFINITY; + l[t] = 0.f; + } + float o[kSparseGroup]; +#pragma unroll + for (int h = 0; h < kSparseGroup; ++h) o[h] = 0.f; + for (int t0 = lo; t0 < hi; t0 += kSparseTile) { + const int tn = min(kSparseTile, hi - t0); + __syncthreads(); + if (t < tn) keys[t] = listed ? ids[r * id_stride + t0 + t] : t0 + t; + __syncthreads(); + for (int i = t; i < tn * dims; i += kSparseWaves * 32) { + const int j = i / dims, d = i % dims; + kt[j][d] = load(k, cache_kind, head_base + keys[j] * dims + d); + } + __syncthreads(); + // scores: a lane a key, a wave a head; then that head's softmax over the tile, folded into its running max + for (int pair = t; pair < kSparseTile * group; pair += kSparseWaves * 32) { + const int j = pair % kSparseTile, h = pair / kSparseTile; + float sc = 0.f; + for (int d = 0; d < dims; ++d) sc += qs[h][d] * kt[j][d]; + const bool live = j < tn; + float top = live ? sc : -INFINITY; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) top = fmaxf(top, __shfl_xor(top, mask, 32)); + top = fmaxf(top, m[h]); + const float e = live ? expf(sc - top) : 0.f; + float sum = e; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + ps[h][j] = e; + if (lane == 0) { + const float f = expf(m[h] - top); + fs[h] = f; + l[h] = l[h] * f + sum; + m[h] = top; + } + } + __syncthreads(); + // values: a thread a dim, every head + for (int d = t; d < dims; d += kSparseWaves * 32) { +#pragma unroll + for (int h = 0; h < kSparseGroup; ++h) o[h] *= h < group ? fs[h] : 1.f; + for (int j = 0; j < tn; ++j) { + const float vd = load(v, cache_kind, head_base + keys[j] * dims + d); +#pragma unroll + for (int h = 0; h < kSparseGroup; ++h) { + if (h < group) o[h] += ps[h][j] * vd; + } + } + } + } + __syncthreads(); + for (int h = 0; h < group; ++h) { + const long long out = (static_cast(r) * heads + g * group + h) * parts + part; + for (int d = t; d < dims; d += kSparseWaves * 32) parts_o[out * dims + d] = o[h]; + if (t == 0) { + parts_ms[out * 2] = m[h]; + parts_ms[out * 2 + 1] = l[h]; + } + } +} + +// The parts kernel for groups of up to 6 query heads (a tp-4 rank's) and of up to 12 (the whole model's). +extern "C" __global__ void __launch_bounds__(kSparseWaves * 32) +tf_fn_sparse_parts6(const float* q, const void* k, const void* v, int cache_kind, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, int kv_heads, + int dims, long long cap, float scale, int parts) { + sparse_parts<6>(q, k, v, cache_kind, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, + scale, parts); +} + +extern "C" __global__ void __launch_bounds__(kSparseWaves * 32) +tf_fn_sparse_parts12(const float* q, const void* k, const void* v, int cache_kind, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, int kv_heads, + int dims, long long cap, float scale, int parts) { + sparse_parts<12>(q, k, v, cache_kind, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, + scale, parts); +} + +// Block (h, r), a thread a dim: the parts of head h of row r combined in part order, fp32 rows-major out. +extern "C" __global__ void tf_fn_sparse_merge(const float* parts_o, const float* parts_ms, float* out, int heads, + int dims, int parts) { + const int h = blockIdx.x, r = blockIdx.y; + const long long at = (static_cast(r) * heads + h) * parts; + float top = -INFINITY; + for (int p = 0; p < parts; ++p) top = fmaxf(top, parts_ms[(at + p) * 2]); + for (int d = threadIdx.x; d < dims; d += blockDim.x) { + float total = 0.f, acc = 0.f; + for (int p = 0; p < parts; ++p) { + const float mp = parts_ms[(at + p) * 2]; + const float w = mp == -INFINITY ? 0.f : expf(mp - top); + total += parts_ms[(at + p) * 2 + 1] * w; + acc += parts_o[(at + p) * dims + d] * w; + } + out[(static_cast(r) * heads + h) * dims + d] = total > 0.f ? acc / total : 0.f; + } +} + +} // namespace diff --git a/zig/kernels/hip/flashnext/streams.hpp b/zig/kernels/hip/flashnext/streams.hpp new file mode 100644 index 00000000000..91405295b3e --- /dev/null +++ b/zig/kernels/hip/flashnext/streams.hpp @@ -0,0 +1,184 @@ +#pragma once + +#include "../ops/common.hpp" + +// Flash Next's residual streams: the hyper-connection norm, gates and mix, and the n-gram (PLE) gate and conv. + +namespace { + +constexpr int kFnThreads = 256; +constexpr int kFnWaves = kFnThreads / 32; +// The widest stream a thread walks in registers: dims / kFnThreads values each. +constexpr int kFnPer = 16; +// The hyper-connection norm's block: a stream's dims over 1024 threads, four values each at most. +constexpr int kNormThreads = 1024; +constexpr int kNormPer = 4; + +// A block's sum of a value a thread (`scratch`: a value a wave): each wave by a fixed xor tree, then waves in order. +__device__ float fn_block_sum(float v, float* scratch) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) v += __shfl_xor(v, mask, 32); + const int wave = threadIdx.x >> 5, waves = (blockDim.x + 31) >> 5; + __syncthreads(); + if ((threadIdx.x & 31) == 0) scratch[wave] = v; + __syncthreads(); + float total = 0.f; + for (int w = 0; w < waves; ++w) total += scratch[w]; + return total; +} + +// Block (s, r): h_s += round(branch * inject[s]) (tp: `world` fp32 shares, summed in order), then x = h rinv scale. +extern "C" __global__ void __launch_bounds__(kNormThreads) +tf_fn_hc_norm(const void* h, const void* branch, const void* inject, void* h_out, void* x_out, const float* scale, + int kind, int streams, int dims, float eps, int world, long long stride) { + __shared__ float scratch[kNormThreads / 32]; + const int s = blockIdx.x, r = blockIdx.y; + const long long base = (static_cast(r) * streams + s) * dims; + float v[kNormPer]; + float sum = 0.f; +#pragma unroll + for (int j = 0; j < kNormPer; ++j) { + const int d = threadIdx.x + j * kNormThreads; + v[j] = 0.f; + if (d >= dims) continue; + float x = load(h, kind, base + d); + if (branch != nullptr) { + const long long at = static_cast(r) * dims + d; + float b; + if (world > 0) { + b = 0.f; + for (int w = 0; w < world; ++w) b += static_cast(branch)[w * stride + at]; + b = rounded(b, kind); + } else { + b = load(branch, kind, at); + } + const float add = rounded(b * load(inject, kind, static_cast(r) * streams + s), kind); + x = rounded(x + add, kind); + } + v[j] = x; + sum += x * x; + } + sum = fn_block_sum(sum, scratch); + const float rinv = rsqrtf(sum / static_cast(dims) + eps); +#pragma unroll + for (int j = 0; j < kNormPer; ++j) { + const int d = threadIdx.x + j * kNormThreads; + if (d >= dims) continue; + if (h_out != nullptr) store(h_out, kind, base + d, v[j]); + store(x_out, kind, base + d, (v[j] * rinv) * scale[s * dims + d]); + } +} + +// From z [rows, low (+ streams with inject)] / streams: silu for the up projection, 2 sigmoid for the inject gates. +extern "C" __global__ void tf_fn_hc_gates(const float* z, void* act, void* inject, int kind, int rows, int low, + int streams) { + const long long i = gid(); + const int width = low + (inject != nullptr ? streams : 0); + if (i >= static_cast(rows) * width) return; + const int r = static_cast(i / width), c = static_cast(i % width); + const float v = rounded(rounded(z[i], kind) / static_cast(streams), kind); + if (c < low) store(act, kind, static_cast(r) * low + c, silu(v)); + else store(inject, kind, static_cast(r) * streams + c - low, 2.f * rounded(sigmoid(v), kind)); +} + +// Row r of x normed over all its `width` values (fp32 sums: each thread's strided values, then the block's sum). +extern "C" __global__ void __launch_bounds__(kFnThreads) +tf_fn_rms_wide(const void* x, const float* scale, void* y, int kind, int width, float eps) { + __shared__ float scratch[kFnWaves]; + const long long base = static_cast(blockIdx.x) * width; + float sum = 0.f; + for (int i = threadIdx.x; i < width; i += kFnThreads) { + const float v = load(x, kind, base + i); + sum += v * v; + } + const float rinv = rsqrtf(fn_block_sum(sum, scratch) / static_cast(width) + eps); + for (int i = threadIdx.x; i < width; i += kFnThreads) { + store(y, kind, base + i, (load(x, kind, base + i) * rinv) * scale[i]); + } +} + +// mixed[r, d] = mean over the streams (in order) of round(sigmoid(round(g)) * x): g the up projection's fp32 sums. +extern "C" __global__ void tf_fn_hc_mix(const float* g, const void* x, void* mixed, int kind, int rows, int streams, + int dims) { + const long long i = gid(); + if (i >= static_cast(rows) * dims) return; + const long long r = i / dims; + const int d = static_cast(i % dims); + float total = 0.f; + for (int s = 0; s < streams; ++s) { + const long long at = (r * streams + s) * dims + d; + const float gate = rounded(sigmoid(rounded(g[at], kind)), kind); + total += rounded(gate * load(x, kind, at), kind); + } + store(mixed, kind, i, total / static_cast(streams)); +} + +// Block (s, r): gated = sigmoid(signed sqrt(k . q / sqrt(dims))) v, k and q normed; normed is the conv input. +extern "C" __global__ void __launch_bounds__(kFnThreads) +tf_fn_ple_gate(const void* kv, const void* h, const float* key_scale, const float* query_scale, const float* conv_scale, + void* gated, void* normed, int kind, int streams, int dims, float eps) { + __shared__ float scratch[kFnWaves]; + const int s = blockIdx.x, r = blockIdx.y; + const long long wide = static_cast(streams) * dims; + const long long krow = r * (wide + dims), hrow = r * wide; + float k[kFnPer], q[kFnPer], v[kFnPer]; + float sk = 0.f, sq = 0.f; +#pragma unroll + for (int j = 0; j < kFnPer; ++j) { + const int d = threadIdx.x + j * kFnThreads; + k[j] = q[j] = v[j] = 0.f; + if (d >= dims) continue; + k[j] = load(kv, kind, krow + static_cast(s) * dims + d); + q[j] = load(h, kind, hrow + static_cast(s) * dims + d); + v[j] = load(kv, kind, krow + wide + d); + sk += k[j] * k[j]; + sq += q[j] * q[j]; + } + const float rk = rsqrtf(fn_block_sum(sk, scratch) / static_cast(dims) + eps); + const float rq = rsqrtf(fn_block_sum(sq, scratch) / static_cast(dims) + eps); + float dot = 0.f; +#pragma unroll + for (int j = 0; j < kFnPer; ++j) { + const int d = threadIdx.x + j * kFnThreads; + if (d >= dims) continue; + const float kn = rounded((k[j] * rk) * key_scale[s * dims + d], kind); + const float qn = rounded((q[j] * rq) * query_scale[s * dims + d], kind); + dot += rounded(kn * qn, kind); + } + dot = fn_block_sum(dot, scratch); + const float g1 = rounded(rounded(dot, kind) / rounded(sqrtf(static_cast(dims)), kind), kind); + const float root = rounded(sqrtf(fmaxf(fabsf(g1), 1e-6f)), kind); + const float g2 = rounded(g1 < 0.f ? -root : (g1 > 0.f ? root : 0.f), kind); + const float gate = rounded(sigmoid(g2), kind); + float sc = 0.f; +#pragma unroll + for (int j = 0; j < kFnPer; ++j) { + v[j] = rounded(gate * v[j], kind); + sc += v[j] * v[j]; + } + const float rc = rsqrtf(fn_block_sum(sc, scratch) / static_cast(dims) + eps); +#pragma unroll + for (int j = 0; j < kFnPer; ++j) { + const int d = threadIdx.x + j * kFnThreads; + if (d >= dims) continue; + const long long at = hrow + static_cast(s) * dims + d; + store(gated, kind, at, v[j]); + store(normed, kind, at, (v[j] * rc) * conv_scale[s * dims + d]); + } +} + +// Channel c of row r: out = h + (gated + silu(conv)), the dilated causal conv over cin, which holds the tail first. +extern "C" __global__ void tf_fn_ple_conv(const void* cin, const float* weight, const void* gated, const void* h, + void* out, int kind, int rows, int width, int taps, int dilation) { + const long long i = gid(); + if (i >= static_cast(rows) * width) return; + const long long r = i / width; + const int c = static_cast(i % width); + float y = 0.f; + for (int j = 0; j < taps; ++j) y = fmaf(weight[c * taps + j], load(cin, kind, (r + dilation * j) * width + c), y); + const float yb = rounded(y, kind); + const float act = rounded(yb * rounded(sigmoid(yb), kind), kind); + store(out, kind, i, load(h, kind, i) + rounded(load(gated, kind, i) + act, kind)); +} + +} // namespace diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 73b676b975d..833211d52bd 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -27,4 +27,6 @@ test { _ = @import("kernel_tests/affine/affine.zig"); _ = @import("kernel_tests/affine/rows.zig"); _ = @import("kernel_tests/graph_split.zig"); + _ = @import("kernel_tests/flashnext.zig"); + _ = @import("kernel_tests/flashnext_attn.zig"); } diff --git a/zig/src/hip/kernel_tests/flashnext.zig b/zig/src/hip/kernel_tests/flashnext.zig new file mode 100644 index 00000000000..6f5c7e9c90e --- /dev/null +++ b/zig/src/hip/kernel_tests/flashnext.zig @@ -0,0 +1,363 @@ +//! Flash Next's stream kernels and n-gram hashes against host references: hashes exact, values within an ulp or two. +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; + +pub fn ptr(comptime T: type, b: DeviceBuffer) T { + return @ptrFromInt(at(b)); +} + +/// The activation's round-to-nearest-even of `v`, widened back. +pub fn rnd(t: *const Rig, v: f32) f32 { + if (!t.bf16) return @floatCast(rig.f16Value(rig.f16Bits(v))); + const u: u32 = @bitCast(v); + const b: u32 = (u + 0x7fff + ((u >> 16) & 1)) >> 16; + return @bitCast(b << 16); +} + +pub fn sigmoid(x: f32) f32 { + return 1.0 / (1.0 + @exp(-x)); +} + +/// Within `ulps` steps of the activation type of `want`'s size (or of 1e-3 near zero). +pub fn close(t: *const Rig, got: f32, want: f32, ulps: f32) bool { + const step: f32 = if (t.bf16) 1.0 / 128.0 else 1.0 / 1024.0; + return @abs(got - want) <= ulps * step * @max(@abs(want), 1e-3); +} + +/// Random activations exact in the activation type, scaled. +pub fn acts(t: *const Rig, rng: *rig.Rng, n: usize, scale: f32) ![]u16 { + const out = try gpa.alloc(u16, n); + for (out) |*x| x.* = t.bits(rng.unit() * scale); + return out; +} + +pub fn value(t: *const Rig, b: u16) f32 { + return @floatCast(t.value(b)); +} + +fn rmsInv(xs: []const f32, eps: f32) f32 { + var sum: f32 = 0; + for (xs) |x| sum += x * x; + return 1.0 / @sqrt(sum / @as(f32, @floatFromInt(xs.len)) + eps); +} + +test "hyper-connection norm, gates and mix: the reference's roundings, each row alone" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x4C }; + const rows = 3; + const s = 4; + const d = 2560; + const w = s * d; + const low = 320; + const eps: f32 = 1e-6; + const hh = try acts(t, &rng, rows * w, 2.0); + defer gpa.free(hh); + const hb = try acts(t, &rng, rows * d, 1.0); + defer gpa.free(hb); + const hi = try acts(t, &rng, rows * s, 1.0); + defer gpa.free(hi); + const scale = try gpa.alloc(f32, w); + defer gpa.free(scale); + for (scale) |*x| x.* = 1.0 + rng.unit() * 0.5; + var h = try t.upload(hh); + defer h.free(); + var branch = try t.upload(hb); + defer branch.free(); + var inject = try t.upload(hi); + defer inject.free(); + var sc = try t.upload(scale); + defer sc.free(); + var h_out = try t.alloc(rows * w * 2); + defer h_out.free(); + var x_out = try t.alloc(rows * w * 2); + defer x_out.free(); + var x_one = try t.alloc(w * 2); + defer x_one.free(); + const k = t.kind(); + const st = t.stream.handle; + try t.on.fn_hc_norm(ptr(?*const anyopaque, h), ptr(?*const anyopaque, branch), ptr(?*const anyopaque, inject), ptr(?*anyopaque, h_out), ptr(?*anyopaque, x_out), ptr(?[*]const f32, sc), k, rows, s, d, eps, st); + try t.on.fn_hc_norm(ptr(?*const anyopaque, h), ptr(?*const anyopaque, branch), ptr(?*const anyopaque, inject), null, ptr(?*anyopaque, x_one), ptr(?[*]const f32, sc), k, 1, s, d, eps, st); + // the gates and the mix over random fp32 sums + const zh = try gpa.alloc(f32, rows * (low + s)); + defer gpa.free(zh); + for (zh) |*x| x.* = rng.unit() * 6.0; + const gh = try gpa.alloc(f32, rows * w); + defer gpa.free(gh); + for (gh) |*x| x.* = rng.unit() * 6.0; + var z = try t.upload(zh); + defer z.free(); + var g = try t.upload(gh); + defer g.free(); + var act = try t.alloc(rows * low * 2); + defer act.free(); + var inj = try t.alloc(rows * s * 2); + defer inj.free(); + var mixed = try t.alloc(rows * d * 2); + defer mixed.free(); + try t.on.fn_hc_gates(ptr(?[*]const f32, z), ptr(?*anyopaque, act), ptr(?*anyopaque, inj), k, rows, low, s, st); + try t.on.fn_hc_mix(ptr(?[*]const f32, g), ptr(?*const anyopaque, x_out), ptr(?*anyopaque, mixed), k, rows, s, d, st); + try t.stream.synchronize(); + const gho = try rig.download(u16, h_out); + defer gpa.free(gho); + const gx = try rig.download(u16, x_out); + defer gpa.free(gx); + const gx1 = try rig.download(u16, x_one); + defer gpa.free(gx1); + try std.testing.expectEqualSlices(u16, gx[0..w], gx1); + // the branch as two fp32 shares (a tp rank's gather): summed in order, then as the whole branch + const shares = try gpa.alloc(f32, 2 * rows * d); + defer gpa.free(shares); + for (shares) |*v| v.* = rng.unit() * 0.5; + var dev_shares = try t.upload(shares); + defer dev_shares.free(); + var h_shared = try t.upload(hh); + defer h_shared.free(); + var x_shared = try t.alloc(rows * w * 2); + defer x_shared.free(); + try t.on.fn_hc_norm_shares(ptr(?*const anyopaque, h_shared), ptr(?*const anyopaque, dev_shares), ptr(?*const anyopaque, inject), ptr(?*anyopaque, h_shared), ptr(?*anyopaque, x_shared), ptr(?[*]const f32, sc), k, rows, s, d, eps, 2, rows * d, st); + try t.stream.synchronize(); + const ghs = try rig.download(u16, h_shared); + defer gpa.free(ghs); + for (0..rows) |r| for (0..s) |si| for (0..d) |j| { + const b = rnd(t, shares[r * d + j] + shares[rows * d + r * d + j]); + const want = rnd(t, value(t, hh[(r * s + si) * d + j]) + rnd(t, b * value(t, hi[r * s + si]))); + try std.testing.expectEqual(t.bits(want), ghs[(r * s + si) * d + j]); + }; + const want_h = try gpa.alloc(f32, d); + defer gpa.free(want_h); + for (0..rows) |r| for (0..s) |si| { + for (0..d) |j| { + const add = rnd(t, value(t, hb[r * d + j]) * value(t, hi[r * s + si])); + want_h[j] = rnd(t, value(t, hh[(r * s + si) * d + j]) + add); + try std.testing.expectEqual(t.bits(want_h[j]), gho[(r * s + si) * d + j]); + } + const inv = rmsInv(want_h, eps); + for (0..d) |j| { + const want = rnd(t, want_h[j] * inv * scale[si * d + j]); + try rig.expect(close(t, value(t, gx[(r * s + si) * d + j]), want, 1), "hc norm row {d} stream {d} dim {d}", .{ r, si, j }); + } + }; + const ga = try rig.download(u16, act); + defer gpa.free(ga); + const gi = try rig.download(u16, inj); + defer gpa.free(gi); + for (0..rows) |r| for (0..low + s) |c| { + const v = rnd(t, rnd(t, zh[r * (low + s) + c]) / 4.0); + if (c < low) { + try rig.expect(close(t, value(t, ga[r * low + c]), rnd(t, v * sigmoid(v)), 1), "hc act {d} {d}", .{ r, c }); + } else try rig.expect(close(t, value(t, gi[r * s + c - low]), 2 * rnd(t, sigmoid(v)), 1), "hc inject {d} {d}", .{ r, c }); + }; + const gm = try rig.download(u16, mixed); + defer gpa.free(gm); + for (0..rows) |r| for (0..d) |j| { + var total: f32 = 0; + for (0..s) |si| { + const e = (r * s + si) * d + j; + total += rnd(t, rnd(t, sigmoid(rnd(t, gh[e]))) * value(t, gx[e])); + } + try rig.expect(close(t, value(t, gm[r * d + j]), rnd(t, total / 4.0), 2), "hc mix {d} {d}", .{ r, j }); + }; +} + +test "the wide norm over a row of every stream, and the gates without inject gates" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x51DE }; + const rows = 3; + const w = 10240; + const low = 320; + const eps: f32 = 1e-6; + const hx = try acts(t, &rng, rows * w, 2.0); + defer gpa.free(hx); + const scale = try gpa.alloc(f32, w); + defer gpa.free(scale); + for (scale) |*x| x.* = 1.0 + rng.unit() * 0.5; + var x = try t.upload(hx); + defer x.free(); + var sc = try t.upload(scale); + defer sc.free(); + var y = try t.alloc(rows * w * 2); + defer y.free(); + const zh = try gpa.alloc(f32, rows * low); + defer gpa.free(zh); + for (zh) |*v| v.* = rng.unit() * 6.0; + var z = try t.upload(zh); + defer z.free(); + var act = try t.alloc(rows * low * 2); + defer act.free(); + const st = t.stream.handle; + try t.on.fn_rms_wide(ptr(?*const anyopaque, x), ptr(?[*]const f32, sc), ptr(?*anyopaque, y), t.kind(), rows, w, eps, st); + try t.on.fn_hc_gates(ptr(?[*]const f32, z), ptr(?*anyopaque, act), null, t.kind(), rows, low, 4, st); + try t.stream.synchronize(); + const gy = try rig.download(u16, y); + defer gpa.free(gy); + const xs = try gpa.alloc(f32, w); + defer gpa.free(xs); + for (0..rows) |r| { + for (xs, 0..) |*v, j| v.* = value(t, hx[r * w + j]); + const inv = rmsInv(xs, eps); + for (0..w) |j| try rig.expect(close(t, value(t, gy[r * w + j]), rnd(t, xs[j] * inv * scale[j]), 1), "wide norm row {d} dim {d}", .{ r, j }); + } + const ga = try rig.download(u16, act); + defer gpa.free(ga); + for (0..rows * low) |i| { + const v = rnd(t, rnd(t, zh[i]) / 4.0); + try rig.expect(close(t, value(t, ga[i]), rnd(t, v * sigmoid(v)), 1), "gate {d}", .{i}); + } +} + +test "the n-gram gate and its dilated conv: gate, norm, conv and residual sums as the reference rounds them" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x91E }; + const rows = 5; + const s = 4; + const d = 2560; + const w = s * d; + const taps = 4; + const dil = 3; + const tail = dil * (taps - 1); + const eps: f32 = 1e-6; + const hkv = try acts(t, &rng, rows * (w + d), 2.0); + defer gpa.free(hkv); + const hh = try acts(t, &rng, rows * w, 2.0); + defer gpa.free(hh); + const htail = try acts(t, &rng, tail * w, 1.0); + defer gpa.free(htail); + const scales = try gpa.alloc(f32, 3 * w + w * taps); + defer gpa.free(scales); + for (scales) |*x| x.* = 1.0 + rng.unit() * 0.5; + var kv = try t.upload(hkv); + defer kv.free(); + var h = try t.upload(hh); + defer h.free(); + var sc = try t.upload(scales); + defer sc.free(); + var cin = try t.alloc((tail + rows) * w * 2); + defer cin.free(); + try cin.upload(0, std.mem.sliceAsBytes(htail)); + var gated = try t.alloc(rows * w * 2); + defer gated.free(); + var out = try t.alloc(rows * w * 2); + defer out.free(); + const k = t.kind(); + const st = t.stream.handle; + const base: usize = @intCast(at(sc)); + const f32p = struct { + fn at(b: usize, i: usize) ?[*]const f32 { + return @ptrFromInt(b + i * 4); + } + }; + try t.on.fn_ple_gate(ptr(?*const anyopaque, kv), ptr(?*const anyopaque, h), f32p.at(base, 0), f32p.at(base, w), f32p.at(base, 2 * w), ptr(?*anyopaque, gated), @ptrFromInt(at(cin) + tail * w * 2), k, rows, s, d, eps, st); + try t.on.fn_ple_conv(ptr(?*const anyopaque, cin), f32p.at(base, 3 * w), ptr(?*const anyopaque, gated), ptr(?*const anyopaque, h), ptr(?*anyopaque, out), k, rows, w, taps, dil, st); + try t.stream.synchronize(); + const gg = try rig.download(u16, gated); + defer gpa.free(gg); + const gc = try rig.download(u16, cin); + defer gpa.free(gc); + const go = try rig.download(u16, out); + defer gpa.free(go); + const kn = try gpa.alloc(f32, d); + defer gpa.free(kn); + const qn = try gpa.alloc(f32, d); + defer gpa.free(qn); + for (0..rows) |r| for (0..s) |si| { + for (0..d) |j| { + kn[j] = value(t, hkv[r * (w + d) + si * d + j]); + qn[j] = value(t, hh[r * w + si * d + j]); + } + const rk = rmsInv(kn, eps); + const rq = rmsInv(qn, eps); + var dot: f32 = 0; + for (0..d) |j| dot += rnd(t, rnd(t, kn[j] * rk * scales[si * d + j]) * rnd(t, qn[j] * rq * scales[w + si * d + j])); + const g1 = rnd(t, rnd(t, dot) / rnd(t, @sqrt(@as(f32, d)))); + const root = rnd(t, @sqrt(@max(@abs(g1), 1e-6))); + const gate = rnd(t, sigmoid(rnd(t, std.math.sign(g1) * root))); + for (0..d) |j| { + kn[j] = rnd(t, gate * value(t, hkv[r * (w + d) + w + j])); + try rig.expect(close(t, value(t, gg[r * w + si * d + j]), kn[j], 2), "ple gate row {d} stream {d} dim {d}", .{ r, si, j }); + } + const rc = rmsInv(kn, eps); + for (0..d) |j| { + const want = rnd(t, kn[j] * rc * scales[2 * w + si * d + j]); + try rig.expect(close(t, value(t, gc[(tail + r) * w + si * d + j]), want, 2), "ple norm row {d} stream {d} dim {d}", .{ r, si, j }); + } + }; + for (0..rows) |r| for (0..w) |c| { + var y: f32 = 0; + for (0..taps) |j| y = @mulAdd(f32, scales[3 * w + c * taps + j], value(t, gc[(r + dil * j) * w + c]), y); + const yb = rnd(t, y); + const silu = rnd(t, yb * rnd(t, sigmoid(yb))); + const want = rnd(t, value(t, hh[r * w + c]) + rnd(t, value(t, gg[r * w + c]) + silu)); + try rig.expect(close(t, value(t, go[r * w + c]), want, 1), "ple conv row {d} channel {d}", .{ r, c }); + }; +} + +/// The reference's hash of row `row`'s n-gram for head `head`: history then tokens, eos for those past a segment. +pub fn ngramId(history: [2]i64, tokens: []const i32, row: usize, head: usize, eos: i64, mult: []const i64, size: i64, offset: i64, per: usize) u32 { + var seq: [66]i64 = undefined; + seq[0], seq[1] = history; + for (tokens[0 .. row + 1], 0..) |x, i| seq[2 + i] = x; + const here = 2 + row; + var before: ?usize = null; + for (0..here) |q| if (seq[q] == eos) { + before = q; + }; + const in_seg = here - if (before) |b| b + 1 else 0; + var mixed: u64 = 0; + for (0..2 + head / per) |q| { + const tok = if (in_seg >= q) seq[here - q] else eos; + const term = @as(u64, @bitCast(tok)) *% @as(u64, @bitCast(mult[q])); + mixed = if (q == 0) term else mixed ^ term; + } + var m = @rem(@as(i64, @bitCast(mixed)), size); + if (m < 0) m += size; + return @intCast(m + offset); +} + +test "n-gram rows: every head's hash of the window, segments cut at eos, exact" { + const t = try Rig.open(1 << 20); + defer t.close(); + const eos: i64 = 248044; + const mult = [3]i64{ 23703573157769, 20109073645365, 8052911324071 }; + var sizes: [16]i64 = undefined; + var offsets: [16]i64 = undefined; + const primes = [16]i64{ 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, 20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171 }; + var off: i64 = 0; + for (primes, 0..) |p, i| { + sizes[i] = p; + offsets[i] = off; + off += p; + } + const cases = [_]struct { history: [2]i64, tokens: []const i32 }{ + .{ .history = .{ 11, 248044 }, .tokens = &.{ 5, 248044, 77, 90000, 248044, 248044, 3, 4, 248319, 0, 12 } }, + .{ .history = .{ 248044, 248044 }, .tokens = &.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }, + .{ .history = .{ 70000, 248044 }, .tokens = &.{248044} }, + }; + for (cases) |c| { + var meta: [3 + 3 + 32]i64 = undefined; + meta[0], meta[1], meta[2] = .{ c.history[0], c.history[1], eos }; + @memcpy(meta[3..6], &mult); + @memcpy(meta[6..22], &sizes); + @memcpy(meta[22..38], &offsets); + var dm = try t.upload(&meta); + defer dm.free(); + var dt = try t.upload(c.tokens); + defer dt.free(); + const rows: c_int = @intCast(c.tokens.len); + var ids = try t.alloc(c.tokens.len * 16 * 4); + defer ids.free(); + try t.on.fn_ngram_ids(ptr(?[*]const i32, dt), ptr(?*const anyopaque, dm), ptr(?*anyopaque, ids), rows, 16, 8, 3, t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(u32, ids); + defer gpa.free(got); + for (0..c.tokens.len) |r| for (0..16) |hd| { + try std.testing.expectEqual(ngramId(c.history, c.tokens, r, hd, eos, &mult, sizes[hd], offsets[hd], 8), got[r * 16 + hd]); + }; + } +} diff --git a/zig/src/hip/kernel_tests/flashnext_attn.zig b/zig/src/hip/kernel_tests/flashnext_attn.zig new file mode 100644 index 00000000000..c2544200b43 --- /dev/null +++ b/zig/src/hip/kernel_tests/flashnext_attn.zig @@ -0,0 +1,293 @@ +//! Flash Next's indexer and sparse attention against host references: selections exact, values near fp64's. +const std = @import("std"); +const rig = @import("rig.zig"); +const fx = @import("flashnext.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const ptr = fx.ptr; +const rnd = fx.rnd; +const value = fx.value; + +test "pooled block keys: the mean of a block's raw keys, normed and rotated at its first position" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9001 }; + const dims = 128; + const ratio = 4; + const rotary = 64; + const first = 3; + const blocks = 9; + const theta: f32 = 10_000_000; + const eps: f32 = 1e-6; + const hraw = try fx.acts(t, &rng, (first + blocks) * ratio * dims, 2.0); + defer gpa.free(hraw); + var scale: [dims]f32 = undefined; + for (&scale) |*x| x.* = 1.0 + rng.unit() * 0.5; + var raw = try t.upload(hraw); + defer raw.free(); + var sc = try t.upload(&scale); + defer sc.free(); + var pooled = try t.alloc(blocks * dims * 2); + defer pooled.free(); + try t.on.fn_idx_pool(ptr(?*const anyopaque, raw), ptr(?*anyopaque, pooled), ptr(?[*]const f32, sc), t.kind(), first, blocks, dims, ratio, rotary, theta, eps, t.stream.handle); + try t.stream.synchronize(); + const got = try rig.download(u16, pooled); + defer gpa.free(got); + var x: [dims]f32 = undefined; + var n: [dims]f32 = undefined; + for (0..blocks) |j| { + const b = first + j; + var sum: f32 = 0; + for (0..dims) |d| { + var m: f32 = 0; + for (0..ratio) |k| m += value(t, hraw[(b * ratio + k) * dims + d]); + x[d] = rnd(t, m / ratio); + sum += x[d] * x[d]; + } + const inv = 1.0 / @sqrt(sum / dims + eps); + for (0..dims) |d| n[d] = rnd(t, x[d] * inv * scale[d]); + for (0..dims) |d| { + var want = n[d]; + if (d < rotary) { + const half = rotary / 2; + const f = d % half; + const freq: f64 = 1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(f)) / half); + const ang: f64 = @as(f64, @floatFromInt(b * ratio)) * freq; + const c: f64 = @cos(ang); + const s: f64 = @sin(ang); + const y: f64 = if (d < half) n[f] * c - n[f + half] * s else n[f] * s + n[f + half] * c; + want = rnd(t, @floatCast(y)); + } + const step: f32 = if (t.bf16) 1.0 / 128.0 else 1.0 / 1024.0; + try rig.expect(@abs(value(t, got[j * dims + d]) - want) <= 2 * step * @max(@abs(want), 0.25), "pool block {d} dim {d}", .{ b, d }); + } + } +} + +test "pooled block keys at device positions: the blocks a window's rows complete, each as a pool from block 0" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x9002 }; + const dims = 128; + const ratio = 4; + const blocks = 5; + const hraw = try fx.acts(t, &rng, blocks * ratio * dims, 2.0); + defer gpa.free(hraw); + var scale: [dims]f32 = undefined; + for (&scale) |*x| x.* = 1.0 + rng.unit() * 0.5; + var raw = try t.upload(hraw); + defer raw.free(); + var sc = try t.upload(&scale); + defer sc.free(); + var whole = try t.alloc(blocks * dims * 2); + defer whole.free(); + try t.on.fn_idx_pool(ptr(?*const anyopaque, raw), ptr(?*anyopaque, whole), ptr(?[*]const f32, sc), t.kind(), 0, blocks, dims, ratio, 64, 1e7, 1e-6, t.stream.handle); + var mark: [blocks * dims]u16 = undefined; + @memset(&mark, 0xffff); + var slots = try t.upload(&mark); + defer slots.free(); + // rows at 10 .. 15: the rows at 11 and 15 complete blocks 2 and 3 + const pos = [_]i32{ 10, 11, 12, 13, 14, 15 }; + var dp = try t.upload(&pos); + defer dp.free(); + try t.on.fn_idx_pool_at(ptr(?*const anyopaque, raw), ptr(?*anyopaque, slots), ptr(?[*]const f32, sc), t.kind(), ptr(?[*]const i32, dp), pos.len, dims, ratio, 64, 1e7, 1e-6, t.stream.handle); + try t.stream.synchronize(); + const want = try rig.download(u16, whole); + defer gpa.free(want); + const got = try rig.download(u16, slots); + defer gpa.free(got); + for (0..blocks) |b| { + const done = b == 2 or b == 3; + for (0..dims) |d| try rig.expect(got[b * dims + d] == if (done) want[b * dims + d] else 0xffff, "block {d} dim {d}", .{ b, d }); + } +} + +/// A row's keys as the reference picks them: the top best blocks (ties: lower id) in block order, then the tail. +fn selectRef(scores: []const f32, nb: usize, end: usize, top: usize, ratio: usize, out: *std.ArrayList(i32)) !void { + const order = try gpa.alloc(usize, nb); + defer gpa.free(order); + for (order, 0..) |*o, i| o.* = i; + std.mem.sort(usize, order, scores, struct { + fn lt(s: []const f32, a: usize, b: usize) bool { + return s[a] > s[b] or (s[a] == s[b] and a < b); + } + }.lt); + const keep = try gpa.alloc(bool, nb); + defer gpa.free(keep); + @memset(keep, false); + for (order[0..top]) |b| keep[b] = true; + for (0..nb) |b| if (keep[b]) for (0..ratio) |j| try out.append(gpa, @intCast(b * ratio + j)); + for (nb * ratio..end) |k| try out.append(gpa, @intCast(k)); +} + +test "block scores and selection: relu-summed heads, the best blocks with ties to the lower id, dense rows untouched" { + const t = try Rig.open(1 << 22); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x5E1 }; + const heads = 4; + const dims = 128; + const ratio = 4; + const top = 32; + const blocks = 3000; + const ends = [_]i32{ 100, 4 * 3000 + 3, 4 * 1500, 4 * 33 + 1, 4 * 2999 + 2 }; + const rows = ends.len; + var complete: [rows]i32 = undefined; + for (&complete, ends) |*c, e| c.* = @divFloor(e, ratio); + const hq = try gpa.alloc(f32, rows * heads * dims); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + const hp = try fx.acts(t, &rng, blocks * dims, 1.0); + defer gpa.free(hp); + var q = try t.upload(hq); + defer q.free(); + var pooled = try t.upload(hp); + defer pooled.free(); + var dc = try t.upload(&complete); + defer dc.free(); + var de = try t.upload(&ends); + defer de.free(); + var scores = try t.alloc(rows * blocks * 4); + defer scores.free(); + try scores.fill8(0); + const st = t.stream.handle; + try t.on.fn_idx_scores(ptr(?[*]const f32, q), ptr(?*const anyopaque, pooled), ptr(?[*]const i32, dc), ptr(?[*]f32, scores), t.kind(), rows, heads, dims, blocks, blocks, top, st); + try t.stream.synchronize(); + const gs = try rig.download(f32, scores); + defer gpa.free(gs); + for (0..rows) |r| for (0..blocks) |b| { + const live = complete[r] > top and b < complete[r]; + var want: f64 = 0; + if (live) for (0..heads) |h| { + var dot: f64 = 0; + for (0..dims) |d| dot += hq[(r * heads + h) * dims + d] * t.value(hp[b * dims + d]); + want += @max(dot, 0); + }; + want /= @sqrt(@as(f64, dims)); + try rig.expect(@abs(gs[r * blocks + b] - want) <= 1e-4 * @max(@abs(want), 1), "score row {d} block {d}", .{ r, b }); + }; + // the selection runs on scores with ties written in: the GPU's, then a few equal to the cut + for (0..rows) |r| for (0..blocks) |b| if (b % 50 == 5) { + gs[r * blocks + b] = 3.0; + }; + var sel_in = try t.upload(gs); + defer sel_in.free(); + const key_stride = top * ratio + ratio; + var keys = try t.alloc(rows * key_stride * 4); + defer keys.free(); + try keys.fill8(0xff); + var count = try t.alloc(rows * 4); + defer count.free(); + var sparse = try t.alloc(rows * 4); + defer sparse.free(); + try t.on.fn_idx_select(ptr(?[*]const f32, sel_in), blocks, ptr(?[*]const i32, dc), ptr(?[*]const i32, de), ptr(?[*]i32, keys), key_stride, ptr(?[*]i32, count), ptr(?[*]i32, sparse), rows, top, ratio, st); + try t.stream.synchronize(); + const gk = try rig.download(i32, keys); + defer gpa.free(gk); + const gc = try rig.download(i32, count); + defer gpa.free(gc); + const gsp = try rig.download(i32, sparse); + defer gpa.free(gsp); + for (0..rows) |r| { + const nb: usize = @intCast(complete[r]); + if (nb <= top) { + try std.testing.expectEqual(@as(i32, 0), gsp[r]); + try std.testing.expectEqual(ends[r], gc[r]); + continue; + } + var want: std.ArrayList(i32) = .empty; + defer want.deinit(gpa); + try selectRef(gs[r * blocks ..][0..nb], nb, @intCast(ends[r]), top, ratio, &want); + try std.testing.expectEqual(@as(i32, 1), gsp[r]); + try std.testing.expectEqual(@as(i32, @intCast(want.items.len)), gc[r]); + try std.testing.expectEqualSlices(i32, want.items, gk[r * key_stride ..][0..want.items.len]); + } +} + +test "sparse attention: listed keys and dense rows near fp64's softmax, a row's parts alike at any row count" { + const t = try Rig.open(1 << 22); + defer t.close(); + // the whole model's 12 query heads a kv head, and a tp-4 rank's 6 + try sparseCase(t, 24, 2); + try sparseCase(t, 6, 1); +} + +fn sparseCase(t: *Rig, comptime heads: usize, comptime kv_heads: usize) !void { + var rng: rig.Rng = .{ .state = 0xA77 + heads }; + const dims = 256; + const cap = 700; + const parts = 16; + const rows = 3; + const stride = 300; + const scale: f32 = 0.0625; + const hk = try fx.acts(t, &rng, kv_heads * cap * dims, 1.0); + defer gpa.free(hk); + const hv = try fx.acts(t, &rng, kv_heads * cap * dims, 1.0); + defer gpa.free(hv); + const hq = try gpa.alloc(f32, rows * heads * dims); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit() * 4.0; + var ids: [rows * stride]i32 = @splat(0); + const count = [rows]i32{ 260, 650, 7 }; + const sparse = [rows]i32{ 1, 0, 1 }; + for (0..rows) |r| for (0..stride) |j| { + ids[r * stride + j] = @intCast((j * 37 + r * 11) % cap); + }; + var dk = try t.upload(hk); + defer dk.free(); + var dv = try t.upload(hv); + defer dv.free(); + var dq = try t.upload(hq); + defer dq.free(); + var di = try t.upload(&ids); + defer di.free(); + var dc = try t.upload(&count); + defer dc.free(); + var ds = try t.upload(&sparse); + defer ds.free(); + var po = try t.alloc(rows * heads * parts * dims * 4); + defer po.free(); + var pm = try t.alloc(rows * heads * parts * 2 * 4); + defer pm.free(); + var out = try t.alloc(rows * heads * dims * 4); + defer out.free(); + var one = try t.alloc(heads * dims * 4); + defer one.free(); + const ck: c_int = if (t.bf16) 2 else 1; + const st = t.stream.handle; + try t.on.fn_sparse_attention(ptr(?[*]const f32, dq), ptr(?*const anyopaque, dk), ptr(?*const anyopaque, dv), ck, ptr(?[*]const i32, di), stride, ptr(?[*]const i32, dc), ptr(?[*]const i32, ds), ptr(?[*]f32, po), ptr(?[*]f32, pm), ptr(?[*]f32, out), rows, heads, kv_heads, dims, cap, scale, parts, st); + try t.on.fn_sparse_attention(ptr(?[*]const f32, dq), ptr(?*const anyopaque, dk), ptr(?*const anyopaque, dv), ck, ptr(?[*]const i32, di), stride, ptr(?[*]const i32, dc), ptr(?[*]const i32, ds), ptr(?[*]f32, po), ptr(?[*]f32, pm), ptr(?[*]f32, one), 1, heads, kv_heads, dims, cap, scale, parts, st); + try t.stream.synchronize(); + const got = try rig.download(f32, out); + defer gpa.free(got); + const solo = try rig.download(f32, one); + defer gpa.free(solo); + try std.testing.expectEqualSlices(f32, got[0 .. heads * dims], solo); + var w: [cap]f64 = undefined; + for (0..rows) |r| for (0..heads) |h| { + const kvh = h / (heads / kv_heads); + const n: usize = @intCast(count[r]); + var top: f64 = -std.math.inf(f64); + for (0..n) |j| { + const key: usize = if (sparse[r] != 0) @intCast(ids[r * stride + j]) else j; + var s: f64 = 0; + for (0..dims) |d| s += @as(f64, hq[(r * heads + h) * dims + d] * scale) * t.value(hk[(kvh * cap + key) * dims + d]); + w[j] = s; + top = @max(top, s); + } + var total: f64 = 0; + for (w[0..n]) |*x| { + x.* = @exp(x.* - top); + total += x.*; + } + for (0..dims) |d| { + var acc: f64 = 0; + for (0..n) |j| { + const key: usize = if (sparse[r] != 0) @intCast(ids[r * stride + j]) else j; + acc += w[j] * t.value(hv[(kvh * cap + key) * dims + d]); + } + const want = acc / total; + try rig.expect(@abs(got[(r * heads + h) * dims + d] - want) <= 1e-4 * @max(@abs(want), 0.1), "attention row {d} head {d} dim {d}", .{ r, h, d }); + } + }; +} diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig index d28850a1c4c..61ca377e522 100644 --- a/zig/src/hip/kernels.zig +++ b/zig/src/hip/kernels.zig @@ -2,7 +2,7 @@ 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, gdn_prefill, decode, plan, affine_tiles, affine_dot2 }; +pub const Group = enum { ops, act, attention, gated_delta, prefill, gdn_prefill, decode, plan, affine_tiles, affine_dot2, flashnext }; 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. diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index c82f8311d67..ee49f11f5c0 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -38,6 +38,7 @@ const plan = @import("launches/plan.zig"); const elementwise = @import("launches/elementwise.zig"); const draw = @import("launches/draw.zig"); const tp = @import("launches/tp.zig"); +const flashnext = @import("launches/flashnext.zig"); pub const ConvArgs = conv.ConvArgs; pub const PlanArgs = plan.PlanArgs; @@ -83,6 +84,8 @@ pub const Launcher = struct { chunked: bool, /// The MLX affine products and the registry that picks their tiles. affine: affine.Kernels, + /// Flash Next's kernels: its residual streams, n-gram rows, indexer and sparse attention. + fnx: flashnext.Fns, const PlanFns = struct { kv_write: Function, @@ -265,6 +268,7 @@ pub const Launcher = struct { const dot2 = l.mods[@backingInt(kernels.Group.affine_dot2)]; l.affine = try affine.Kernels.load(tiles, dot2, caps.Caps.of(kernels.arch) orelse return error.Invalid, choices.products); try l.affine.fillByteLut(r, dot2); + l.fnx = try flashnext.Fns.load(l.mods[@backingInt(kernels.Group.flashnext)]); return l; } @@ -323,6 +327,19 @@ pub const Launcher = struct { 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; + pub const fn_hc_norm = flashnext.hcNorm; + pub const fn_hc_norm_shares = flashnext.hcNormShares; + pub const fn_hc_gates = flashnext.hcGates; + pub const fn_hc_mix = flashnext.hcMix; + pub const fn_rms_wide = flashnext.rmsWide; + pub const fn_ple_gate = flashnext.pleGate; + pub const fn_ple_conv = flashnext.pleConv; + pub const fn_ngram_ids = flashnext.ngramIds; + pub const fn_idx_pool = flashnext.idxPool; + pub const fn_idx_pool_at = flashnext.idxPoolAt; + pub const fn_idx_scores = flashnext.idxScores; + pub const fn_idx_select = flashnext.idxSelect; + pub const fn_sparse_attention = flashnext.sparseAttention; /// 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 { diff --git a/zig/src/hip/launches/flashnext.zig b/zig/src/hip/launches/flashnext.zig new file mode 100644 index 00000000000..2e663450629 --- /dev/null +++ b/zig/src/hip/launches/flashnext.zig @@ -0,0 +1,157 @@ +//! Flash Next's launches: stream norms, gates and mixes, the n-gram gate, conv and hashes, indexer, sparse attention. + +const Launcher = @import("../launches.zig").Launcher; +const Module = @import("../module.zig").Module; +const Function = @import("../module.zig").Function; +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 I = util.I; +const CI = util.CI; +const Args = util.Args; +const Error = util.Error; +const ad = util.ad; +const dim = util.dim; +const cdiv = util.cdiv; + +pub const Fns = struct { + hc_norm: Function, + hc_gates: Function, + rms_wide: Function, + hc_mix: Function, + ple_gate: Function, + ple_conv: Function, + ngram_ids: Function, + idx_pool: Function, + idx_scores: Function, + idx_select: Function, + sparse_parts: [2]Function, // groups of up to 6 and up to 12 query heads + sparse_merge: Function, + + pub fn load(m: Module) Error!Fns { + return .{ + .hc_norm = try m.function("tf_fn_hc_norm"), + .hc_gates = try m.function("tf_fn_hc_gates"), + .rms_wide = try m.function("tf_fn_rms_wide"), + .hc_mix = try m.function("tf_fn_hc_mix"), + .ple_gate = try m.function("tf_fn_ple_gate"), + .ple_conv = try m.function("tf_fn_ple_conv"), + .ngram_ids = try m.function("tf_fn_ngram_ids"), + .idx_pool = try m.function("tf_fn_idx_pool"), + .idx_scores = try m.function("tf_fn_idx_scores"), + .idx_select = try m.function("tf_fn_idx_select"), + .sparse_parts = .{ try m.function("tf_fn_sparse_parts6"), try m.function("tf_fn_sparse_parts12") }, + .sparse_merge = try m.function("tf_fn_sparse_merge"), + }; + } +}; + +/// The widest stream the norm and gate kernels walk: 16 values a thread of 256. +pub const most_dims = 4096; +const threads = 256; + +/// `rows` rows of `streams` streams: h += round(branch * inject) when a branch is given, then x = h rinv scale. +pub fn hcNorm(l: *const Launcher, h: C, branch: C, inject: C, h_out: P, x_out: P, scale: CF, kind: c_int, rows: c_int, streams: c_int, dims: c_int, eps: f32, s: S) Error!void { + return hcNormShares(l, h, branch, inject, h_out, x_out, scale, kind, rows, streams, dims, eps, 0, 0, s); +} + +/// hcNorm with the branch as `world` fp32 shares `stride` values apart (a tensor-parallel gather), summed in order. +pub fn hcNormShares(l: *const Launcher, h: C, branch: C, inject: C, h_out: P, x_out: P, scale: CF, kind: c_int, rows: c_int, streams: c_int, dims: c_int, eps: f32, world: c_int, stride: i64, s: S) Error!void { + if (dims > most_dims) return util.invalid("hcNorm"); + var a: Args = .{}; + inline for (.{ ad(h), ad(branch), ad(inject), ad(h_out), ad(x_out), ad(scale), kind, streams, dims, eps, world, stride }) |v| try a.add(v); + try l.go(l.fnx.hc_norm, dim(streams, rows, 1), dim(1024, 1, 1), 0, s, &a); +} + +/// act = silu(z / streams) and inject = 2 sigmoid(z / streams) from the down projection's fp32 sums (no inject: null). +pub fn hcGates(l: *const Launcher, z: CF, act: P, inject: P, kind: c_int, rows: c_int, low: c_int, streams: c_int, s: S) Error!void { + var a: Args = .{}; + inline for (.{ ad(z), ad(act), ad(inject), kind, rows, low, streams }) |v| try a.add(v); + try l.flat(l.fnx.hc_gates, @as(i64, rows) * (low + if (inject != null) streams else 0), s, &a); +} + +/// Each of `rows` rows normed over its whole `width` (any width) times the fp32 `scale`. +pub fn rmsWide(l: *const Launcher, x: C, scale: CF, y: P, kind: c_int, rows: c_int, width: c_int, eps: f32, s: S) Error!void { + if (rows == 0) return; + var a: Args = .{}; + inline for (.{ ad(x), ad(scale), ad(y), kind, width, eps }) |v| try a.add(v); + try l.go(l.fnx.rms_wide, dim(rows, 1, 1), dim(threads, 1, 1), 0, s, &a); +} + +/// The block input: the mean over the streams of sigmoid(g) times the normed stream. +pub fn hcMix(l: *const Launcher, g: CF, x: C, mixed: P, kind: c_int, rows: c_int, streams: c_int, dims: c_int, s: S) Error!void { + var a: Args = .{}; + inline for (.{ ad(g), ad(x), ad(mixed), kind, rows, streams, dims }) |v| try a.add(v); + try l.flat(l.fnx.hc_mix, @as(i64, rows) * dims, s, &a); +} + +/// The n-gram gate of every stream; `normed` is the conv's input rows. +pub fn pleGate(l: *const Launcher, kv: C, h: C, key_scale: CF, query_scale: CF, conv_scale: CF, gated: P, normed: P, kind: c_int, rows: c_int, streams: c_int, dims: c_int, eps: f32, s: S) Error!void { + if (dims > most_dims) return util.invalid("pleGate"); + var a: Args = .{}; + inline for (.{ ad(kv), ad(h), ad(key_scale), ad(query_scale), ad(conv_scale), ad(gated), ad(normed), kind, streams, dims, eps }) |v| try a.add(v); + try l.go(l.fnx.ple_gate, dim(streams, rows, 1), dim(threads, 1, 1), 0, s, &a); +} + +/// out = h + (gated + silu(conv)): the dilated causal conv over `cin`, its tail rows first. +pub fn pleConv(l: *const Launcher, cin: C, weight: CF, gated: C, h: C, out: P, kind: c_int, rows: c_int, width: c_int, taps: c_int, dilation: c_int, s: S) Error!void { + var a: Args = .{}; + inline for (.{ ad(cin), ad(weight), ad(gated), ad(h), ad(out), kind, rows, width, taps, dilation }) |v| try a.add(v); + try l.flat(l.fnx.ple_conv, @as(i64, rows) * width, s, &a); +} + +/// Each row's n-gram table rows; `meta` holds the history, eos, multipliers, sizes and offsets (int64). +pub fn ngramIds(l: *const Launcher, tokens: CI, meta: ?*const anyopaque, ids: P, rows: c_int, heads: c_int, per: c_int, n: c_int, s: S) Error!void { + var a: Args = .{}; + inline for (.{ ad(tokens), ad(meta), ad(ids), rows, heads, per, n }) |v| try a.add(v); + try l.flat(l.fnx.ngram_ids, @as(i64, rows) * heads, s, &a); +} + +/// Blocks first .. first + blocks of the raw indexer keys, pooled, normed and rotated into `pooled`. +pub fn idxPool(l: *const Launcher, raw: C, pooled: P, scale: CF, kind: c_int, first: c_int, blocks: c_int, dims: c_int, ratio: c_int, rotary: c_int, theta: f32, eps: f32, s: S) Error!void { + if (blocks == 0) return; + if (dims > threads) return util.invalid("idxPool"); + var a: Args = .{}; + inline for (.{ ad(raw), ad(pooled), ad(scale), kind, first, @as(u64, 0), dims, ratio, rotary, theta, eps }) |v| try a.add(v); + try l.go(l.fnx.idx_pool, dim(blocks, 1, 1), dim(threads, 1, 1), 0, s, &a); +} + +/// The blocks `rows` rows at device positions `pos` complete, pooled into their slots of `pooled` (all blocks'). +pub fn idxPoolAt(l: *const Launcher, raw: C, pooled: P, scale: CF, kind: c_int, pos: CI, rows: c_int, dims: c_int, ratio: c_int, rotary: c_int, theta: f32, eps: f32, s: S) Error!void { + if (rows == 0) return; + if (dims > threads) return util.invalid("idxPoolAt"); + var a: Args = .{}; + inline for (.{ ad(raw), ad(pooled), ad(scale), kind, @as(c_int, 0), ad(pos), dims, ratio, rotary, theta, eps }) |v| try a.add(v); + try l.go(l.fnx.idx_pool, dim(rows, 1, 1), dim(threads, 1, 1), 0, s, &a); +} + +/// Every row's score of each of `blocks` pooled blocks it has complete, for rows past `top` complete blocks. +pub fn idxScores(l: *const Launcher, q: CF, pooled: C, complete: CI, scores: F, kind: c_int, rows: c_int, heads: c_int, dims: c_int, blocks: c_int, stride: i64, top: c_int, s: S) Error!void { + if (blocks == 0) return; + if (dims > threads) return util.invalid("idxScores"); + var a: Args = .{}; + inline for (.{ ad(q), ad(pooled), ad(complete), ad(scores), kind, rows, heads, dims, blocks, stride, top }) |v| try a.add(v); + try l.go(l.fnx.idx_scores, dim(cdiv(blocks, 8), cdiv(rows, 8), 1), dim(threads, 1, 1), 0, s, &a); +} + +/// Each row's keys: its `top` best blocks and its tail past `top` complete blocks, else its first ends[r] keys. +pub fn idxSelect(l: *const Launcher, scores: CF, stride: i64, complete: CI, ends: CI, keys: I, key_stride: i64, count: I, sparse: I, rows: c_int, top: c_int, ratio: c_int, s: S) Error!void { + var a: Args = .{}; + inline for (.{ ad(scores), stride, ad(complete), ad(ends), ad(keys), key_stride, ad(count), ad(sparse), top, ratio }) |v| try a.add(v); + try l.go(l.fnx.idx_select, dim(rows, 1, 1), dim(1024, 1, 1), 0, s, &a); +} + +/// Attention of each row's heads over its listed keys (or its first count[r] keys) in `parts` parts, then merged. +pub fn sparseAttention(l: *const Launcher, q: CF, k: C, v: C, cache_kind: c_int, ids: CI, id_stride: i64, count: CI, sparse: CI, parts_o: F, parts_ms: F, out: F, rows: c_int, heads: c_int, kv_heads: c_int, dims: c_int, cap: i64, scale: f32, parts: c_int, s: S) Error!void { + if (dims > 256 or @rem(heads, kv_heads) != 0 or @divExact(heads, kv_heads) > 12) return util.invalid("sparseAttention"); + var a: Args = .{}; + inline for (.{ ad(q), ad(k), ad(v), cache_kind, ad(ids), id_stride, ad(count), ad(sparse), ad(parts_o), ad(parts_ms), heads, kv_heads, dims, cap, scale, parts }) |x| try a.add(x); + const wide: usize = if (@divExact(heads, kv_heads) <= 6) 0 else 1; + try l.go(l.fnx.sparse_parts[wide], dim(kv_heads, rows, parts), dim(256, 1, 1), 0, s, &a); + var b: Args = .{}; + inline for (.{ ad(parts_o), ad(parts_ms), ad(out), heads, dims, parts }) |x| try b.add(x); + try l.go(l.fnx.sparse_merge, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &b); +} From 2e2a03f1c8af11ec808c5329a25f86ac4aa34285 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:43:50 +0200 Subject: [PATCH 38/52] feat(flashnext): a window's n-gram rows on the host, where the HIP engine keeps the tables The HIP engine keeps the n-gram tables (30 GiB at 4 bits) in host memory and gathers the rows a window needs; Hasher hashes them as the reference's NGramEmbedding.ids does (segments cut at eos, 64-bit wrapping products, the floor modulus), checked against the Python ids of a window with eos inside and against the same window cut in two. The plan counts the tables' rows as the reference shards them (rounded up to the vocabulary divisor, the remainder on the first shards). --- zig/src/families/flashnext/hip.zig | 2 + zig/src/families/flashnext/hip/ngram.zig | 72 ++++++++++++++++++++++++ zig/src/families/flashnext/hip/plan.zig | 9 ++- 3 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 zig/src/families/flashnext/hip/ngram.zig diff --git a/zig/src/families/flashnext/hip.zig b/zig/src/families/flashnext/hip.zig index 8d293b01cd2..f9b7f5d1231 100644 --- a/zig/src/families/flashnext/hip.zig +++ b/zig/src/families/flashnext/hip.zig @@ -4,6 +4,7 @@ pub const Config = config.Config; pub const index = @import("index.zig"); pub const Spec = @import("spec.zig").Spec; pub const plan = @import("hip/plan.zig"); +pub const ngram = @import("hip/ngram.zig"); /// The registry entry of the native server. pub const native = @import("hip/native.zig"); @@ -11,5 +12,6 @@ test { _ = config; _ = index; _ = plan; + _ = ngram; _ = native; } diff --git a/zig/src/families/flashnext/hip/ngram.zig b/zig/src/families/flashnext/hip/ngram.zig new file mode 100644 index 00000000000..3f176b8d6a9 --- /dev/null +++ b/zig/src/families/flashnext/hip/ngram.zig @@ -0,0 +1,72 @@ +//! The n-gram table rows of a window on the host, where the tables live: the HIP engine gathers these rows' bytes. +const std = @import("std"); +const config = @import("../config.zig"); + +pub const heads = 16; +pub const n = 3; +/// Tokens before a window the hashes read. +pub const context = n - 1; + +pub const Hasher = struct { + ref: config.PleRef, + per: usize, + + pub fn init(c: *const config.Config) !Hasher { + return .{ .ref = try config.pleRef(c), .per = c.ngram_heads }; + } + + /// Row ids [tokens.len][heads] for `tokens` after `history` (oldest first); eos starts a new segment. + pub fn ids(h: *const Hasher, history: [context]i64, tokens: []const u32, out: [][heads]u32) void { + var seq: [context + 1]i64 = undefined; // the row and the context tokens before it, oldest first + @memcpy(seq[0..context], &history); + var run: usize = 0; // tokens of the segment before the row, counted up to n - 1 + for (history) |t| run = if (t == h.ref.eos) 0 else @min(run + 1, context); + for (tokens, out) |tok, *row| { + seq[context] = tok; + for (row, 0..) |*id, head| { + var mixed: u64 = 0; + for (0..2 + head / h.per) |q| { + const t = if (run >= q) seq[context - q] else h.ref.eos; + const term = @as(u64, @bitCast(t)) *% @as(u64, @bitCast(h.ref.multipliers[q])); + mixed = if (q == 0) term else mixed ^ term; + } + id.* = @intCast(@mod(@as(i64, @bitCast(mixed)), h.ref.sizes[head]) + h.ref.offsets[head]); + } + run = if (tok == h.ref.eos) 0 else @min(run + 1, context); + std.mem.copyForwards(i64, seq[0..context], seq[1 .. context + 1]); + } + } +}; + +/// The history after `tokens`: their last `context` tokens, the older history before them. +pub fn after(history: [context]i64, tokens: []const u32) [context]i64 { + var out = history; + for (tokens) |t| { + std.mem.copyForwards(i64, out[0 .. context - 1], out[1..context]); + out[context - 1] = t; + } + return out; +} + +test "the hashes of a window with eos inside equal the reference's rows" { + var c = try config.parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + const h = try Hasher.init(&c); + const tokens = [_]u32{ 5, 248044, 77, 90000, 248044, 248044, 3, 4, 248319, 0, 12 }; + var rows: [tokens.len][heads]u32 = undefined; + h.ids(.{ 11, 248044 }, &tokens, &rows); + // the Python embedding's ids() on the same history and tokens + const first = [_]u32{ 15389869, 18392917, 16611476, 15060967, 3987706, 9663979, 5318554, 11040574, 12308622, 3745007, 15226805 }; + const last = [_]u32{ 315720898, 301167364, 315908561, 316215863, 315670648, 300986548, 306094789, 314073144, 315610311, 302201836, 314647527 }; + for (rows, first, last) |row, a, b| { + try std.testing.expectEqual(a, row[0]); + try std.testing.expectEqual(b, row[heads - 1]); + } + try std.testing.expectEqualSlices(u32, &.{ 15389869, 39778609, 55713969, 62213332 }, rows[0][0..4]); + try std.testing.expectEqualSlices(u32, &.{ 160450612, 188182008, 207605318, 236922708 }, rows[3][8..12]); + // a window cut in two hashes the same rows when the second part starts from the first part's history + var split: [tokens.len][heads]u32 = undefined; + h.ids(.{ 11, 248044 }, tokens[0..4], split[0..4]); + h.ids(after(.{ 11, 248044 }, tokens[0..4]), tokens[4..], split[4..]); + try std.testing.expectEqualSlices([heads]u32, &rows, &split); +} diff --git a/zig/src/families/flashnext/hip/plan.zig b/zig/src/families/flashnext/hip/plan.zig index 1289a1df70c..072fc137a3d 100644 --- a/zig/src/families/flashnext/hip/plan.zig +++ b/zig/src/families/flashnext/hip/plan.zig @@ -74,7 +74,10 @@ pub fn weights(c: *const Config, s: Spec, world: u32) !Weights { if (!c.ple[i]) continue; const heads: u64 = try c.ngramHeadCount(); w.replicated += affine(s, wide, c.ple_dim) + affine(s, d, c.ple_dim) + 3 * wide * bf16 + wide * c.ple_conv * bf16 + (3 + 2 * heads) * 8; - w.host += c.ngram_shards * affine(s, try tableRows(c), c.ple_dim / heads); + const rows = try tableRows(c); + const base = rows / c.ngram_shards; + const extra = rows % c.ngram_shards; + w.host += (c.ngram_shards - extra) * affine(s, base, c.ple_dim / heads) + extra * affine(s, base + 1, c.ple_dim / heads); } if (c.mtp.layers > 0) { w.replicated += 2 * affine(s, d, d) + (d + wide) * bf16 + 2 * affine(s, c.hc_lowrank, wide) + wide * bf16; @@ -83,12 +86,12 @@ pub fn weights(c: *const Config, s: Spec, world: u32) !Weights { return w; } -/// Rows of one n-gram table shard: the heads' prime table sizes, together, cut in `ngram_shards` equal parts. +/// Rows of the n-gram tables: the heads' prime table sizes together, rounded up to the vocabulary divisor. pub fn tableRows(c: *const Config) !u64 { const ref = try config.pleRef(c); var rows: u64 = 0; for (ref.sizes) |n| rows += @intCast(n); - return std.math.divCeil(u64, rows, c.ngram_shards); + return try std.math.divCeil(u64, rows, c.ngram_divisor) * c.ngram_divisor; } /// A position's cache bytes on one rank: keys and values (kv_dtype bytes), the indexer's raw and pooled keys (bf16). From a56342b3c9eaf4fe2df2a6dd914770e704e01f46 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:52:40 +0200 Subject: [PATCH 39/52] feat(flashnext): the HIP forward on one device: weights, caches, host n-gram tables, every layer and the MTP head --- zig/build/hip.zig | 10 +- zig/src/families/flashnext/hip.zig | 16 + zig/src/families/flashnext/hip/cache.zig | 174 +++++++++++ .../flashnext/hip/checkpoint_tables.zig | 47 +++ zig/src/families/flashnext/hip/engine.zig | 205 +++++++++++++ zig/src/families/flashnext/hip/forward.zig | 182 +++++++++++ zig/src/families/flashnext/hip/head.zig | 79 +++++ zig/src/families/flashnext/hip/load.zig | 287 ++++++++++++++++++ zig/src/families/flashnext/hip/mixers.zig | 194 ++++++++++++ zig/src/families/flashnext/hip/model.zig | 145 +++++++++ zig/src/families/flashnext/hip/tables.zig | 79 +++++ zig/src/families/flashnext/hip/tensors.zig | 175 +++++++++++ zig/tests/flashnext_hip/main.zig | 130 ++++++++ 13 files changed, 1722 insertions(+), 1 deletion(-) create mode 100644 zig/src/families/flashnext/hip/cache.zig create mode 100644 zig/src/families/flashnext/hip/checkpoint_tables.zig create mode 100644 zig/src/families/flashnext/hip/engine.zig create mode 100644 zig/src/families/flashnext/hip/forward.zig create mode 100644 zig/src/families/flashnext/hip/head.zig create mode 100644 zig/src/families/flashnext/hip/load.zig create mode 100644 zig/src/families/flashnext/hip/mixers.zig create mode 100644 zig/src/families/flashnext/hip/model.zig create mode 100644 zig/src/families/flashnext/hip/tables.zig create mode 100644 zig/src/families/flashnext/hip/tensors.zig create mode 100644 zig/tests/flashnext_hip/main.zig diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 81c89004d57..6aa77578028 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -97,6 +97,14 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil test_step.dependOn(&server(b, b.graph.host, host, build_options).step); const gpu = engineModules(b, target, optimize, objects, hip_include); b.step("tf-qwen35-test", "Qwen3.5 / 3.6 model checks on the GPU (-Dhip-arch)").dependOn(&b.addInstallArtifact(checksExe(b, target, optimize, gpu), .{}).step); + const fx_test = b.addExecutable(.{ .name = "tf-flashnext-hip-test", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/flashnext_hip/main.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "hip", .module = gpu.hip }, .{ .name = "flashnext", .module = gpu.flashnext }, .{ .name = "tokenizer", .module = gpu.hip.import_table.get("core").?.import_table.get("tokenizer").? } }, + }) }); + b.step("tf-flashnext-hip-test", "Flash Next model checks on the GPU (-Dhip-arch)").dependOn(&b.addInstallArtifact(fx_test, .{}).step); const native = server(b, target, gpu, build_options); b.step("native-hip", "tensorfold-native with the HIP engines into zig-out/native-hip/bin (-Dhip-arch)").dependOn(&b.addInstallArtifact(native, .{ .dest_dir = .{ .override = .{ .custom = "native-hip/bin" } } }).step); } @@ -146,7 +154,7 @@ fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "lanes", .module = lanes } }, + .imports = &.{ .{ .name = "hip", .module = hip }, .{ .name = "lanes", .module = lanes }, .{ .name = "core", .module = core }, .{ .name = "engine_api", .module = api }, .{ .name = "hip_serve", .module = serve } }, }); const native = b.createModule(.{ .root_source_file = b.path("zig/src/native/hip.zig"), diff --git a/zig/src/families/flashnext/hip.zig b/zig/src/families/flashnext/hip.zig index f9b7f5d1231..a6a31abac2e 100644 --- a/zig/src/families/flashnext/hip.zig +++ b/zig/src/families/flashnext/hip.zig @@ -5,6 +5,14 @@ pub const index = @import("index.zig"); pub const Spec = @import("spec.zig").Spec; pub const plan = @import("hip/plan.zig"); pub const ngram = @import("hip/ngram.zig"); +pub const model = @import("hip/model.zig"); +pub const load = @import("hip/load.zig"); +pub const cache = @import("hip/cache.zig"); +pub const tables = @import("hip/tables.zig"); +pub const forward = @import("hip/forward.zig"); +pub const mixers = @import("hip/mixers.zig"); +pub const engine = @import("hip/engine.zig"); +pub const head = @import("hip/head.zig"); /// The registry entry of the native server. pub const native = @import("hip/native.zig"); @@ -13,5 +21,13 @@ test { _ = index; _ = plan; _ = ngram; + _ = model; + _ = cache; + @import("std").testing.refAllDecls(engine.Engine); + @import("std").testing.refAllDecls(load); + @import("std").testing.refAllDecls(forward); + @import("std").testing.refAllDecls(mixers); + @import("std").testing.refAllDecls(tables.Tables); + @import("std").testing.refAllDecls(head); _ = native; } diff --git a/zig/src/families/flashnext/hip/cache.zig b/zig/src/families/flashnext/hip/cache.zig new file mode 100644 index 00000000000..b1138f7fd1c --- /dev/null +++ b/zig/src/families/flashnext/hip/cache.zig @@ -0,0 +1,174 @@ +//! A stream's state on a rank: sparse layers' keys, DeltaNet states, the n-gram tail; a window's per-row snapshots. +const std = @import("std"); +const hip = @import("hip"); +const model = @import("model.zig"); + +const Dims = model.Dims; + +/// Most rows a verified window holds: the pending token and up to three drafts. +pub const max_window = 4; + +/// Where the bytes of one sparse layer's caches start, and their strides. +pub const SparseView = struct { k: u64, v: u64, raw: u64, pooled: u64 }; + +/// Where one DeltaNet layer's conv tail (fp32 (taps - 1, channels)) and recurrent state (fp32) live. +pub const LinearView = struct { conv: u64, state: u64 }; + +pub const Layout = struct { + sparse: usize, + linear: usize, + act: usize, + cap: usize, + kv_bytes: usize, + raw_bytes: usize, + pooled_bytes: usize, + conv_bytes: usize, + state_bytes: usize, + tail_rows: usize, + tail_bytes: usize, + kv_heads: usize, + head_dim: usize, + index_dim: usize, + ratio: usize, + + pub fn of(d: Dims, kinds: []const bool, cap: usize, act: model.Kind) Layout { + var sparse: usize = 0; + for (kinds) |linear| sparse += @intFromBool(!linear); + const a = act.size(); + const blocks = cap / d.index_ratio + 1; + return .{ + .sparse = sparse, + .linear = kinds.len - sparse, + .act = a, + .cap = cap, + .kv_bytes = d.kv_heads * cap * d.head_dim * a, + .raw_bytes = cap * d.index_dim * a, + .pooled_bytes = blocks * d.index_dim * a, + .conv_bytes = (d.conv - 1) * d.convWidth() * 4, + .state_bytes = d.value_heads * d.key_dim * d.value_dim * 4, + .tail_rows = d.ngram * (d.ple_taps - 1), + .tail_bytes = d.ngram * (d.ple_taps - 1) * d.wide() * a, + .kv_heads = d.kv_heads, + .head_dim = d.head_dim, + .index_dim = d.index_dim, + .ratio = d.index_ratio, + }; + } + + fn sparseBytes(l: Layout) usize { + return 2 * l.kv_bytes + l.raw_bytes + l.pooled_bytes; + } + + fn linearBytes(l: Layout) usize { + return l.conv_bytes + l.state_bytes; + } + + /// Device bytes of a stream's caches at `cap` positions. + pub fn bytes(l: Layout) usize { + return l.sparse * l.sparseBytes() + l.linear * l.linearBytes() + l.tail_bytes; + } + + /// Bytes of the state after `at` positions: the sparse layers' first `at` rows, the rest whole. + pub fn stateBytes(l: Layout, at: usize) usize { + const sparse_rows = 2 * l.kv_heads * at * l.head_dim * l.act + at * l.index_dim * l.act + at / l.ratio * l.index_dim * l.act; + return l.sparse * sparse_rows + l.linear * l.linearBytes() + l.tail_bytes; + } + + /// Device bytes of a window's snapshots: every DeltaNet layer's conv tail and state after each row. + pub fn windowBytes(l: Layout) usize { + return max_window * l.linear * l.linearBytes(); + } + + /// Device bytes of the n-gram conv's input over a window: the tail, then the window's rows. + pub fn cinBytes(l: Layout) usize { + return l.tail_bytes + max_window * (l.tail_bytes / l.tail_rows); + } +}; + +pub const Caches = struct { + layout: Layout, + /// Each layer's place among its kind (sparse or linear). + slot: []usize, + linear: []bool, + mem: hip.DeviceBuffer, + /// Snapshots of the last window: every linear layer's conv tails (a row each), then their states (a row each). + window: hip.DeviceBuffer, + /// The n-gram conv's input over the last window (the tail, then its rows): a keep takes its new tail from it. + cin: hip.DeviceBuffer, + /// Positions kept, and complete blocks pooled in every sparse layer. + len: usize = 0, + pooled: usize = 0, + /// The n-gram history: the last tokens before the next row (eos before any). + history: [2]i64, + + pub fn init(gpa: std.mem.Allocator, d: *const hip.Runtime, dims: Dims, kinds: []const bool, cap: usize, act: model.Kind, eos: i64) !Caches { + const layout = Layout.of(dims, kinds, cap, act); + const slot = try gpa.alloc(usize, kinds.len); + errdefer gpa.free(slot); + var counts: [2]usize = .{ 0, 0 }; + for (kinds, slot) |linear, *s| { + s.* = counts[@intFromBool(linear)]; + counts[@intFromBool(linear)] += 1; + } + const linear = try gpa.dupe(bool, kinds); + errdefer gpa.free(linear); + var mem = try hip.DeviceBuffer.alloc(d, layout.bytes()); + errdefer mem.free(); + try mem.fill8(0); + var window = try hip.DeviceBuffer.alloc(d, @max(layout.windowBytes(), 4)); + errdefer window.free(); + var cin = try hip.DeviceBuffer.alloc(d, layout.cinBytes()); + errdefer cin.free(); + return .{ .layout = layout, .slot = slot, .linear = linear, .mem = mem, .window = window, .cin = cin, .history = .{ eos, eos } }; + } + + pub fn deinit(c: *Caches, gpa: std.mem.Allocator) void { + c.cin.free(); + c.window.free(); + c.mem.free(); + gpa.free(c.slot); + gpa.free(c.linear); + c.* = undefined; + } + + pub fn sparse(c: *const Caches, layer: usize) SparseView { + const l = c.layout; + const at = c.mem.base() + c.slot[layer] * l.sparseBytes(); + return .{ .k = at, .v = at + l.kv_bytes, .raw = at + 2 * l.kv_bytes, .pooled = at + 2 * l.kv_bytes + l.raw_bytes }; + } + + pub fn linearAt(c: *const Caches, layer: usize) LinearView { + const l = c.layout; + const at = c.mem.base() + l.sparse * l.sparseBytes() + c.slot[layer] * l.linearBytes(); + return .{ .conv = at, .state = at + l.conv_bytes }; + } + + /// The n-gram conv's tail rows (act dtype, (tail_rows, W)). + pub fn tail(c: *const Caches) u64 { + const l = c.layout; + return c.mem.base() + l.sparse * l.sparseBytes() + l.linear * l.linearBytes(); + } + + /// Row `row` of the window's snapshots of linear layer `layer`; a layer's rows consecutive, as the kernels write. + pub fn snapshot(c: *const Caches, layer: usize, row: usize) LinearView { + const l = c.layout; + const n = c.slot[layer] * max_window + row; + const states = c.window.base() + l.linear * max_window * l.conv_bytes; + return .{ .conv = c.window.base() + n * l.conv_bytes, .state = states + n * l.state_bytes }; + } +}; + +test "a stream's bytes at tp 4: 12 sparse layers' caches, 36 DeltaNet states and the n-gram tail" { + const config = @import("../config.zig"); + var c = try config.parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + const d = try Dims.of(&c, 4); + var kinds: [48]bool = undefined; + for (&kinds, 0..) |*k, i| k.* = (try c.kind(i)) == .linear_attention; + const l = Layout.of(d, &kinds, 4096, .f16); + try std.testing.expectEqual(@as(usize, 12), l.sparse); + try std.testing.expectEqual(@as(usize, 36), l.linear); + const per_layer = 2 * 4096 * 256 * 2 + 4096 * 128 * 2 + 1025 * 128 * 2; + const linear = 3 * 2560 * 4 + 12 * 128 * 128 * 4; + try std.testing.expectEqual(@as(usize, 12 * per_layer + 36 * linear + 9 * 10240 * 2), l.bytes()); +} diff --git a/zig/src/families/flashnext/hip/checkpoint_tables.zig b/zig/src/families/flashnext/hip/checkpoint_tables.zig new file mode 100644 index 00000000000..c6ec7c7f920 --- /dev/null +++ b/zig/src/families/flashnext/hip/checkpoint_tables.zig @@ -0,0 +1,47 @@ +//! The checkpoint as core/quant reads it for the HIP loader: tensors by name, code widths from the config. +const std = @import("std"); +const Config = @import("../config.zig").Config; + +/// Each side passes its own core's checkpoint and width types (one by path, one as a module). +pub fn Tables(comptime Checkpoint: type, comptime Width: type) type { + const Got = @typeInfo(@TypeOf(Checkpoint.get)).@"fn".return_type.?; + return struct { + ck: *Checkpoint, + cfg: *const Config, + + const Self = @This(); + + pub fn has(t: *const Self, key: []const u8) bool { + return t.ck.has(key); + } + + pub fn get(t: *const Self, key: []const u8) Got { + return t.ck.get(key); + } + + /// The width core/quant reads `key`'s words and group tables with. + pub fn width(t: *const Self, key: []const u8) !Width { + const s = (try t.cfg.quantization(key)) orelse return error.UnsupportedQuantization; + return .{ .bits = s.bits, .group = @intCast(s.group) }; + } + }; +} + +test "a projection's width comes from the config's table" { + var c = try @import("../config.zig").parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + const Fake = struct { + pub fn has(_: *@This(), _: []const u8) bool { + return false; + } + pub fn get(_: *@This(), _: []const u8) !u8 { + return error.NotFound; + } + }; + var f: Fake = .{}; + const t: Tables(Fake, struct { bits: u8, group: u16 }) = .{ .ck = &f, .cfg = &c }; + const w = try t.width("language_model.model.layers.0.linear_attn.in_proj_qkv"); + try std.testing.expectEqual(@as(u8, 6), w.bits); + try std.testing.expectEqual(@as(u16, 32), w.group); + try std.testing.expect(!t.has("x")); +} diff --git a/zig/src/families/flashnext/hip/engine.zig b/zig/src/families/flashnext/hip/engine.zig new file mode 100644 index 00000000000..f610206165a --- /dev/null +++ b/zig/src/families/flashnext/hip/engine.zig @@ -0,0 +1,205 @@ +//! Flash Next on one HIP device: the kernels, a stream, the rank's weights, the host n-gram tables and the scratch. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const serve = @import("hip_serve"); +const config = @import("../config.zig"); +const model = @import("model.zig"); +const load = @import("load.zig"); +const tables = @import("tables.zig"); +const cache = @import("cache.zig"); +const forward = @import("forward.zig"); +const mixers = @import("mixers.zig"); +const index = @import("../index.zig"); + +pub const Options = struct { + device: c_int = 0, + policy: hip.Policy = .{}, + /// Positions a stream holds at most (its prompt, reply and a window's rows). + capacity: usize = 4096, + /// Prompt rows a forward takes at most: a multiple of 64, so a prompt's bits do not depend on where it is cut. + chunk: usize = 512, +}; + +/// Bytes of the pinned staging a forward's uploads and n-gram rows go through. +const staging_bytes = 64 << 20; + +pub const Engine = struct { + gpa: std.mem.Allocator, + io: std.Io, + driver: hip.Runtime, + ctx: hip.Context, + lib: hip.Launcher, + stream: hip.Stream, + o: Options, + cfg: config.Config, + ck: core.checkpoint.Checkpoint, + /// The n-gram tables' row views and other loader leftovers that live as long as the engine. + keep: std.heap.ArenaAllocator, + weights: load.Weights, + tables: tables.Tables, + host: forward.Host, + qk: [2]hip.DeviceBuffer, + arena: hip.Arena, + drawer: serve.draw.Drawer, + act: model.Kind, + eos: i64, + + /// The checkpoint `dir` on device `o.device`, this rank's share loaded; the scratch sized for `o.chunk` rows. + pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !*Engine { + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.gpa = gpa; + e.io = io; + e.o = o; + e.driver = try hip.Runtime.open(); + errdefer e.driver.close(); + e.ctx = try hip.Context.init(&e.driver, o.device); + errdefer e.ctx.deinit(); + const caps = try hip.Device.kernelCaps(&e.driver, o.device); + e.lib = try hip.Launcher.load(&e.driver, o.policy.choices(), hip.kernels.images); + errdefer e.lib.unload(); + e.act = if (caps.act == .f16) .f16 else .bf16; + e.stream = try hip.Stream.init(&e.driver); + errdefer e.stream.deinit(); + e.cfg = try config.Config.read(gpa, io, dir); + errdefer e.cfg.deinit(); + e.ck = try core.checkpoint.Checkpoint.openModel(gpa, io, dir); + errdefer e.ck.close(); + e.keep = .init(gpa); + errdefer e.keep.deinit(); + e.weights = try load.load(gpa, &e.driver, &e.ck, &e.cfg, e.act); + errdefer e.weights.deinit(); + const spelling = try spellingOf(e.keep.allocator(), io, dir); + e.tables = try tables.Tables.init(e.keep.allocator(), &e.ck, &e.cfg, e.weights.model.ple.layer, spelling); + const c = mixers.qkConstants(e.cfg.key_dim); + var w: [2]hip.DeviceBuffer = undefined; + for (&w, [_]f32{ c.q, c.k }) |*b, v| { + const vals = try gpa.alloc(f32, e.cfg.key_dim); + defer gpa.free(vals); + @memset(vals, v); + b.* = try hip.DeviceBuffer.fromHost(&e.driver, std.mem.sliceAsBytes(vals)); + } + e.qk = w; + errdefer for (&e.qk) |*b| b.free(); + e.weights.model.qk = .{ .q = e.qk[0].base(), .k = e.qk[1].base(), .eps = c.eps }; + e.host = .{ .gpa = gpa, .d = &e.driver, .staging = try hip.HostBuffer.alloc(&e.driver, staging_bytes), .tables = &e.tables }; + errdefer e.host.staging.free(); + e.eos = e.tables.hasher.ref.eos; + e.arena = try hip.Arena.init(&e.driver, try e.scratchBytes()); + errdefer e.arena.deinit(); + e.drawer = try serve.draw.Drawer.init(gpa, &e.driver, if (e.act == .f16) .f16 else .bf16, e.cfg.vocab, cache.max_window * forward.max_segs); + return e; + } + + pub fn deinit(e: *Engine) void { + e.stream.synchronize() catch {}; + e.drawer.deinit(); + e.arena.deinit(); + e.host.staging.free(); + for (&e.qk) |*b| b.free(); + e.weights.deinit(); + e.keep.deinit(); + e.ck.close(); + e.cfg.deinit(); + e.stream.deinit(); + e.lib.unload(); + e.ctx.deinit(); + e.driver.close(); + e.gpa.destroy(e); + } + + pub fn model_(e: *const Engine) *const model.Model { + return &e.weights.model; + } + + pub fn ops(e: *Engine, arena: *hip.Arena) hip.ops.Ops { + return .{ .l = &e.lib, .bf16 = e.act == .bf16, .stream = e.stream.handle, .arena = arena }; + } + + /// The layer kinds as the caches lay them out: true for a DeltaNet layer. + pub fn kinds(e: *const Engine, out: []bool) ![]const bool { + for (out[0..e.cfg.layers], 0..) |*k, i| k.* = (try e.cfg.kind(i)) == .linear_attention; + return out[0..e.cfg.layers]; + } + + /// A stream's caches for `cap` positions. + pub fn caches(e: *Engine, cap: usize) !cache.Caches { + var buf: [config.max_layers]bool = undefined; + return cache.Caches.init(e.gpa, &e.driver, e.weights.model.dims, try e.kinds(&buf), cap, e.act, e.eos); + } + + /// The scratch the largest forward takes: a prompt chunk at the capacity's end, counted on a dry run. + fn scratchBytes(e: *Engine) !usize { + var counting = hip.Arena.counting(); + var o = e.ops(&counting); + o.stream = hip.counting; + var c = try e.caches(@max(e.o.capacity, e.o.chunk) + cache.max_window); + defer c.deinit(e.gpa); + const tokens = try e.gpa.alloc(u32, e.o.chunk); + defer e.gpa.free(tokens); + @memset(tokens, 0); + const before = e.host.used; + defer e.host.used = before; + const out = try forward.run(o, &e.weights.model, &e.host, &.{.{ .c = &c, .tokens = tokens, .pos = e.o.capacity -| e.o.chunk }}, false); + _ = try e.logits(o, out.mixed, e.o.chunk); + return counting.used + (16 << 20); + } + + /// The output head over `rows` final rows: whole logits rows (act dtype). + pub fn logits(e: *Engine, o: hip.ops.Ops, mixed: hip.ops.Tensor, rows: usize) !hip.ops.Tensor { + return o.project(mixed, e.weights.model.head, rows, false); + } + + /// The first `kept` rows of a window from `c.len` become the stream's: DeltaNet states, n-gram tail and history. + pub fn keepWindow(e: *Engine, c: *cache.Caches, tokens: []const u32, kept: usize) !void { + if (kept == 0 or kept > tokens.len) return error.BadKeep; + const l = c.layout; + const s = e.stream.handle; + if (kept < tokens.len) for (c.linear, 0..) |linear, i| { + if (!linear) continue; + const from = c.snapshot(i, kept - 1); + const to = c.linearAt(i); + try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync(@ptrFromInt(to.conv), @ptrFromInt(from.conv), l.conv_bytes, s)); + try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync(@ptrFromInt(to.state), @ptrFromInt(from.state), l.state_bytes, s)); + }; + const row = l.tail_bytes / l.tail_rows; + try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync(@ptrFromInt(c.tail()), @ptrFromInt(c.cin.base() + kept * row), l.tail_bytes, s)); + c.history = @import("ngram.zig").after(c.history, tokens[0..kept]); + c.len += kept; + c.pooled = @min(c.pooled, c.len / e.cfg.index_ratio); + } + + /// A prompt's `tokens` from `c.len` into `c`, kept: the final rows of the last of them. + pub fn prompt(e: *Engine, c: *cache.Caches, tokens: []const u32) !forward.Out { + const out = try e.run(c, tokens, c.len, false); + c.len += tokens.len; + return out; + } + + /// `tokens` from `pos` through the forward into `c`; a prompt's rows, or a window's (kept later). + pub fn run(e: *Engine, c: *cache.Caches, tokens: []const u32, pos: usize, window: bool) !forward.Out { + // the staging is reused: the last forward's uploads must have left it + try e.stream.synchronize(); + e.host.used = 0; + e.arena.reset(); + return e.runMany(&.{.{ .c = c, .tokens = tokens, .pos = pos }}, window); + } + + /// Several streams' rows in one forward (every segment from its own caches): windows of a shared round. + pub fn runMany(e: *Engine, segs: []const forward.Seg, window: bool) !forward.Out { + try e.stream.synchronize(); + e.host.used = 0; + e.arena.reset(); + return forward.run(e.ops(&e.arena), &e.weights.model, &e.host, segs, window); + } +}; + +/// The index's spelling of its n-gram shards (`shard_` or oMLX's `shards.`). +fn spellingOf(a: std.mem.Allocator, io: std.Io, dir: []const u8) ![]const u8 { + const path = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 26)); + const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}); + const map = doc.object.get("weight_map") orelse return error.InvalidFlashIndex; + return index.ngramSpelling(map.object); +} diff --git a/zig/src/families/flashnext/hip/forward.zig b/zig/src/families/flashnext/hip/forward.zig new file mode 100644 index 00000000000..4d8e7d98bc9 --- /dev/null +++ b/zig/src/families/flashnext/hip/forward.zig @@ -0,0 +1,182 @@ +//! Flash Next's forward on a HIP rank: a stream's rows through every layer, a window's each with a serial step's bits. +const std = @import("std"); +const hip = @import("hip"); +const model = @import("model.zig"); +const cache = @import("cache.zig"); +const tables = @import("tables.zig"); +const mixers = @import("mixers.zig"); +const ngram = @import("ngram.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const Kind = hip.ops.Kind; + +/// What a forward reads from the host: the pinned staging its uploads go through, and the n-gram tables. +pub const Host = struct { + gpa: std.mem.Allocator, + d: *const hip.Runtime, + staging: hip.HostBuffer, + /// Bytes of `staging` this forward used: the stream is synchronized before a forward starts again. + used: usize = 0, + tables: *const tables.Tables, + + /// `bytes` copied through the staging into fresh arena memory, queued on the stream. + pub fn put(h: *Host, o: Ops, bytes: []const u8) !u64 { + const from = std.mem.alignForward(usize, h.used, 16); + if (from + bytes.len > h.staging.bytes.len) return error.StagingTooSmall; + const dst = try o.arena.take(bytes.len); + @memcpy(h.staging.bytes[from..][0..bytes.len], bytes); + h.used = from + bytes.len; + if (o.stream != hip.counting and bytes.len > 0) try hip.runtime.check(h.d.api.hipMemcpyHtoDAsync(@ptrFromInt(dst), h.staging.bytes[from..].ptr, bytes.len, o.stream)); + return dst; + } +}; + +/// A device buffer of `n` values of `kind` from the arena. +pub fn take(o: Ops, kind: Kind, n: usize) !Tensor { + return .{ .ptr = try o.arena.take(n * kind.size()), .kind = kind }; +} + +/// `t` advanced by `n` values. +pub fn at(t: Tensor, n: usize) Tensor { + return .{ .ptr = t.ptr + n * t.kind.size(), .kind = t.kind }; +} + +/// One call's rows: their tokens, the position of the first, and whether they are a window (else a prompt's). +pub const Call = struct { tokens: []const u32, pos: usize, window: bool }; + +/// One stream's rows in a forward: its caches, its tokens and the position of its first row. +pub const Seg = struct { c: *cache.Caches, tokens: []const u32, pos: usize }; + +/// The final mixer's rows (rows, hidden) for the head, and the residual streams (rows, wide) before it. +pub const Out = struct { mixed: Tensor, streams: Tensor }; + +/// A hyper-connection's read of the normed streams `x`: the block input, and the inject gates when `inject` is set. +pub fn hcPre(o: Ops, m: *const model.Model, hc: model.Hc, x: Tensor, rows: usize, inject: ?Tensor) !Tensor { + const d = m.dims; + const z = try o.project(x, hc.down, rows, true); + const act = try take(o, m.act, rows * d.low); + const kind = @backingInt(m.act); + try o.l.fn_hc_gates(@ptrFromInt(z.ptr), @ptrFromInt(act.ptr), if (inject) |i| @ptrFromInt(i.ptr) else null, kind, @intCast(rows), @intCast(d.low), @intCast(d.streams), o.stream); + const g = try o.project(act, hc.up, rows, true); + const mixed = try take(o, m.act, rows * d.hidden); + try o.l.fn_hc_mix(@ptrFromInt(g.ptr), @ptrFromInt(x.ptr), @ptrFromInt(mixed.ptr), kind, @intCast(rows), @intCast(d.streams), @intCast(d.hidden), o.stream); + return mixed; +} + +/// h += round(branch * inject) per stream when a branch is given, then x = the streams normed with `scale`. +pub fn hcNorm(o: Ops, m: *const model.Model, h: Tensor, branch: ?Tensor, inject: ?Tensor, x: Tensor, scale: u64, rows: usize) !void { + const d = m.dims; + try o.l.fn_hc_norm(@ptrFromInt(h.ptr), if (branch) |b| @ptrFromInt(b.ptr) else null, if (inject) |i| @ptrFromInt(i.ptr) else null, if (branch != null) @ptrFromInt(h.ptr) else null, @ptrFromInt(x.ptr), @ptrFromInt(scale), @backingInt(m.act), @intCast(rows), @intCast(d.streams), @intCast(d.hidden), d.eps, o.stream); +} + +/// The n-gram layer over `rows` rows: h += gated + silu(conv); `cin` is the conv input (the tail, then the rows). +fn ple(o: Ops, m: *const model.Model, host: *Host, c: *cache.Caches, h: Tensor, call: Call, cin: u64) !void { + const d = m.dims; + const rows = call.tokens.len; + const t = host.tables; + const heads = d.ple_dim / t.dims; + if (heads != ngram.heads) return error.UnsupportedNgramHeads; + var buf: [64][ngram.heads]u32 = undefined; + const mark = o.arena.mark(); + defer o.arena.release(mark); + const emb = try take(o, m.act, rows * d.ple_dim); + var row: usize = 0; + var history = c.history; + while (row < rows) : (row += buf.len) { + const n = @min(buf.len, rows - row); + t.hasher.ids(history, call.tokens[row..][0..n], buf[0..n]); + history = ngram.after(history, call.tokens[row..][0..n]); + const flat: []const u32 = @as([*]const u32, @ptrCast(&buf))[0 .. n * heads]; + const count = n * heads; + const wb = t.wordBytes(); + const tb = t.tableBytes(); + const words = try o.arena.take(count * wb); + const scales = try o.arena.take(count * tb); + const biases = try o.arena.take(count * tb); + const stage = host.staging.bytes; + const at0 = std.mem.alignForward(usize, host.used, 16); + if (at0 + count * (wb + 2 * tb) > stage.len) return error.StagingTooSmall; + try t.gather(flat, stage[at0..][0 .. count * wb], stage[at0 + count * wb ..][0 .. count * tb], stage[at0 + count * (wb + tb) ..][0 .. count * tb]); + host.used = at0 + count * (wb + 2 * tb); + if (o.stream != hip.counting) { + try hip.runtime.check(host.d.api.hipMemcpyHtoDAsync(@ptrFromInt(words), stage[at0..].ptr, count * wb, o.stream)); + try hip.runtime.check(host.d.api.hipMemcpyHtoDAsync(@ptrFromInt(scales), stage[at0 + count * wb ..].ptr, count * tb, o.stream)); + try hip.runtime.check(host.d.api.hipMemcpyHtoDAsync(@ptrFromInt(biases), stage[at0 + count * (wb + tb) ..].ptr, count * tb, o.stream)); + } + var iota: [64 * 16]i32 = undefined; + for (iota[0..count], 0..) |*x, i| x.* = @intCast(i); + const local = try host.put(o, std.mem.sliceAsBytes(iota[0..count])); + try o.l.tf_embed_rows(@ptrFromInt(words), @ptrFromInt(scales), @ptrFromInt(biases), @backingInt(Kind.bf16), @ptrFromInt(local), @intCast(count), t.bits, @intCast(t.group), @intCast(t.dims), @ptrFromInt(at(emb, row * d.ple_dim).ptr), @backingInt(m.act), o.stream); + } + const kv = try o.project(emb, m.ple.kv, rows, false); + const gated = try take(o, m.act, rows * d.wide()); + const tail = c.layout.tail_rows * d.wide() * m.act.size(); + try hip.raw.copy(.{ .r = host.d, .ptr = @ptrFromInt(cin), .len = tail }, 0, c.tail(), tail, o.stream); + const kind = @backingInt(m.act); + try o.l.fn_ple_gate(@ptrFromInt(kv.ptr), @ptrFromInt(h.ptr), @ptrFromInt(m.ple.key_scale), @ptrFromInt(m.ple.query_scale), @ptrFromInt(m.ple.conv_scale), @ptrFromInt(gated.ptr), @ptrFromInt(cin + tail), kind, @intCast(rows), @intCast(d.streams), @intCast(d.hidden), d.eps, o.stream); + try o.l.fn_ple_conv(@ptrFromInt(cin), @ptrFromInt(m.ple.conv), @ptrFromInt(gated.ptr), @ptrFromInt(h.ptr), @ptrFromInt(h.ptr), kind, @intCast(rows), @intCast(d.wide()), @intCast(d.ple_taps), @intCast(d.ngram), o.stream); + // a prompt's rows are kept: the tail moves on now; a window's waits for its keep + if (!call.window) { + try hip.raw.copy(.{ .r = host.d, .ptr = @ptrFromInt(c.tail()), .len = tail }, 0, cin + rows * d.wide() * m.act.size(), tail, o.stream); + c.history = history; + } +} + +/// Every segment's rows through every layer: one stream's prompt chunk, or several streams' windows together. +pub fn run(ops: Ops, m: *const model.Model, host: *Host, segs: []const Seg, window: bool) !Out { + var o = ops; + o.prefill = !window; + o.window = window; + const d = m.dims; + var rows: usize = 0; + for (segs) |g| rows += g.tokens.len; + const ids4 = try host.gpa.alloc(i32, rows * d.streams); + defer host.gpa.free(ids4); + const pos = try host.gpa.alloc(i32, rows); + defer host.gpa.free(pos); + var row: usize = 0; + for (segs) |g| { + for (g.tokens, 0..) |t, r| { + for (0..d.streams) |s| ids4[(row + r) * d.streams + s] = @intCast(t); + pos[row + r] = @intCast(g.pos + r); + } + row += g.tokens.len; + } + const dev_ids = try host.put(o, std.mem.sliceAsBytes(ids4)); + const dev_pos = try host.put(o, std.mem.sliceAsBytes(pos)); + const h = try take(o, m.act, rows * d.wide()); + const x = try take(o, m.act, rows * d.wide()); + try o.embedRows(m.embed, dev_ids, rows * d.streams, h); + var cins: [max_segs]u64 = undefined; + if (segs.len > max_segs) return error.TooManyStreams; + for (segs, cins[0..segs.len]) |g, *cin| cin.* = if (window) g.c.cin.base() else try o.arena.take((g.c.layout.tail_rows + g.tokens.len) * d.wide() * m.act.size()); + for (m.layers, 0..) |layer, i| { + const mark = o.arena.mark(); + defer o.arena.release(mark); + if (i == m.ple.layer) { + var off: usize = 0; + for (segs, cins[0..segs.len]) |g, cin| { + try ple(o, m, host, g.c, at(h, off * d.wide()), .{ .tokens = g.tokens, .pos = g.pos, .window = window }, cin); + off += g.tokens.len; + } + } + if (i == 0 or i == m.ple.layer) try hcNorm(o, m, h, null, null, x, layer.ahc.scale, rows); + const inject = try take(o, m.act, rows * d.streams); + const mixed = try hcPre(o, m, layer.ahc, x, rows, inject); + const branch = switch (layer.mixer) { + .linear => |l| try mixers.linear(o, m, l, segs, i, mixed, rows, window), + .sparse => |s| try mixers.sparse(o, m, d, s, segs, i, mixed, rows, dev_pos, host), + }; + try hcNorm(o, m, h, branch, inject, x, layer.mhc.scale, rows); + const mixed2 = try hcPre(o, m, layer.mhc, x, rows, inject); + const y = try hip.moe.run(o, m.act, layer.moe, mixed2, rows, !window); + const next = if (i + 1 < m.layers.len) m.layers[i + 1].ahc.scale else m.mix.scale; + try hcNorm(o, m, h, y, inject, x, next, rows); + } + for (segs) |g| g.c.pooled = (g.pos + g.tokens.len) / d.index_ratio; + return .{ .mixed = try hcPre(o, m, m.mix, x, rows, null), .streams = h }; +} + +/// Streams a forward takes at once at most. +pub const max_segs = 64; diff --git a/zig/src/families/flashnext/hip/head.zig b/zig/src/families/flashnext/hip/head.zig new file mode 100644 index 00000000000..ba3c58f1003 --- /dev/null +++ b/zig/src/families/flashnext/hip/head.zig @@ -0,0 +1,79 @@ +//! The MTP head on the drafting rank: its forward over (residual streams, next token) rows, and greedy draft chains. +const std = @import("std"); +const hip = @import("hip"); +const model = @import("model.zig"); +const cache = @import("cache.zig"); +const forward = @import("forward.zig"); +const mixers = @import("mixers.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const take = forward.take; + +pub const Out = forward.Out; + +/// The head's caches: one sparse layer at the whole model's heads. +pub fn caches(gpa: std.mem.Allocator, d: *const hip.Runtime, h: *const model.Head, cap: usize, act: model.Kind, eos: i64) !cache.Caches { + return cache.Caches.init(gpa, d, h.dims, &.{false}, cap, act, eos); +} + +/// `tokens` (each the token after its row) over residual `streams` from `pos`; `ones` a one a stream a row. +pub fn run(ops: Ops, m: *const model.Model, host: *forward.Host, c: *cache.Caches, streams: Tensor, tokens: []const u32, pos: usize, ones: hip.DeviceBuffer) !Out { + var o = ops; + o.window = true; + const w = &m.mtp.?; + const d = w.dims; + const rows = tokens.len; + if (rows * d.streams * m.act.size() > ones.len) return error.HeadRowsPastOnes; + const ids = try host.gpa.alloc(i32, rows); + defer host.gpa.free(ids); + const at_pos = try host.gpa.alloc(i32, rows); + defer host.gpa.free(at_pos); + for (ids, at_pos, tokens, 0..) |*i, *p, t, r| { + i.* = @intCast(t); + p.* = @intCast(pos + r); + } + const dev_ids = try host.put(o, std.mem.sliceAsBytes(ids)); + const dev_pos = try host.put(o, std.mem.sliceAsBytes(at_pos)); + const emb = try take(o, m.act, rows * d.hidden); + try o.embedRows(m.embed, dev_ids, rows, emb); + const en = try take(o, m.act, rows * d.hidden); + try o.rms(emb, w.e_norm, en, rows, d.hidden, d.eps); + const e = try o.project(en, w.fc_e, rows, false); + const hn = try take(o, m.act, rows * d.wide()); + try o.l.fn_rms_wide(@ptrFromInt(streams.ptr), @ptrFromInt(w.h_norm), @ptrFromInt(hn.ptr), @backingInt(m.act), @intCast(rows), @intCast(d.wide()), d.eps, o.stream); + const h = try o.project(hn, w.fc_h, rows * d.streams, false); + const x = try take(o, m.act, rows * d.wide()); + const l = w.layer; + // the embedding broadcast over the streams: h += round(e * 1) per stream, then the layer's first norm + try forward.hcNorm(o, m, h, e, .{ .ptr = ones.base(), .kind = m.act }, x, l.ahc.scale, rows); + const inject = try take(o, m.act, rows * d.streams); + const mixed = try forward.hcPre(o, m, l.ahc, x, rows, inject); + const seg = [_]forward.Seg{.{ .c = c, .tokens = tokens, .pos = pos }}; + c.pooled = @min(c.pooled, pos / d.index_ratio); + const branch = try mixers.sparse(o, m, d, l.mixer.sparse, &seg, 0, mixed, rows, dev_pos, host); + try forward.hcNorm(o, m, h, branch, inject, x, l.mhc.scale, rows); + const mixed2 = try forward.hcPre(o, m, l.mhc, x, rows, inject); + const y = try hip.moe.run(o, m.act, l.moe, mixed2, rows, false); + try forward.hcNorm(o, m, h, y, inject, x, w.mix.scale, rows); + c.pooled = (pos + rows) / d.index_ratio; + return .{ .mixed = try forward.hcPre(o, m, w.mix, x, rows, null), .streams = h }; +} + +/// The draft head's greedy token for each of `rows` mixed rows (argmax over the draft vocabulary) and its probability. +pub fn draws(o: Ops, m: *const model.Model, host: *forward.Host, s: hip.Stream, mixed: Tensor, rows: usize, ids: []const u32, out: []u32, probs: []f32) !void { + const w = &m.mtp.?; + const logits = try o.project(mixed, w.draft, rows, false); + const arg = try o.arena.of(i32, 2 * rows); + try o.argmaxRows(logits, rows, w.draft.n, arg); + try o.tokenProb(logits, rows, w.draft.n, arg, arg + rows * 4); + const at = std.mem.alignForward(usize, host.used, 16); + const bytes = host.staging.bytes[at..][0 .. 2 * rows * 4]; + try hip.runtime.check(host.d.api.hipMemcpyDtoHAsync(bytes.ptr, @ptrFromInt(arg), 2 * rows * 4, s.handle)); + try s.synchronize(); + const words = std.mem.bytesAsSlice(u32, @as([]align(4) u8, @alignCast(bytes))); + for (out[0..rows], probs[0..rows], words[0..rows], words[rows..]) |*t, *p, i, f| { + t.* = ids[i]; + p.* = @bitCast(f); + } +} diff --git a/zig/src/families/flashnext/hip/load.zig b/zig/src/families/flashnext/hip/load.zig new file mode 100644 index 00000000000..ebb14254132 --- /dev/null +++ b/zig/src/families/flashnext/hip/load.zig @@ -0,0 +1,287 @@ +//! Flash Next's checkpoint onto a HIP device: each tensor read from the mapped shards and uploaded. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const config = @import("../config.zig"); +const tensors = @import("tensors.zig"); +const model = @import("model.zig"); + +const quant = core.quant; +const Tensor = core.checkpoint.Tensor; +const Host = quant.Host; +const Span = quant.Span; +const Allocator = std.mem.Allocator; + +/// The table core/quant reads projections through: the family's checkpoint tables, over core's checkpoint. +pub const Tables = @import("checkpoint_tables.zig").Tables(core.checkpoint.Checkpoint, core.quant.mlx.Width); + +/// The device copy of the weights: every buffer it uploaded, freed together. +pub const Weights = struct { + gpa: Allocator, + buffers: std.ArrayList(hip.DeviceBuffer) = .empty, + layers: []model.Layer = &.{}, + model: model.Model = undefined, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.* = undefined; + } +}; + +const Loader = struct { + a: Allocator, + t: *const Tables, + up: hip.Upload, + /// The checkpoint stores centred norms as gamma (true) or as gamma - 1 (false). + around_one: bool, + + fn key(l: *const Loader, comptime fmt: []const u8, args: anytype) ![]const u8 { + return std.fmt.allocPrint(l.a, fmt, args); + } + + /// A projection, its rows and inputs checked against the model's description where it gives them. + fn proj(l: *const Loader, k: []const u8) !Host { + const h = try quant.read(l.a, l.t, k); + const want = (try tensors.shape(l.t.cfg, k)) orelse return h; + const n, const width = switch (h) { + .mlx => |m| .{ m.words.shape[0], m.scales.shape[1] * m.group }, + else => return h, + }; + if (n != want.n or width != want.k) return error.UnexpectedShape; + return h; + } + + fn put(l: *const Loader, h: Host) !model.Projection { + return quant.view(try quant.upload(l.up.uploader(), h), false); + } + + fn tensor(l: *const Loader, t: Tensor) !u64 { + return (try l.up.uploader().tensor(t)).ptr; + } + + /// A float tensor widened to fp32. + fn float(l: *const Loader, k: []const u8) !Tensor { + return quant.convert.float32(l.a, try l.t.get(k)); + } + + /// A centred RMSNorm's fp32 scale from its stored value (tensors.centred). + fn scale(l: *const Loader, k: []const u8) !u64 { + var t = try l.float(k); + const v = try floats(l.a, t); + for (v) |*x| x.* = tensors.centred(x.*, l.around_one); + t.bytes = std.mem.sliceAsBytes(v); + return l.tensor(t); + } + + /// The down projection with the inject rows stacked under it: one product gives the low rank and the gates. + fn hc(l: *const Loader, base: []const u8, inject: bool) !model.Hc { + var down = try l.proj(try l.named(base, tensors.hc.down)); + if (inject) down = try stackRows(l.a, down, try l.proj(try l.named(base, tensors.hc.inject))); + return .{ + .scale = try l.scale(try l.named(base, tensors.hc.norm)), + .down = try l.put(down), + .up = try l.put(try l.proj(try l.named(base, tensors.hc.up))), + }; + } + + /// `name` under `stem`. + fn named(l: *const Loader, stem: []const u8, name: []const u8) ![]const u8 { + return std.fmt.allocPrint(l.a, "{s}.{s}", .{ stem, name }); + } + + fn linear(l: *const Loader, base: []const u8) !model.Linear { + const t = tensors.linear; + var conv_t = try l.float(try l.named(base, t.conv)); + conv_t.rank = 2; + return .{ + .qkv = try l.put(try l.proj(try l.named(base, t.qkv))), + .z = try l.put(try l.proj(try l.named(base, t.z))), + .a = try l.put(try l.proj(try l.named(base, t.a))), + .b = try l.put(try l.proj(try l.named(base, t.b))), + .out = try l.put(try l.proj(try l.named(base, t.out))), + .conv = try l.tensor(conv_t), + .a_log = try l.tensor(try l.float(try l.named(base, t.a_log))), + .dt_bias = try l.tensor(try l.float(try l.named(base, t.dt_bias))), + .norm = try l.tensor(try l.float(try l.named(base, t.norm))), + }; + } + + fn sparse(l: *const Loader, base: []const u8) !model.Sparse { + const t = tensors.sparse; + return .{ + .q = try l.put(try l.proj(try l.named(base, t.q))), + .k = try l.put(try l.proj(try l.named(base, t.k))), + .v = try l.put(try l.proj(try l.named(base, t.v))), + .o = try l.put(try l.proj(try l.named(base, t.o))), + .index = try l.put(try l.proj(try l.named(base, t.index))), + .q_norm = try l.scale(try l.named(base, t.q_norm)), + .k_norm = try l.scale(try l.named(base, t.k_norm)), + .iq_norm = try l.scale(try l.named(base, t.iq_norm)), + .ik_norm = try l.scale(try l.named(base, t.ik_norm)), + }; + } + + fn moe(l: *const Loader, base: []const u8, c: *const config.Config) !model.Routed { + const r = try quant.experts.routed(l.a, l.t, try l.key("{s}.{s}", .{ base, tensors.moe.prefix }), .{ .experts = c.experts, .hidden = c.hidden, .top_k = c.topk }); + const u = l.up.uploader(); + return .{ + .rows32 = (try u.tensor(r.rows32)).ptr, + .top_k = r.top_k, + .rows = r.router.shape[0], + .remap = if (r.remap) |t| (try u.tensor(t)).ptr else 0, + .exact = true, + .experts = .{ + .fused = try quant.view(try quant.upload(u, r.experts.fused), true), + .down = try quant.view(try quant.upload(u, r.experts.down), true), + .count = r.experts.count, + .width = r.experts.width, + .dims = r.experts.dims, + }, + }; + } + + fn layer(l: *const Loader, base: []const u8, c: *const config.Config, kind: config.Kind) !model.Layer { + return .{ + .ahc = try l.hc(try l.named(base, tensors.hc.attn), true), + .mhc = try l.hc(try l.named(base, tensors.hc.mlp), true), + .mixer = switch (kind) { + .linear_attention => .{ .linear = try l.linear(base) }, + .sparse_attention => .{ .sparse = try l.sparse(base) }, + }, + .moe = try l.moe(base, c), + }; + } + + fn ple(l: *const Loader, index: usize) !model.Ple { + var buf: [128]u8 = undefined; + const base = try tensors.layer(&buf, index); + const t = tensors.ple; + const kv = try stackRows(l.a, try l.proj(try l.named(base, t.key)), try l.proj(try l.named(base, t.value))); + var conv = try l.float(try l.named(base, t.conv)); + conv.rank = 2; + return .{ + .layer = index, + .kv = try l.put(kv), + .key_scale = try l.scale(try l.named(base, t.norm_key)), + .query_scale = try l.scale(try l.named(base, t.norm_query)), + .conv_scale = try l.scale(try l.named(base, t.norm_conv)), + .conv = try l.tensor(conv), + }; + } +}; + +/// An fp32 tensor's values copied out (its bytes may sit at any alignment). +fn floats(a: Allocator, t: Tensor) ![]f32 { + const v = try a.alloc(f32, t.bytes.len / 4); + @memcpy(std.mem.sliceAsBytes(v), t.bytes); + return v; +} + +/// Rows of `under` stacked below `top` (one product for both): same K, bits and group. +fn stackRows(a: Allocator, top: Host, under: Host) !Host { + const t = top.mlx; + const u = under.mlx; + if (t.bits != u.bits or t.group != u.group or t.words.shape[1] != u.words.shape[1]) return error.UnexpectedTensor; + return .{ .mlx = .{ .words = try join(a, t.words, u.words), .scales = try join(a, t.scales, u.scales), .biases = try join(a, t.biases, u.biases), .bits = t.bits, .group = t.group } }; +} + +fn join(a: Allocator, x: Tensor, y: Tensor) !Tensor { + if (x.dtype != y.dtype or x.rank != 2 or y.rank != 2 or x.shape[1] != y.shape[1]) return error.UnexpectedTensor; + const bytes = try a.alloc(u8, x.bytes.len + y.bytes.len); + @memcpy(bytes[0..x.bytes.len], x.bytes); + @memcpy(bytes[x.bytes.len..], y.bytes); + var out = x; + out.shape[0] = x.shape[0] + y.shape[0]; + out.bytes = bytes; + return out; +} + +/// Whether the centred norms are stored as gamma, from every layer's attention hc norm mean (tensors.normsAroundOne). +fn aroundOne(a: Allocator, t: *const Tables, layers: usize) !bool { + const means = try a.alloc(f64, layers); + for (means, 0..) |*m, i| { + var buf: [128]u8 = undefined; + const k = try std.fmt.allocPrint(a, "{s}.{s}.{s}", .{ try tensors.layer(&buf, i), tensors.hc.attn, tensors.hc.norm }); + const v = try floats(a, try quant.convert.float32(a, try t.get(k))); + var sum: f64 = 0; + for (v) |x| sum += x; + m.* = sum / @as(f64, @floatFromInt(v.len)); + } + return tensors.normsAroundOne(means); +} + +/// The draft head's rows: the family's draft vocabulary (ascending ids) of the output head. +pub const draft_ids = @embedFile("../draft_vocab_default.txt"); + +fn draftSpans(a: Allocator) ![]Span { + var list: std.ArrayList(Span) = .empty; + var it = std.mem.tokenizeAny(u8, draft_ids, "\n\r "); + while (it.next()) |word| { + const id = try std.fmt.parseInt(usize, word, 10); + if (list.items.len > 0 and list.items[list.items.len - 1].to == id) { + list.items[list.items.len - 1].to += 1; + } else try list.append(a, .{ .from = id, .to = id + 1 }); + } + return list.items; +} + +/// The draft vocabulary as token ids. +pub fn draftIds(a: Allocator) ![]u32 { + var list: std.ArrayList(u32) = .empty; + var it = std.mem.tokenizeAny(u8, draft_ids, "\n\r "); + while (it.next()) |word| try list.append(a, try std.fmt.parseInt(u32, word, 10)); + return list.toOwnedSlice(a); +} + +test "the draft ids are one allocation of the vocabulary's length" { + const ids = try draftIds(std.testing.allocator); + defer std.testing.allocator.free(ids); + try std.testing.expectEqual(@as(usize, 79591), ids.len); +} + +/// The whole model's weights from the mapped checkpoint `ck`, the MTP head's included. +pub fn load(gpa: Allocator, d: *const hip.Runtime, ck: *core.checkpoint.Checkpoint, c: *const config.Config, act: model.Kind) !Weights { + var w: Weights = .{ .gpa = gpa }; + errdefer w.deinit(); + const tables: Tables = .{ .ck = ck, .cfg = c }; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const l: Loader = .{ .a = arena.allocator(), .t = &tables, .up = .{ .r = d, .buffers = &w.buffers, .gpa = gpa }, .around_one = try aroundOne(arena.allocator(), &tables, c.layers) }; + const dims = try model.Dims.of(c, 1); + const head = try l.proj(tensors.lm_head); + w.layers = try gpa.alloc(model.Layer, c.layers); + var ple: ?model.Ple = null; + for (0..c.layers) |i| { + _ = arena.reset(.retain_capacity); + var buf: [128]u8 = undefined; + w.layers[i] = try l.layer(try tensors.layer(&buf, i), c, try c.kind(i)); + if (c.ple[i]) ple = try l.ple(i); + } + _ = arena.reset(.retain_capacity); + w.model = .{ + .dims = dims, + .act = act, + .embed = try l.put(try l.proj(tensors.embed)), + .layers = w.layers, + .mix = try l.hc(tensors.mixer, false), + .head = try l.put(head), + .ple = ple orelse return error.NoPleLayer, + }; + if (c.mtp.layers > 0) { + _ = arena.reset(.retain_capacity); + const draft_rows = try quant.sliceRows(l.a, head, try draftSpans(l.a)); + w.model.mtp = .{ + .e_norm = try l.scale(tensors.mtp.norm_embedding), + .h_norm = try l.scale(tensors.mtp.norm_hidden), + .fc_e = try l.put(try l.proj(tensors.mtp.fc_embedding)), + .fc_h = try l.put(try l.proj(tensors.mtp.fc_hidden)), + .layer = try l.layer(tensors.mtp.layer0, c, c.mtp.kinds[0]), + .mix = try l.hc(tensors.mtp.mixer, false), + .dims = try model.Dims.of(c, 1), + .draft = try l.put(draft_rows), + }; + } + return w; +} diff --git a/zig/src/families/flashnext/hip/mixers.zig b/zig/src/families/flashnext/hip/mixers.zig new file mode 100644 index 00000000000..161127aeeb0 --- /dev/null +++ b/zig/src/families/flashnext/hip/mixers.zig @@ -0,0 +1,194 @@ +//! Flash Next's two mixers on a HIP rank: the Gated DeltaNet and the sparse attention with its indexer. +const std = @import("std"); +const hip = @import("hip"); +const model = @import("model.zig"); +const cache = @import("cache.zig"); +const forward = @import("forward.zig"); + +const Ops = hip.ops.Ops; +const Tensor = hip.ops.Tensor; +const take = forward.take; + +/// normalize_qk's constants: q and k scaled by rsqrt(sum + 1e-6) (q also by dk^-0.5) as an RMS norm with a weight. +pub fn qkConstants(key_dim: usize) struct { q: f32, k: f32, eps: f32 } { + const inv = std.math.pow(f64, @floatFromInt(key_dim), -0.5); + return .{ .q = @floatCast(inv * inv), .k = @floatCast(inv), .eps = @floatCast(1e-6 * inv * inv) }; +} + +/// The Gated DeltaNet over every segment: products and norms on all rows, conv and recurrence a stream at a time. +pub fn linear(o: Ops, m: *const model.Model, l: model.Linear, segs: []const forward.Seg, index: usize, x: Tensor, rows: usize, window: bool) !Tensor { + const d = m.dims; + const ch = d.convWidth(); + const kw = d.key_heads * d.key_dim; + const vw = d.value_heads * d.value_dim; + var outs: [4]Tensor = undefined; + if (!try o.projectGroup(x, &.{ l.qkv, l.z, l.a, l.b }, rows, &outs)) { + for (&outs, [_]model.Projection{ l.qkv, l.z, l.a, l.b }) |*t, p| t.* = try o.project(x, p, rows, false); + } + const qkv, const z, const a, const b = outs; + const q = try o.arena.of(f32, rows * kw); + const k = try o.arena.of(f32, rows * kw); + const v = try o.arena.of(f32, rows * vw); + const gate = try o.arena.of(f32, rows * d.value_heads); + const beta = try o.arena.of(f32, rows * d.value_heads); + if (window) { + // a window's conv, split, q and k norms and gates in one launch a stream, each row's conv state kept aside + var at_row: usize = 0; + for (segs) |g| { + const n = g.tokens.len; + const nh = n * d.value_heads; + try o.l.tf_conv_split(.{ + .x = forward.at(qkv, at_row * ch).ptr, + .kind = @backingInt(m.act), + .weight = l.conv, + .state = g.c.linearAt(index).conv, + .states = g.c.snapshot(index, 0).conv, + .qn = q + at_row * kw * 4, + .kn = k + at_row * kw * 4, + .v = v + at_row * vw * 4, + .channels = @intCast(ch), + .kernel = @intCast(d.conv), + .rows = @intCast(n), + .kw = @intCast(kw), + .vw = @intCast(vw), + .qw = m.qk.q, + .kw_w = m.qk.k, + .eps = m.qk.eps, + .norm = 128, + .ga = forward.at(a, at_row * d.value_heads).ptr, + .gb = forward.at(b, at_row * d.value_heads).ptr, + .a_log = l.a_log, + .dt_bias = l.dt_bias, + .gate = gate + at_row * d.value_heads * 4, + .beta = beta + at_row * d.value_heads * 4, + .gcount = @intCast(nh), + .heads = @intCast(d.value_heads), + }, o.stream); + at_row += n; + } + return recur(o, m, l, segs, index, q, k, v, gate, beta, z, rows, true); + } + const mixed = try o.arena.of(f32, rows * ch); + var off: usize = 0; + for (segs) |g| { + const n = g.tokens.len; + const st = g.c.linearAt(index); + const out = mixed + off * ch * 4; + const conv_bytes = (d.conv - 1) * ch * 4; + const next = try o.arena.take(conv_bytes); + try o.convPrefill(forward.at(qkv, off * ch), l.conv, st.conv, out, next, n, ch, d.conv); + if (o.stream != hip.counting) try hip.runtime.check(o.l.r.api.hipMemcpyDtoDAsync(@ptrFromInt(st.conv), @ptrFromInt(next), conv_bytes, o.stream)); + off += n; + } + const mixed_t: Tensor = .{ .ptr = mixed, .kind = .f32 }; + const qc = try o.arena.of(f32, rows * kw); + const kc = try o.arena.of(f32, rows * kw); + try o.copyCols(mixed_t, ch, 0, qc, rows, kw); + try o.copyCols(mixed_t, ch, kw, kc, rows, kw); + try o.copyCols(mixed_t, ch, 2 * kw, v, rows, vw); + try o.rms(.{ .ptr = qc, .kind = .f32 }, m.qk.q, .{ .ptr = q, .kind = .f32 }, rows * d.key_heads, d.key_dim, m.qk.eps); + try o.rms(.{ .ptr = kc, .kind = .f32 }, m.qk.k, .{ .ptr = k, .kind = .f32 }, rows * d.key_heads, d.key_dim, m.qk.eps); + try o.gdnGatePrefill(a, b, l.a_log, l.dt_bias, gate, beta, rows, d.value_heads); + return recur(o, m, l, segs, index, q, k, v, gate, beta, z, rows, false); +} + +/// The delta rule a stream at a time (a window's rows each with its state kept aside), the gated norm, the out product. +fn recur(o: Ops, m: *const model.Model, l: model.Linear, segs: []const forward.Seg, index: usize, q: u64, k: u64, v: u64, gate: u64, beta: u64, z: Tensor, rows: usize, window: bool) !Tensor { + const d = m.dims; + const kw = d.key_heads * d.key_dim; + const vw = d.value_heads * d.value_dim; + const y = try o.arena.of(f32, rows * vw); + var off: usize = 0; + for (segs) |g| { + const n = g.tokens.len; + const snaps: ?u64 = if (window) g.c.snapshot(index, 0).state else null; + try o.gatedDelta(q + off * kw * 4, k + off * kw * 4, v + off * vw * 4, gate + off * d.value_heads * 4, beta + off * d.value_heads * 4, g.c.linearAt(index).state, y + off * vw * 4, n, d.key_heads, d.value_heads, d.key_dim, d.value_dim, snaps); + off += n; + } + const out = try take(o, m.act, rows * vw); + try o.gnormOut(y, l.norm, z, out, rows * d.value_heads, d.value_dim, d.eps, .sigmoid); + return o.project(out, l.out, rows, l.out.partial); +} + +/// Rows of a prompt's attention a slice: the indexer's scores and the attention's parts stay bounded. +const slice_rows = 64; +const parts = 16; + +/// The sparse attention over every segment's rows: products on all rows, each stream's caches, blocks and keys its own. +pub fn sparse(o: Ops, m: *const model.Model, d: model.Dims, s: model.Sparse, segs: []const forward.Seg, layer: usize, x: Tensor, rows: usize, dev_pos: u64, host: *forward.Host) !Tensor { + const hd = d.head_dim; + const di = d.index_dim; + const width = (d.index_heads + 1) * di; + const kind = @backingInt(m.act); + var outs: [4]Tensor = undefined; + if (!try o.projectGroup(x, &.{ s.q, s.k, s.v, s.index }, rows, &outs)) { + for (&outs, [_]model.Projection{ s.q, s.k, s.v, s.index }) |*t, p| t.* = try o.project(x, p, rows, false); + } + const qg, const keys, const values, const idx = outs; + const q32 = try o.arena.of(f32, rows * d.heads * hd); + try o.qkRope(qg, d.heads * 2 * hd, 2 * hd, s.q_norm, d.eps, rows, d.heads, hd, d.rotary, d.theta, dev_pos, q32, null, 0); + const iq = try o.arena.of(f32, rows * d.index_heads * di); + try o.qkRope(idx, width, di, s.iq_norm, d.eps, rows, d.index_heads, di, d.rotary, d.theta, dev_pos, iq, null, 0); + const att = try o.arena.of(f32, rows * d.heads * hd); + var off: usize = 0; + for (segs) |g| { + const n = g.tokens.len; + const kv = g.c.sparse(layer); + const cap = g.c.layout.cap; + const pos = g.pos; + try o.qkRope(forward.at(keys, off * d.kv_heads * hd), d.kv_heads * hd, hd, s.k_norm, d.eps, n, d.kv_heads, hd, d.rotary, d.theta, dev_pos + off * 4, null, kv.k, cap); + try o.kvWrite(forward.at(values, off * d.kv_heads * hd), kv.v, n, d.kv_heads, hd, cap, pos); + try o.copyCols(forward.at(idx, off * width), width, d.index_heads * di, kv.raw + pos * di * m.act.size(), n, di); + const blocks = (pos + n) / d.index_ratio; + const pooled = g.c.pooled; + if (blocks > pooled) try o.l.fn_idx_pool(@ptrFromInt(kv.raw), @ptrFromInt(kv.pooled + pooled * di * m.act.size()), @ptrFromInt(s.ik_norm), kind, @intCast(pooled), @intCast(blocks - pooled), @intCast(di), @intCast(d.index_ratio), @intCast(d.rotary), d.theta, d.eps, o.stream); + try attend(o, m, d, kv, cap, q32 + off * d.heads * hd * 4, iq + off * d.index_heads * di * 4, att + off * d.heads * hd * 4, n, pos, host); + off += n; + } + const gated = try take(o, m.act, rows * d.heads * hd); + try o.attnGate(att, qg, gated, rows, d.heads, hd, true); + return o.project(gated, s.o, rows, s.o.partial); +} + +/// One stream's `rows` rows from `pos` over its caches, in slices: each row's keys chosen, then attended. +fn attend(o: Ops, m: *const model.Model, d: model.Dims, kv: cache.SparseView, cap: usize, q32: u64, iq: u64, att: u64, rows: usize, pos: usize, host: *forward.Host) !void { + const hd = d.head_dim; + const di = d.index_dim; + const kind = @backingInt(m.act); + const key_stride = d.index_top * d.index_ratio + d.index_ratio; + var r0: usize = 0; + while (r0 < rows) : (r0 += slice_rows) { + const n = @min(slice_rows, rows - r0); + const mark = o.arena.mark(); + defer o.arena.release(mark); + var complete: [slice_rows]i32 = undefined; + var ends: [slice_rows]i32 = undefined; + var sparse_rows = false; + for (0..n) |r| { + ends[r] = @intCast(pos + r0 + r + 1); + complete[r] = @divFloor(ends[r], @as(i32, @intCast(d.index_ratio))); + sparse_rows = sparse_rows or complete[r] > d.index_top; + } + const dev_complete = try host.put(o, std.mem.sliceAsBytes(complete[0..n])); + const dev_ends = try host.put(o, std.mem.sliceAsBytes(ends[0..n])); + var ids: ?u64 = null; + var sparse_flags: ?u64 = null; + var count = dev_ends; + if (sparse_rows) { + const nb: usize = @intCast(complete[n - 1]); + const scores = try o.arena.of(f32, n * nb); + try o.l.fn_idx_scores(@ptrFromInt(iq + r0 * d.index_heads * di * 4), @ptrFromInt(kv.pooled), @ptrFromInt(dev_complete), @ptrFromInt(scores), kind, @intCast(n), @intCast(d.index_heads), @intCast(di), @intCast(nb), @intCast(nb), @intCast(d.index_top), o.stream); + const list = try o.arena.of(i32, n * key_stride); + const counts = try o.arena.of(i32, n); + const flags = try o.arena.of(i32, n); + try o.l.fn_idx_select(@ptrFromInt(scores), @intCast(nb), @ptrFromInt(dev_complete), @ptrFromInt(dev_ends), @ptrFromInt(list), @intCast(key_stride), @ptrFromInt(counts), @ptrFromInt(flags), @intCast(n), @intCast(d.index_top), @intCast(d.index_ratio), o.stream); + ids = list; + sparse_flags = flags; + count = counts; + } + const po = try o.arena.of(f32, n * d.heads * parts * hd); + const pm = try o.arena.of(f32, n * d.heads * parts * 2); + const scale: f32 = @floatCast(1.0 / std.math.sqrt(@as(f64, @floatFromInt(hd)))); + try o.l.fn_sparse_attention(@ptrFromInt(q32 + r0 * d.heads * hd * 4), @ptrFromInt(kv.k), @ptrFromInt(kv.v), @backingInt(m.act), if (ids) |i| @ptrFromInt(i) else null, @intCast(key_stride), @ptrFromInt(count), if (sparse_flags) |f| @ptrFromInt(f) else null, @ptrFromInt(po), @ptrFromInt(pm), @ptrFromInt(att + r0 * d.heads * hd * 4), @intCast(n), @intCast(d.heads), @intCast(d.kv_heads), @intCast(hd), @intCast(cap), scale, parts, o.stream); + } +} diff --git a/zig/src/families/flashnext/hip/model.zig b/zig/src/families/flashnext/hip/model.zig new file mode 100644 index 00000000000..8f28669a2f1 --- /dev/null +++ b/zig/src/families/flashnext/hip/model.zig @@ -0,0 +1,145 @@ +//! Flash Next on a HIP rank: the device weights the forward reads, and the dimensions this rank sees. +const std = @import("std"); +const hip = @import("hip"); +const config = @import("../config.zig"); + +pub const Projection = hip.ops.Projection; +pub const Kind = hip.ops.Kind; +pub const Routed = hip.moe.Routed; + +/// The dimensions of the checkpoint, and this rank's share of the heads tensor parallelism splits. +pub const Dims = struct { + hidden: usize, + streams: usize, + low: usize, + vocab: usize, + layers: usize, + eps: f32, + heads: usize, + kv_heads: usize, + head_dim: usize, + rotary: usize, + theta: f32, + key_heads: usize, + value_heads: usize, + key_dim: usize, + value_dim: usize, + conv: usize, + index_heads: usize, + index_dim: usize, + index_ratio: usize, + index_top: usize, + ple_dim: usize, + ple_taps: usize, + ngram: usize, + /// The rank's slice of the vocabulary rows of the head. + vocab_rows: usize, + + pub fn wide(d: Dims) usize { + return d.hidden * d.streams; + } + + pub fn convWidth(d: Dims) usize { + return 2 * d.key_heads * d.key_dim + d.value_heads * d.value_dim; + } + + /// This rank's dimensions: query, value and key heads by rank, a kv head held by `world / kv_heads` ranks. + pub fn of(c: *const config.Config, world: usize) error{UnevenSplit}!Dims { + for ([_]usize{ c.heads, c.key_heads, c.value_heads, c.vocab }) |n| if (n % world != 0) return error.UnevenSplit; + if (world > c.kv_heads and world % c.kv_heads != 0) return error.UnevenSplit; + return .{ + .hidden = c.hidden, + .streams = c.hc_count, + .low = c.hc_lowrank, + .vocab = c.vocab, + .layers = c.layers, + .eps = c.eps, + .heads = c.heads / world, + .kv_heads = @max(1, c.kv_heads / world), + .head_dim = c.head_dim, + .rotary = c.rotary_dim, + .theta = @floatCast(c.rope_theta), + .key_heads = c.key_heads / world, + .value_heads = c.value_heads / world, + .key_dim = c.key_dim, + .value_dim = c.value_dim, + .conv = c.conv, + .index_heads = c.index_heads, + .index_dim = c.index_dim, + .index_ratio = c.index_ratio, + .index_top = c.index_budget / c.index_ratio, + .ple_dim = c.ple_dim, + .ple_taps = c.ple_conv, + .ngram = c.ngram, + .vocab_rows = c.vocab / world, + }; + } +}; + +/// A hyper-connection: its stream norm's fp32 scale (W), the down projection with the inject rows under it, the up. +pub const Hc = struct { scale: u64, down: Projection, up: Projection }; + +pub const Linear = struct { + qkv: Projection, + z: Projection, + a: Projection, + b: Projection, + out: Projection, + /// fp32 (channels, taps), a_log and dt_bias fp32 (value heads), the gated norm's fp32 weight (value dim). + conv: u64, + a_log: u64, + dt_bias: u64, + norm: u64, +}; + +pub const Sparse = struct { + q: Projection, + k: Projection, + v: Projection, + o: Projection, + index: Projection, + /// fp32 scales: q and k norms (head dim), the indexer's q and k norms (index dim). + q_norm: u64, + k_norm: u64, + iq_norm: u64, + ik_norm: u64, +}; + +pub const Mixer = union(enum) { linear: Linear, sparse: Sparse }; + +pub const Layer = struct { ahc: Hc, mhc: Hc, mixer: Mixer, moe: Routed }; + +/// The n-gram layer: key and value projections stacked, three norms' fp32 scales (W), the conv's fp32 taps (W, taps). +pub const Ple = struct { layer: usize, kv: Projection, key_scale: u64, query_scale: u64, conv_scale: u64, conv: u64 }; + +/// The MTP head, whole on the drafting rank: input norms, projections, one sparse layer, its mixer, draft-vocab rows. +pub const Head = struct { e_norm: u64, h_norm: u64, fc_e: Projection, fc_h: Projection, layer: Layer, mix: Hc, dims: Dims, draft: Projection }; + +/// The DeltaNet's q and k normalization as RMS norms: constant fp32 weights (key dim wide) and their eps. +pub const Qk = struct { q: u64, k: u64, eps: f32 }; + +pub const Model = struct { + dims: Dims, + qk: Qk = undefined, + act: Kind, + embed: Projection, + layers: []const Layer, + mix: Hc, + /// The output head: this rank's rows of the vocabulary. + head: Projection, + ple: Ple, + mtp: ?Head = null, +}; + +test "a rank's dimensions: heads, value heads and the vocabulary split, the kv heads held two ranks a head" { + var c = try config.parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + const d = try Dims.of(&c, 4); + try std.testing.expectEqual(@as(usize, 6), d.heads); + try std.testing.expectEqual(@as(usize, 1), d.kv_heads); + try std.testing.expectEqual(@as(usize, 12), d.value_heads); + try std.testing.expectEqual(@as(usize, 4), d.key_heads); + try std.testing.expectEqual(@as(usize, 512), d.index_top); + try std.testing.expectEqual(@as(usize, 2 * 4 * 128 + 12 * 128), d.convWidth()); + try std.testing.expectError(error.UnevenSplit, Dims.of(&c, 3)); +} diff --git a/zig/src/families/flashnext/hip/tables.zig b/zig/src/families/flashnext/hip/tables.zig new file mode 100644 index 00000000000..828663972a4 --- /dev/null +++ b/zig/src/families/flashnext/hip/tables.zig @@ -0,0 +1,79 @@ +//! The n-gram tables in host memory (the checkpoint's mapped shards): a window's rows gathered for the device. +const std = @import("std"); +const core = @import("core"); +const config = @import("../config.zig"); +const tensors = @import("tensors.zig"); +const ngram = @import("ngram.zig"); + +/// One shard's packed rows and their group tables, as mapped. +const Shard = struct { words: []const u8, scales: []const u8, biases: []const u8 }; + +pub const Tables = struct { + shards: []Shard, + /// The first row of each shard, and one past the last. + starts: []usize, + dims: usize, + bits: u8, + group: usize, + hasher: ngram.Hasher, + + /// Bytes of a row's packed words, and of its scales (as of its biases). + pub fn wordBytes(t: Tables) usize { + return t.dims * t.bits / 8; + } + + pub fn tableBytes(t: Tables) usize { + return t.dims / t.group * 2; + } + + /// The tables of the PLE layer `layer` from the mapped checkpoint; the shards' rows as the reference splits them. + pub fn init(a: std.mem.Allocator, ck: *core.checkpoint.Checkpoint, c: *const config.Config, layer: usize, spelling: []const u8) !Tables { + const heads = try c.ngramHeadCount(); + const ref = try config.pleRef(c); + var total: usize = 0; + for (ref.sizes) |s| total += @intCast(s); + const rows = try std.math.divCeil(usize, total, c.ngram_divisor) * c.ngram_divisor; + const base = rows / c.ngram_shards; + const extra = rows % c.ngram_shards; + const shards = try a.alloc(Shard, c.ngram_shards); + const starts = try a.alloc(usize, c.ngram_shards + 1); + starts[0] = 0; + var spec: ?@import("../spec.zig").Spec = null; + for (shards, 0..) |*s, i| { + var lb: [128]u8 = undefined; + var nb: [256]u8 = undefined; + const stem = try a.dupe(u8, try tensors.ple.table(&nb, try tensors.layer(&lb, layer), spelling, i)); + const n = base + @intFromBool(i < extra); + starts[i + 1] = starts[i] + n; + const w = try ck.get(try std.fmt.allocPrint(a, "{s}.weight", .{stem})); + const sc = try ck.get(try std.fmt.allocPrint(a, "{s}.scales", .{stem})); + const bi = try ck.get(try std.fmt.allocPrint(a, "{s}.biases", .{stem})); + if (spec == null) spec = (try c.quantization(stem)) orelse return error.UnsupportedQuantization; + if (w.shape[0] != n or sc.dtype != .bf16 or bi.dtype != .bf16) return error.UnexpectedNgramTable; + s.* = .{ .words = w.bytes, .scales = sc.bytes, .biases = bi.bytes }; + } + const dims = c.ple_dim / heads; + if (shards[0].words.len != (starts[1] - starts[0]) * dims * spec.?.bits / 8) return error.UnexpectedNgramTable; + return .{ .shards = shards, .starts = starts, .dims = dims, .bits = spec.?.bits, .group = spec.?.group, .hasher = try ngram.Hasher.init(c) }; + } + + /// Each id's packed words, scales and biases copied into the three staging slices, in id order. + pub fn gather(t: *const Tables, ids: []const u32, words: []u8, scales: []u8, biases: []u8) !void { + const wb = t.wordBytes(); + const tb = t.tableBytes(); + if (words.len < ids.len * wb or scales.len < ids.len * tb or biases.len < ids.len * tb) return error.StagingTooSmall; + for (ids, 0..) |id, i| { + const s = std.sort.upperBound(usize, t.starts, @as(usize, id), struct { + fn order(x: usize, y: usize) std.math.Order { + return std.math.order(x, y); + } + }.order) - 1; + if (s >= t.shards.len) return error.NgramRowOutOfRange; + const row = id - t.starts[s]; + const sh = t.shards[s]; + @memcpy(words[i * wb ..][0..wb], sh.words[row * wb ..][0..wb]); + @memcpy(scales[i * tb ..][0..tb], sh.scales[row * tb ..][0..tb]); + @memcpy(biases[i * tb ..][0..tb], sh.biases[row * tb ..][0..tb]); + } + } +}; diff --git a/zig/src/families/flashnext/hip/tensors.zig b/zig/src/families/flashnext/hip/tensors.zig new file mode 100644 index 00000000000..92446e2e8a5 --- /dev/null +++ b/zig/src/families/flashnext/hip/tensors.zig @@ -0,0 +1,175 @@ +//! Flash Next's tensors as the HIP loader reads them: names, shapes and centred norm storage. +const std = @import("std"); +const Config = @import("../config.zig").Config; + +/// Every text tensor's prefix (the vision tower's sit outside it). +pub const root = "language_model."; +pub const embed = "language_model.model.embed_tokens"; +pub const lm_head = "language_model.lm_head"; +pub const mixer = "language_model.model.hyper_connection_mixer"; + +/// Decoder layer `i`'s stem. +pub fn layer(buf: []u8, i: usize) ![]const u8 { + return std.fmt.bufPrint(buf, "language_model.model.layers.{d}", .{i}); +} + +/// The MTP head's tensors (one decoder layer, `layer0`). +pub const mtp = struct { + pub const stem = "language_model.mtp"; + pub const layer0 = "language_model.mtp.layers.0"; + pub const fc_e = "fc_embedding"; + pub const fc_h = "fc_hidden"; + pub const fc_embedding = stem ++ "." ++ fc_e; + pub const fc_hidden = stem ++ "." ++ fc_h; + pub const norm_embedding = "language_model.mtp.pre_fc_norm_embedding.weight"; + pub const norm_hidden = "language_model.mtp.pre_fc_norm_hidden.weight"; + pub const mixer = "language_model.mtp.hyper_connection_mixer"; +}; + +/// A hyper-connection under a layer's stem (`attn` or `mlp`) or the mixers: its norm and projections. +pub const hc = struct { + pub const attn = "attn_hyper_connection"; + pub const mlp = "mlp_hyper_connection"; + pub const norm = "hc_norm.weight"; + pub const down = "input_mix_weight_down"; + pub const up = "input_mix_weight_up"; + pub const inject = "block_inject_weight"; +}; + +/// The MoE block under a layer's stem: the router, the shared expert's gate and projections, the routed experts. +pub const moe = struct { + pub const prefix = "mlp."; + pub const gate = "mlp.gate"; + pub const shared_gate = "mlp.shared_expert_gate"; + pub const shared = [_][]const u8{ "mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.shared_expert.down_proj" }; + pub const routed = [_][]const u8{ "mlp.switch_mlp.gate_proj", "mlp.switch_mlp.up_proj", "mlp.switch_mlp.down_proj" }; +}; + +/// The Gated DeltaNet block under a layer's stem. +pub const linear = struct { + pub const qkv = "linear_attn.in_proj_qkv"; + pub const z = "linear_attn.in_proj_z"; + pub const b = "linear_attn.in_proj_b"; + pub const a = "linear_attn.in_proj_a"; + pub const out = "linear_attn.out_proj"; + pub const a_log = "linear_attn.A_log"; + pub const dt_bias = "linear_attn.dt_bias"; + pub const conv = "linear_attn.conv1d.weight"; + pub const norm = "linear_attn.norm.weight"; + /// The input projections in the order they share one product. + pub const inputs = [_][]const u8{ qkv, z, b, a }; +}; + +/// The sparse attention block under a layer's stem, with its indexer. +pub const sparse = struct { + pub const q = "self_attn.q_proj"; + pub const k = "self_attn.k_proj"; + pub const v = "self_attn.v_proj"; + pub const o = "self_attn.o_proj"; + pub const index = "self_attn.indexer.index_qk_proj"; + pub const q_norm = "self_attn.q_norm.weight"; + pub const k_norm = "self_attn.k_norm.weight"; + pub const iq_norm = "self_attn.indexer.q_layernorm.weight"; + pub const ik_norm = "self_attn.indexer.k_layernorm.weight"; + /// The input projections in the order they share one product. + pub const inputs = [_][]const u8{ q, k, v, index }; +}; + +/// The n-gram (PLE) block under its layer's stem. +pub const ple = struct { + pub const key = "ple.key_proj"; + pub const value = "ple.value_proj"; + pub const norm_key = "ple.norm_key.weight"; + pub const norm_query = "ple.norm_query.weight"; + pub const norm_conv = "ple.norm_conv.weight"; + pub const conv = "ple.conv1d.weight"; + pub const vectors = [_][]const u8{ conv, norm_conv, norm_key, norm_query, "ple.ple_embedding.layer_multipliers", "ple.ple_embedding.ngram_heads_offsets", "ple.ple_embedding.ngram_heads_vocab_sizes" }; + + /// Shard `i` of the tables under `spelling` (`shard_` or `shards.`), without its `.weight`/`.scales`/`.biases`. + pub fn table(buf: []u8, layer_stem: []const u8, spelling: []const u8, i: usize) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}.ple.ple_embedding.ngram_embedding.{s}{d}", .{ layer_stem, spelling, i }); + } +}; + +/// A projection's output rows and input width. +pub const Shape = struct { n: usize, k: usize }; + +/// The shape of the projection named `suffix` (one of the names above), or null for a name this table does not size. +pub fn shape(c: *const Config, suffix: []const u8) !?Shape { + const wide = try c.wide(); + const kw = c.key_heads * c.key_dim; + const vw = c.value_heads * c.value_dim; + const table = [_]struct { []const u8, Shape }{ + .{ hc.down, .{ .n = c.hc_lowrank, .k = wide } }, + .{ hc.up, .{ .n = wide, .k = c.hc_lowrank } }, + .{ hc.inject, .{ .n = c.hc_count, .k = wide } }, + .{ linear.qkv, .{ .n = 2 * kw + vw, .k = c.hidden } }, + .{ linear.z, .{ .n = vw, .k = c.hidden } }, + .{ linear.a, .{ .n = c.value_heads, .k = c.hidden } }, + .{ linear.b, .{ .n = c.value_heads, .k = c.hidden } }, + .{ linear.out, .{ .n = c.hidden, .k = vw } }, + .{ sparse.q, .{ .n = 2 * c.heads * c.head_dim, .k = c.hidden } }, + .{ sparse.k, .{ .n = c.kv_heads * c.head_dim, .k = c.hidden } }, + .{ sparse.v, .{ .n = c.kv_heads * c.head_dim, .k = c.hidden } }, + .{ sparse.o, .{ .n = c.hidden, .k = c.heads * c.head_dim } }, + .{ sparse.index, .{ .n = (c.index_heads + c.index_kv_heads) * c.index_dim, .k = c.hidden } }, + .{ ple.key, .{ .n = wide, .k = c.ple_dim } }, + .{ ple.value, .{ .n = c.hidden, .k = c.ple_dim } }, + .{ embed, .{ .n = c.vocab, .k = c.hidden } }, + .{ lm_head, .{ .n = c.vocab, .k = c.hidden } }, + .{ mtp.fc_embedding, .{ .n = c.hidden, .k = c.hidden } }, + .{ mtp.fc_hidden, .{ .n = c.hidden, .k = c.hidden } }, + }; + for (table) |e| if (std.mem.endsWith(u8, suffix, e[0])) return e[1]; + return null; +} + +/// Gamma (true) or gamma - 1 stored, from the layers' attention hc norm means: under 8 say zero, a mix is refused. +pub fn normsAroundOne(means: []f64) !bool { + if (means.len < 8) return false; + var above: usize = 0; + for (means) |m| { + if (m > 0.5) above += 1; + } + std.mem.sort(f64, means, {}, std.sort.asc(f64)); + const median = means[means.len / 2]; + const share = @as(f64, @floatFromInt(above)) / @as(f64, @floatFromInt(means.len)); + const around_one = share >= 0.9 and 0.75 <= median and median <= 1.5; + const around_zero = share <= 0.1 and -0.5 <= median and median <= 0.25; + if (!around_one and !around_zero) return error.AmbiguousNormStorage; + return around_one; +} + +/// A centred norm's scale from its stored value: 1 + w, w the stored value less one when gamma is stored. +pub fn centred(stored: f32, around_one: bool) f32 { + const w = if (around_one) stored - 1.0 else stored; + return 1.0 + w; +} + +test "every sized projection of the 4-bit checkpoint has the shape its config gives" { + var c = try @import("../config.zig").parse(std.testing.allocator, @embedFile("../fixtures/config.json")); + defer c.deinit(); + // the published checkpoint's headers: rows and inputs of each projection + const want = [_]struct { []const u8, Shape }{ + .{ hc.down, .{ .n = 320, .k = 10240 } }, .{ hc.up, .{ .n = 10240, .k = 320 } }, .{ hc.inject, .{ .n = 4, .k = 10240 } }, + .{ linear.qkv, .{ .n = 10240, .k = 2560 } }, .{ linear.z, .{ .n = 6144, .k = 2560 } }, .{ linear.a, .{ .n = 48, .k = 2560 } }, + .{ linear.out, .{ .n = 2560, .k = 6144 } }, .{ sparse.q, .{ .n = 12288, .k = 2560 } }, .{ sparse.k, .{ .n = 512, .k = 2560 } }, + .{ sparse.o, .{ .n = 2560, .k = 6144 } }, .{ sparse.index, .{ .n = 640, .k = 2560 } }, .{ ple.key, .{ .n = 10240, .k = 2560 } }, + .{ ple.value, .{ .n = 2560, .k = 2560 } }, .{ lm_head, .{ .n = 248320, .k = 2560 } }, .{ mtp.fc_hidden, .{ .n = 2560, .k = 2560 } }, + }; + for (want) |w| try std.testing.expectEqual(w[1], (try shape(&c, w[0])).?); + try std.testing.expect((try shape(&c, moe.gate)) == null); +} + +test "norm storage: gamma near one, gamma - 1 near zero, a mix refused, few layers around zero" { + var one = [_]f64{ 1.0, 0.9, 1.1, 1.0, 1.2, 0.95, 1.0, 1.05 }; + try std.testing.expect(try normsAroundOne(&one)); + var zero = [_]f64{ 0.0, 0.1, -0.1, 0.0, 0.2, 0.05, 0.0, 0.02 }; + try std.testing.expect(!try normsAroundOne(&zero)); + var mixed = [_]f64{ 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 }; + try std.testing.expectError(error.AmbiguousNormStorage, normsAroundOne(&mixed)); + var few = [_]f64{ 1.0, 1.0 }; + try std.testing.expect(!try normsAroundOne(&few)); + try std.testing.expectEqual(@as(f32, 2.25), centred(1.25, false)); + try std.testing.expectEqual(@as(f32, 1.25), centred(1.25, true)); +} diff --git a/zig/tests/flashnext_hip/main.zig b/zig/tests/flashnext_hip/main.zig new file mode 100644 index 00000000000..36d22acaafc --- /dev/null +++ b/zig/tests/flashnext_hip/main.zig @@ -0,0 +1,130 @@ +//! Flash Next model checks on HIP: `tf-flashnext-hip-test generate [--text T] [--chat] [--max N]`. +const std = @import("std"); +const hip = @import("hip"); +const fx = @import("flashnext"); +const tokenizer = @import("tokenizer"); + +/// No per-thread alternate signal stack: its thread-local leaves RCCL's and HIP's threads too little stack to start. +pub const std_options: std.Options = .{ .signal_stack_size = null }; + +const usage = "usage: tf-flashnext-hip-test generate [--policy P] [--text T] [--chat] [--max N] [--capacity N] [--repeat N] [--chunk N] [--hash]\n"; + +const Args = struct { + dir: []const u8 = "", + policy: []const u8 = "", + text: []const u8 = "The capital of France is", + chat: bool = false, + max: usize = 32, + capacity: usize = 8192, + repeat: usize = 1, + chunk: usize = 512, + /// Print a hash of every step's whole logits row, to compare builds and policies bit for bit. + hash: bool = false, +}; + +fn parse(args: []const [:0]const u8) !Args { + var a: Args = .{ .dir = args[0] }; + var i: usize = 1; + while (i < args.len) : (i += 1) { + const name = args[i]; + if (std.mem.eql(u8, name, "--chat") or std.mem.eql(u8, name, "--hash")) { + if (name[2] == 'c') a.chat = true else a.hash = true; + continue; + } + i += 1; + if (i >= args.len) return error.MissingArgument; + const v = args[i]; + if (std.mem.eql(u8, name, "--policy")) a.policy = v else if (std.mem.eql(u8, name, "--text")) a.text = v else if (std.mem.eql(u8, name, "--max")) a.max = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, name, "--capacity")) a.capacity = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, name, "--repeat")) a.repeat = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, name, "--chunk")) a.chunk = try std.fmt.parseInt(usize, v, 10) else return error.UnknownOption; + } + return a; +} + +fn nowNs(io: std.Io) i96 { + return std.Io.Timestamp.now(io, .awake).nanoseconds; +} + +/// The prompt and greedy steps on device 0; prints the text and the timings. +fn generate(gpa: std.mem.Allocator, io: std.Io, a: Args) !void { + var notes: hip.Policy.Notes = .{}; + const policy = try hip.Policy.resolve(a.policy, .current, ¬es); + const t0 = nowNs(io); + const e = try fx.engine.Engine.open(gpa, io, a.dir, .{ .policy = policy, .capacity = a.capacity, .chunk = a.chunk }); + defer e.deinit(); + std.debug.print("loaded in {d:.1} s, {d:.2} GiB on the device\n", .{ @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9, @as(f64, @floatFromInt(hip.usage(false).device)) / (1 << 30) }); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const tk_path = try std.fs.path.join(arena.allocator(), &.{ a.dir, "tokenizer.json" }); + var tok = try tokenizer.loadTokenizer(io, arena.allocator(), tk_path); + const text = if (a.chat) try std.fmt.allocPrint(arena.allocator(), "<|im_start|>user\n{s}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", .{a.text}) else a.text; + const prompt = try tok.encode(arena.allocator(), text); + for (0..a.repeat) |_| { + var c = try e.caches(a.capacity); + defer c.deinit(gpa); + const m = e.model_(); + var at: usize = 0; + var start: usize = 0; + const p0 = nowNs(io); + var out: fx.forward.Out = undefined; + while (at < prompt.len) { + const n = @min(e.o.chunk, prompt.len - at); + out = try e.prompt(&c, prompt[at..][0..n]); + start = at; + at += n; + } + const last = fx.forward.at(out.mixed, (prompt.len - 1 - start) * m.dims.hidden); + var o = e.ops(&e.arena); + var next: [1]u32 = undefined; + var digest = std.hash.Fnv1a_64.init(); + const first = try e.logits(o, last, 1); + if (a.hash) try mix(e, &digest, first); + try e.drawer.draw(o, e.stream, first, &.{.{ .sampling = null, .position = prompt.len }}, &next, false); + const p1 = nowNs(io); + var reply: std.ArrayList(u32) = .empty; + try reply.append(arena.allocator(), next[0]); + for (1..a.max) |_| { + const step = [1]u32{next[0]}; + const w = try e.run(&c, &step, c.len, true); + o = e.ops(&e.arena); + const y = try e.logits(o, w.mixed, 1); + if (a.hash) try mix(e, &digest, y); + try e.drawer.draw(o, e.stream, y, &.{.{ .sampling = null, .position = c.len + 1 }}, &next, false); + try e.keepWindow(&c, &step, 1); + try reply.append(arena.allocator(), next[0]); + } + try e.stream.synchronize(); + const p2 = nowNs(io); + const words = try tok.decode(arena.allocator(), reply.items, false); + const pre = @as(f64, @floatFromInt(p1 - p0)) / 1e9; + const dec = @as(f64, @floatFromInt(p2 - p1)) / 1e9; + std.debug.print("prompt {d} tokens in {d:.3} s ({d:.1} tok/s); {d} tokens in {d:.3} s ({d:.2} tok/s)\n", .{ prompt.len, pre, @as(f64, @floatFromInt(prompt.len)) / pre, a.max - 1, dec, @as(f64, @floatFromInt(a.max - 1)) / dec }); + if (a.hash) std.debug.print("logits hash {x:0>16}\n", .{digest.final()}); + std.debug.print("ids {any}\n---\n{s}{s}\n---\n", .{ reply.items, text, words }); + } +} + +/// One logits row folded into `digest`, read back after the stream's work. +fn mix(e: *fx.engine.Engine, digest: *std.hash.Fnv1a_64, y: hip.ops.Tensor) !void { + const bytes = try e.gpa.alloc(u8, e.cfg.vocab * y.kind.size()); + defer e.gpa.free(bytes); + try e.stream.synchronize(); + try hip.runtime.check(e.driver.api.hipMemcpyDtoH(bytes.ptr, @ptrFromInt(y.ptr), bytes.len)); + digest.update(bytes); +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 3 or !std.mem.eql(u8, args[1], "generate")) { + std.debug.print(usage, .{}); + return 2; + } + const a = parse(args[2..]) catch { + std.debug.print(usage, .{}); + return 2; + }; + generate(init.gpa, init.io, a) catch |err| { + std.debug.print("FAIL {t}\n", .{err}); + if (@errorReturnTrace()) |t| std.debug.dumpStackTrace(t); + return 1; + }; + return 0; +} From 3fa886162741f3a3911777b729101e6d3ebf0973 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:21:06 +0200 Subject: [PATCH 40/52] refactor(core): a MoE layer's stacked experts and router rows in core/quant, for every family that reads MLX experts The Qwen3.5 loader's expert stacking (routed experts with the shared one last, gate and up fused per expert, router rows with the shared gate as the last row) and its per-rank slicing move from the family into core/quant/experts.zig, generic over any table with has, get and width; Qwen3.5 calls it unchanged and Flash Next's HIP loader will too. A test stacks two experts and a shared one and checks the order and a rank's remap. --- .../weights => core/quant}/experts.zig | 167 +++++++++++++----- zig/src/core/quant/quant.zig | 2 + .../families/qwen3_5/weights/checkpoint.zig | 6 +- zig/src/families/qwen3_5/weights/host.zig | 18 +- zig/src/families/qwen3_5/weights/slicing.zig | 12 +- 5 files changed, 136 insertions(+), 69 deletions(-) rename zig/src/{families/qwen3_5/weights => core/quant}/experts.zig (50%) diff --git a/zig/src/families/qwen3_5/weights/experts.zig b/zig/src/core/quant/experts.zig similarity index 50% rename from zig/src/families/qwen3_5/weights/experts.zig rename to zig/src/core/quant/experts.zig index 16c7afa0153..ffc48249c20 100644 --- a/zig/src/families/qwen3_5/weights/experts.zig +++ b/zig/src/core/quant/experts.zig @@ -1,28 +1,42 @@ -//! The Python loader's `_routed`, `_experts` and `_affine_side`: router rows and the stacked affine experts. +//! A MoE layer's router rows and its affine experts stacked with the shared expert last, any table with has/get/width. const std = @import("std"); -const quant = @import("core").quant; -const table = @import("table.zig"); -const convert = quant.convert; -const config = @import("config.zig"); -const host = @import("host.zig"); -const projection = @import("projection.zig"); - -const Tensor = table.Tensor; -const Table = table.Table; -const DType = table.DType; -pub const Error = projection.Error; - -fn refuse(key: []const u8, what: []const u8) error{UnexpectedTensor} { - std.log.err("{s}: {s}", .{ key, what }); - return error.UnexpectedTensor; -} +const types = @import("types.zig"); +const convert = @import("convert.zig"); +const mlx = @import("mlx.zig"); +const slice = @import("slice.zig"); +const quant = @import("quant.zig"); + +const Tensor = types.Tensor; +const DType = types.DType; +const Allocator = std.mem.Allocator; +const refuse = types.refuse; +const join = types.join; + +/// A layer's E + 1 experts, shared last: `fused` is gate then up along N per expert, or up alone when not `gated`. +pub const Experts = struct { + fused: quant.Host, + gated: bool, + down: quant.Host, + /// The expert MLP's inner width (rows of the gate, and of the up). + width: usize, + /// The model width (rows of the down). + dims: usize, + /// E + 1. + count: usize, +}; + +/// The router rows [E + 1, D] with the shared gate last, in bf16 and widened to `rows32`; `remap` is a rank's own ids. +pub const Routed = struct { router: Tensor, rows32: Tensor, experts: Experts, top_k: usize, remap: ?Tensor = null }; + +/// What the router's rows are checked against: the routed experts, the model width, the experts a token takes. +pub const Shape = struct { experts: usize, hidden: usize, top_k: usize }; /// `_router_rows`: one router's rows [R, D] as fp32, a float tensor as stored or an affine group table unpacked. -fn routerRows(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!struct { data: []f32, rows: usize, cols: usize } { +fn routerRows(a: Allocator, t: anytype, key: []const u8) !struct { data: []f32, rows: usize, cols: usize } { var buf: [256]u8 = undefined; var other: [256]u8 = undefined; - const weight = try t.get(projection.join(&buf, &.{ key, ".weight" })); + const weight = try t.get(join(&buf, &.{ key, ".weight" })); if (convert.isFloat(weight.dtype)) { if (weight.rank != 2) return refuse(key, "router weight must be (rows, hidden)"); const wide = try convert.float32(a, weight); @@ -31,20 +45,20 @@ fn routerRows(a: std.mem.Allocator, t: *const Table, key: []const u8) Error!stru return .{ .data = out, .rows = weight.shape[0], .cols = weight.shape[1] }; } const group = (try t.width(key)).group; - const scale = try t.get(projection.join(&buf, &.{ key, ".scales" })); - const bias = try t.get(projection.join(&other, &.{ key, ".biases" })); - const data = try quant.mlx.dequant(a, weight, scale, bias, group); + const scale = try t.get(join(&buf, &.{ key, ".scales" })); + const bias = try t.get(join(&other, &.{ key, ".biases" })); + const data = try mlx.dequant(a, weight, scale, bias, group); return .{ .data = data, .rows = weight.shape[0], .cols = scale.shape[1] * group }; } /// The routed stack and the shared expert's tensor for one suffix, as `_shared_last` checks them. const Pair = struct { mine: Tensor, one: Tensor }; -fn pair(t: *const Table, stack_key: []const u8, shared: []const u8, suffix: []const u8) Error!Pair { +fn pair(t: anytype, stack_key: []const u8, shared: []const u8, suffix: []const u8) !Pair { var b1: [256]u8 = undefined; var b2: [256]u8 = undefined; - var mine = try t.get(projection.join(&b1, &.{ stack_key, suffix })); - var one = try t.get(projection.join(&b2, &.{ shared, suffix })); + var mine = try t.get(join(&b1, &.{ stack_key, suffix })); + var one = try t.get(join(&b2, &.{ shared, suffix })); if (mine.dtype == .u32) mine.dtype = .i32; if (one.dtype == .u32) one.dtype = .i32; if (one.rank == mine.rank and one.shape[0] == 1) { @@ -56,7 +70,7 @@ fn pair(t: *const Table, stack_key: []const u8, shared: []const u8, suffix: []co } /// `fused` words, scales and biases of `srcs` stacked per expert, each expert's slices side by side along N. -fn stack(a: std.mem.Allocator, srcs: []const Pair, dtype: DType) Error!Tensor { +fn stack(a: Allocator, srcs: []const Pair, dtype: DType) !Tensor { const count = srcs[0].mine.shape[0] + 1; const rest = srcs[0].mine.shape[2]; var rows: usize = 0; @@ -89,7 +103,7 @@ fn tableDtype(srcs: []const Pair, other: []const Pair) DType { /// One projection's tensors, checked as `_affine_side` does against (bits, group). const Part = struct { words: Pair, scales: Pair, biases: Pair }; -fn part(t: *const Table, stack_key: []const u8, shared: []const u8, w: config.Width) Error!Part { +fn part(t: anytype, stack_key: []const u8, shared: []const u8, w: mlx.Width) !Part { const p: Part = .{ .words = try pair(t, stack_key, shared, ".weight"), .scales = try pair(t, stack_key, shared, ".scales"), @@ -102,7 +116,7 @@ fn part(t: *const Table, stack_key: []const u8, shared: []const u8, w: config.Wi return p; } -fn side(a: std.mem.Allocator, parts: []const Part, w: config.Width) Error!host.Projection { +fn side(a: Allocator, parts: []const Part, w: mlx.Width) !quant.Host { var words: [2]Pair = undefined; var scales: [2]Pair = undefined; var biases: [2]Pair = undefined; @@ -123,22 +137,22 @@ fn side(a: std.mem.Allocator, parts: []const Part, w: config.Width) Error!host.P } /// `_experts`: a layer's E + 1 affine experts, the shared one last, gate and up fused per expert. -pub fn experts(a: std.mem.Allocator, t: *const Table, prefix: []const u8) Error!host.Experts { +pub fn experts(a: Allocator, t: anytype, prefix: []const u8) !Experts { var b: [4][256]u8 = undefined; - const mine = projection.join(&b[0], &.{ prefix, "switch_mlp." }); - const shared = projection.join(&b[1], &.{ prefix, "shared_expert." }); - if (!t.has(projection.join(&b[2], &.{ mine, "up_proj.weight" }))) { - if (t.has(projection.join(&b[2], &.{ mine, "up_proj.qweight" }))) return error.UnsupportedQuantization; - _ = try t.get(projection.join(&b[2], &.{ mine, "up_proj.weight" })); + const mine = join(&b[0], &.{ prefix, "switch_mlp." }); + const shared = join(&b[1], &.{ prefix, "shared_expert." }); + if (!t.has(join(&b[2], &.{ mine, "up_proj.weight" }))) { + if (t.has(join(&b[2], &.{ mine, "up_proj.qweight" }))) return error.UnsupportedQuantization; + _ = try t.get(join(&b[2], &.{ mine, "up_proj.weight" })); } - const gated = t.has(projection.join(&b[2], &.{ mine, "gate_proj.weight" })); + const gated = t.has(join(&b[2], &.{ mine, "gate_proj.weight" })); var names: [3][2][256]u8 = undefined; const keys = [3][]const u8{ "up_proj", "gate_proj", "down_proj" }; var routed_keys: [3][]const u8 = undefined; var shared_keys: [3][]const u8 = undefined; for (keys, 0..) |k, i| { - routed_keys[i] = projection.join(&names[i][0], &.{ mine, k }); - shared_keys[i] = projection.join(&names[i][1], &.{ shared, k }); + routed_keys[i] = join(&names[i][0], &.{ mine, k }); + shared_keys[i] = join(&names[i][1], &.{ shared, k }); } const up_w = try t.width(routed_keys[0]); const down_w = try t.width(routed_keys[2]); @@ -167,10 +181,10 @@ pub fn experts(a: std.mem.Allocator, t: *const Table, prefix: []const u8) Error! } /// `_routed`: router rows [E + 1, D] in bf16 (the shared expert's gate row last), widened once, and the experts. -pub fn routed(a: std.mem.Allocator, t: *const Table, prefix: []const u8, spec: config.Spec) Error!host.Routed { +pub fn routed(a: Allocator, t: anytype, prefix: []const u8, spec: Shape) !Routed { var b: [2][256]u8 = undefined; - const gate = try routerRows(a, t, projection.join(&b[0], &.{ prefix, "gate" })); - const shared_gate = try routerRows(a, t, projection.join(&b[1], &.{ prefix, "shared_expert_gate" })); + const gate = try routerRows(a, t, join(&b[0], &.{ prefix, "gate" })); + const shared_gate = try routerRows(a, t, join(&b[1], &.{ prefix, "shared_expert_gate" })); const rows = gate.rows + shared_gate.rows; if (gate.cols != shared_gate.cols or rows != spec.experts + 1 or gate.cols != spec.hidden) return refuse(prefix, "router rows do not fit E + 1 by hidden"); const router = try a.alloc(u8, rows * gate.cols * 2); @@ -191,3 +205,76 @@ pub fn routed(a: std.mem.Allocator, t: *const Table, prefix: []const u8, spec: c .top_k = spec.top_k, }; } + +/// A rank's contiguous routed experts, the shared one on rank 0, and the remap to its own ids (-1: another rank's). +pub fn sliceRank(a: Allocator, x: *Routed, r: slice.Rank) slice.Error!void { + const total = x.experts.count - 1; + const part_n = try slice.even(total, r.world, "experts"); + x.experts.fused = try quant.sliceStack(a, x.experts.fused, r, part_n); + x.experts.down = try quant.sliceStack(a, x.experts.down, r, part_n); + x.experts.count = part_n + @intFromBool(r.rank == 0); + const remap = try a.alloc(i32, total + 1); + @memset(remap, -1); + for (0..part_n) |i| remap[r.rank * part_n + i] = @intCast(i); + if (r.rank == 0) remap[total] = @intCast(part_n); + x.remap = .{ .dtype = .i32, .rank = 1, .shape = .{ total + 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(remap) }; +} + +const Fake = struct { + map: std.StringHashMapUnmanaged(Tensor) = .empty, + + pub fn has(f: *const Fake, key: []const u8) bool { + return f.map.contains(key); + } + + pub fn get(f: *const Fake, key: []const u8) !Tensor { + return f.map.get(key) orelse error.MissingTensor; + } + + pub fn width(_: *const Fake, _: []const u8) !mlx.Width { + return .{ .bits = 4, .group = 32 }; + } +}; + +test "two routed experts and the shared one stack in order, and a rank keeps its own with the remap" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f: Fake = .{}; + // expert e's word w of row n is 100 e + 10 n + w; the shared expert's are 900 + 10 n + w + for ([_][]const u8{ "gate_proj", "up_proj", "down_proj" }) |name| { + const words = try a.alloc(u32, 2 * 2 * 4); + for (words, 0..) |*x, i| x.* = @intCast(100 * (i / 8) + 10 * ((i / 4) % 2) + i % 4); + const one = try a.alloc(u32, 2 * 4); + for (one, 0..) |*x, i| x.* = @intCast(900 + 10 * (i / 4) + i % 4); + const tables = try a.alloc(u16, 2 * 2); + @memset(tables, 0x3f80); + const shared_tables = try a.alloc(u16, 2); + @memset(shared_tables, 0x3f80); + for ([_][]const u8{ "weight", "scales", "biases" }) |suffix| { + const stacked = std.mem.eql(u8, suffix, "weight"); + try f.map.put(a, try std.fmt.allocPrint(a, "mlp.switch_mlp.{s}.{s}", .{ name, suffix }), if (stacked) + .{ .dtype = .u32, .rank = 3, .shape = .{ 2, 2, 4, 1, 1 }, .bytes = std.mem.sliceAsBytes(words) } + else + .{ .dtype = .bf16, .rank = 3, .shape = .{ 2, 2, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(tables) }); + try f.map.put(a, try std.fmt.allocPrint(a, "mlp.shared_expert.{s}.{s}", .{ name, suffix }), if (stacked) + .{ .dtype = .u32, .rank = 2, .shape = .{ 2, 4, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(one) } + else + .{ .dtype = .bf16, .rank = 2, .shape = .{ 2, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(shared_tables) }); + } + } + const ex = try experts(a, &f, "mlp."); + try std.testing.expect(ex.gated); + try std.testing.expectEqual(@as(usize, 3), ex.count); + var fused: [48]u32 = undefined; + @memcpy(std.mem.sliceAsBytes(&fused), ex.fused.mlx.words.bytes); + // expert 1: its gate rows, then its up rows; the shared expert last + try std.testing.expectEqualSlices(u32, &.{ 100, 101, 102, 103, 110, 111, 112, 113, 100, 101 }, fused[16..26]); + try std.testing.expectEqual(@as(u32, 900), fused[32]); + var r: Routed = .{ .router = undefined, .rows32 = undefined, .experts = ex, .top_k = 1 }; + try sliceRank(a, &r, .{ .rank = 1, .world = 2 }); + try std.testing.expectEqual(@as(usize, 1), r.experts.count); + var remap: [3]i32 = undefined; + @memcpy(std.mem.sliceAsBytes(&remap), r.remap.?.bytes); + try std.testing.expectEqualSlices(i32, &.{ -1, 0, -1 }, &remap); +} diff --git a/zig/src/core/quant/quant.zig b/zig/src/core/quant/quant.zig index 944bca7a3d2..b3d8d72211a 100644 --- a/zig/src/core/quant/quant.zig +++ b/zig/src/core/quant/quant.zig @@ -7,6 +7,7 @@ pub const slice = @import("slice.zig"); pub const convert = @import("convert.zig"); pub const mlx = @import("mlx.zig"); pub const dense = @import("dense.zig"); +pub const experts = @import("experts.zig"); /// FP8 and NVFP4 values and fp64 references; host only (no Format: their kernels' layouts are each backend's). pub const fp8 = @import("fp8.zig"); pub const nvfp4 = @import("nvfp4.zig"); @@ -200,6 +201,7 @@ test { _ = convert; _ = mlx; _ = dense; + _ = experts; _ = fp8; _ = nvfp4; } diff --git a/zig/src/families/qwen3_5/weights/checkpoint.zig b/zig/src/families/qwen3_5/weights/checkpoint.zig index 61c06a719da..b6b16ca165c 100644 --- a/zig/src/families/qwen3_5/weights/checkpoint.zig +++ b/zig/src/families/qwen3_5/weights/checkpoint.zig @@ -5,7 +5,7 @@ const config = @import("config.zig"); const table = @import("table.zig"); const host = @import("host.zig"); const projection = @import("projection.zig"); -const experts = @import("experts.zig"); +const experts = @import("core").quant.experts; const Tensor = table.Tensor; const Table = table.Table; @@ -162,7 +162,7 @@ fn subConv(a: std.mem.Allocator, t: *const Table, base: []const u8) !Tensor { /// The routed MLP when the config has experts, else gate, up and down. fn readMlp(a: std.mem.Allocator, t: *const Table, mlp: []const u8, s: config.Spec) !host.Mlp { - if (s.experts != 0) return .{ .routed = try experts.routed(a, t, mlp, s) }; + if (s.experts != 0) return .{ .routed = try experts.routed(a, t, mlp, .{ .experts = s.experts, .hidden = s.hidden, .top_k = s.top_k }) }; return .{ .dense = .{ .gate = try sub(a, t, mlp, "gate_proj"), .up = try sub(a, t, mlp, "up_proj"), @@ -217,7 +217,7 @@ fn readMtp(a: std.mem.Allocator, t: *const Table, s: config.Spec) !host.Mtp { .head = head, .input_norm = try projection.float(a, t, layer ++ "input_layernorm.weight"), .post_norm = try projection.float(a, t, layer ++ "post_attention_layernorm.weight"), - .mlp = if (routed) .{ .routed = try experts.routed(a, t, mlp, s) } else .{ .dense = .{ + .mlp = if (routed) .{ .routed = try experts.routed(a, t, mlp, .{ .experts = s.experts, .hidden = s.hidden, .top_k = s.top_k }) } else .{ .dense = .{ .gate = try projection.projection(a, t, mlp ++ "gate_proj"), .up = try projection.projection(a, t, mlp ++ "up_proj"), .down = try projection.projection(a, t, mlp ++ "down_proj"), diff --git a/zig/src/families/qwen3_5/weights/host.zig b/zig/src/families/qwen3_5/weights/host.zig index b0dc214f166..f2d2f8dee96 100644 --- a/zig/src/families/qwen3_5/weights/host.zig +++ b/zig/src/families/qwen3_5/weights/host.zig @@ -9,21 +9,9 @@ pub const Tensor = table.Tensor; /// A projection as its format read it from the checkpoint. pub const Projection = quant.Host; -/// A layer's E + 1 experts, shared last: `fused` is gate then up along N per expert, or up alone when not `gated`. -pub const Experts = struct { - fused: Projection, - gated: bool, - down: Projection, - /// The expert MLP's inner width (rows of the gate, and of the up). - width: usize, - /// The model width (rows of the down). - dims: usize, - /// E + 1. - count: usize, -}; - -/// The router rows [E + 1, D] with the shared gate last, in bf16 and widened to `rows32`; `remap` is a rank's own ids. -pub const Routed = struct { router: Tensor, rows32: Tensor, experts: Experts, top_k: usize, remap: ?Tensor = null }; +/// A layer's E + 1 experts, shared last, and its router rows (core/quant/experts.zig). +pub const Experts = quant.experts.Experts; +pub const Routed = quant.experts.Routed; pub const DenseMlp = struct { gate: Projection, up: Projection, down: Projection }; diff --git a/zig/src/families/qwen3_5/weights/slicing.zig b/zig/src/families/qwen3_5/weights/slicing.zig index 9c458f67abd..3232b24e171 100644 --- a/zig/src/families/qwen3_5/weights/slicing.zig +++ b/zig/src/families/qwen3_5/weights/slicing.zig @@ -96,18 +96,8 @@ fn mlp(a: Allocator, m: *host.Mlp, r: Rank) Error!void { } } -/// A rank's contiguous routed experts, the shared one on rank 0, and the remap to its own ids (-1: another rank's). fn routed(a: Allocator, x: *host.Routed, r: Rank) Error!void { - const total = x.experts.count - 1; - const part = try even(total, r.world, "experts"); - x.experts.fused = try quant.sliceStack(a, x.experts.fused, r, part); - x.experts.down = try quant.sliceStack(a, x.experts.down, r, part); - x.experts.count = part + @intFromBool(r.rank == 0); - const remap = try a.alloc(i32, total + 1); - @memset(remap, -1); - for (0..part) |i| remap[r.rank * part + i] = @intCast(i); - if (r.rank == 0) remap[total] = @intCast(part); - x.remap = .{ .dtype = .i32, .rank = 1, .shape = .{ total + 1, 1, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(remap) }; + return quant.experts.sliceRank(a, x, r); } /// The output head's rows for rank `r`: its share of the vocabulary. From 07ff3aa678facc7d80f5c3d83cc31011368b4c25 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 04:13:26 +0200 Subject: [PATCH 41/52] feat(hip): a MoE plan sized by the rows' own pairs, for a family whose launches no graph replays hip.moe.run plans a power-of-two bucket of rows so Qwen3.5's captured rounds replay at any row count; a routed launch then walks every item the bucket could need (198 at one decode row of an 11-pair MoE). A Routed view with exact set plans the rows' own pairs instead (12 items for one row). Qwen3.5 keeps its buckets; the plan's items and their order are otherwise the same. --- zig/src/hip/moe.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zig/src/hip/moe.zig b/zig/src/hip/moe.zig index 628ffc14776..51c671dbdca 100644 --- a/zig/src/hip/moe.zig +++ b/zig/src/hip/moe.zig @@ -27,6 +27,8 @@ pub const Routed = struct { rows: usize, /// A rank's expert ids (int32, E + 1): each id's place among its own, -1 for another rank's; zero on one rank. remap: u64 = 0, + /// Plan the rows' own pairs, not a power-of-two bucket's (no graph replays the launches at other row counts). + exact: bool = false, /// Routed experts, the shared one not counted. pub fn count(r: Routed) usize { @@ -61,7 +63,7 @@ pub fn run(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, prefill: bool) _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tile comes from tile_for) const ex = r.experts; const slots = r.top_k + 1; - const size = bucket(rows); + const size = if (r.exact) rows else bucket(rows); const pairs = rows * slots; const cap = capacity(size * slots, r.rows); const logits = try o.arena.of(f32, rows * r.rows); @@ -101,7 +103,7 @@ pub const Parts = struct { y: u64, wts: u64, slots: usize }; pub fn parts(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize) ops.Error!Parts { const slots = r.top_k + 1; - const size = bucket(rows); + const size = if (r.exact) rows else bucket(rows); const cap = capacity(size * slots, r.rows); const logits = try o.arena.of(f32, rows * r.rows); const pick = try o.arena.of(i32, size * slots); From c28aad2d7dc4fef7c60fb389f2454f2ba0153a4b Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 03:27:58 +0200 Subject: [PATCH 42/52] feat(hip): the merged MoE pick over 512 threads, one expert a thread at 512 experts tf_select_decode ranks each expert against every other with one expert a thread; at 256 threads a block a 512-expert router (Flash Next's) took two experts a thread, 27 us a decode step. The block is 512 threads now; the picks and weights are the same. The chain test's merged pick passes on gfx1030. --- zig/kernels/hip/decode/decode.hip | 2 +- zig/src/hip/launches/moe.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/kernels/hip/decode/decode.hip b/zig/kernels/hip/decode/decode.hip index 4f8328fd445..12d93325e11 100644 --- a/zig/kernels/hip/decode/decode.hip +++ b/zig/kernels/hip/decode/decode.hip @@ -327,7 +327,7 @@ __device__ void } } -constexpr int kSelectThreads = 256; +constexpr int kSelectThreads = 512; constexpr int kSelectMax = 1024; __device__ __forceinline__ float round_bf16_f(float v) { return round_kind(v, 2); } diff --git a/zig/src/hip/launches/moe.zig b/zig/src/hip/launches/moe.zig index 86411c0a383..2cccb06e86d 100644 --- a/zig/src/hip/launches/moe.zig +++ b/zig/src/hip/launches/moe.zig @@ -81,7 +81,7 @@ pub fn tf_moe_select(l: *const Launcher, logits: CF, pick: I, wts: F, items: I, 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); + if (l.fuse) return l.go(l.dec.select, dim(r, 1, 1), dim(512, 1, 1), 0, s, &a); try l.go(l.moe_select, dim(r, 1, 1), dim(32, 1, 1), 0, s, &a); } From 0e4b3740b201a7282bf0790a86fa19746d9cccbe Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:58:20 +0200 Subject: [PATCH 43/52] feat(hip): the gated norm's gate is SiLU or sigmoid Flash Next's DeltaNet output norm gates with sigmoid(z) (output_gate_type); Qwen3.5's with silu(z). Both the merged decode norm (tf_gnorm_out) and the unmerged one (tf_gnorm_silu) take the gate; Qwen3.5 passes .silu and its bytes are unchanged. The chain test runs both gates, the merged against the unmerged launch, and the sigmoid one against a host reference; it fails when either kernel ignores the gate. --- zig/kernels/hip/decode/decode.hip | 12 +++++---- zig/kernels/hip/ops/linear.hpp | 6 +++-- .../qwen3_5/backend/hip/forward/forward.zig | 4 +-- zig/src/hip/kernel_tests/chain.zig | 26 ++++++++++++++----- zig/src/hip/launches/norms.zig | 5 ++-- zig/src/hip/launches/recurrence.zig | 3 ++- zig/src/hip/ops/norms.zig | 13 ++++++---- 7 files changed, 46 insertions(+), 23 deletions(-) diff --git a/zig/kernels/hip/decode/decode.hip b/zig/kernels/hip/decode/decode.hip index 12d93325e11..f29148a015c 100644 --- a/zig/kernels/hip/decode/decode.hip +++ b/zig/kernels/hip/decode/decode.hip @@ -296,10 +296,10 @@ __device__ void } } -// The gated norm out = rms(y) * weight * round(silu(z)) in the kind, a wave a (row, head), no fp32 round trip between. +// The gated norm out = rms(y) * weight * round(silu(z) or sigmoid(z)) in the kind, a wave a (row, head). __device__ void gnorm_out_body(const float* y, const float* weight, const void* z, void* out, int kind, int rows, int width, - float eps) { + float eps, int sigmoid_gate) { constexpr int kMost = 1024 / 32; const int lane = threadIdx.x & 31; const int row = blockIdx.x * 8 + (threadIdx.x >> 5); @@ -323,7 +323,8 @@ __device__ void 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)); + const float gate = sigmoid_gate ? 1.f / (1.f + expf(-zv)) : zv / (1.f + expf(-zv)); + store_kind(out, kind, at + i, value * round_kind(gate, kind)); } } @@ -412,8 +413,9 @@ extern "C" __global__ void __launch_bounds__(256) } 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); + tf_gnorm_out(const float* y, const float* weight, const void* z, void* out, int kind, int rows, int width, float eps, + int sigmoid_gate) { + gnorm_out_body(y, weight, z, out, kind, rows, width, eps, sigmoid_gate); } extern "C" __global__ void __launch_bounds__(kSelectThreads) diff --git a/zig/kernels/hip/ops/linear.hpp b/zig/kernels/hip/ops/linear.hpp index fd2ce6950a9..dde30998ae2 100644 --- a/zig/kernels/hip/ops/linear.hpp +++ b/zig/kernels/hip/ops/linear.hpp @@ -54,10 +54,12 @@ extern "C" __global__ void tf_gdn_gate_prefill(const void* a, const void* b, int } // 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) { +extern "C" __global__ void tf_gnorm_silu(const float* y, const void* z, void* out, int kind, long long n, + int sigmoid_gate) { long long i = gid(); if (i >= n) return; - float s = rounded(silu(load(z, kind, i)), kind); + const float zv = load(z, kind, i); + float s = rounded(sigmoid_gate ? sigmoid(zv) : silu(zv), kind); store(out, kind, i, y[i] * s); } diff --git a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig index f2d9c973e56..9926861d782 100644 --- a/zig/src/families/qwen3_5/backend/hip/forward/forward.zig +++ b/zig/src/families/qwen3_5/backend/hip/forward/forward.zig @@ -163,11 +163,11 @@ pub fn gatedOut(o: Ops, m: *const view.Model, l: view.Linear, y: u64, z: Tensor, const n = rows * s.valueWidth(); const out = try take(o, m.act, n); if (o.fused() and s.value_dim <= 1024 and z.kind == m.act) { - try o.gnormOut(y, l.gnorm, z, out, rows * s.value_heads, s.value_dim, @floatCast(s.eps)); + try o.gnormOut(y, l.gnorm, z, out, rows * s.value_heads, s.value_dim, @floatCast(s.eps), .silu); } else { const yn = try o.arena.of(f32, n); try o.rms(.{ .ptr = y, .kind = .f32 }, l.gnorm, .{ .ptr = yn, .kind = .f32 }, rows * s.value_heads, s.value_dim, @floatCast(s.eps)); - try o.gnormSilu(yn, z, out, n); + try o.gnormSilu(yn, z, out, n, .silu); } return o.project(out, l.out, rows, l.out.partial); } diff --git a/zig/src/hip/kernel_tests/chain.zig b/zig/src/hip/kernel_tests/chain.zig index c2edd65a083..0d9bf21d955 100644 --- a/zig/src/hip/kernel_tests/chain.zig +++ b/zig/src/hip/kernel_tests/chain.zig @@ -168,8 +168,8 @@ fn conv(t: *Rig, rng: *rig.Rng, rows: usize) !void { 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 { +/// The linear attention's gated norm: rms then gnorm_silu against one launch; the sigmoid gate against the host's too. +fn gnorm(t: *Rig, rng: *rig.Rng, rows: usize, sigmoid: c_int) !void { const n = rows * 32 * 128; const eps: f32 = 1e-6; const hy = try gpa.alloc(f32, n); @@ -193,10 +193,24 @@ fn gnorm(t: *Rig, rng: *rig.Rng, rows: usize) !void { 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.on.tf_gnorm_silu(@ptrFromInt(at(yn)), ptr(at(z)), ptr(at(outs[0])), t.kind(), @intCast(n), sigmoid, 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, sigmoid, s); try t.stream.synchronize(); try same(outs[0], outs[1]); + if (sigmoid == 0) return; + const got = try rig.download(u16, outs[1]); + defer gpa.free(got); + const fx = @import("flashnext.zig"); + for (0..rows * 32) |r| { + var sum: f32 = 0; + for (hy[r * 128 ..][0..128]) |v| sum += v * v; + const inv = 1.0 / @sqrt(sum / 128.0 + eps); + for (0..128) |i| { + const zv = fx.value(t, hz[r * 128 + i]); + const want = fx.rnd(t, hy[r * 128 + i] * inv * hn[i] * fx.rnd(t, fx.sigmoid(zv))); + try rig.expect(fx.close(t, fx.value(t, got[r * 128 + i]), want, 1), "sigmoid-gated norm row {d} dim {d}", .{ r, i }); + } + } } test "the merged MoE pick writes the scanning kernel's picks, weights, items and members" { @@ -214,9 +228,9 @@ test "the merged conv split writes the chain's state, snapshots, q, k, v, gate a for ([_]usize{ 1, 2, 4, 16 }) |rows| try conv(t, &rng, rows); } -test "the merged gated norm writes rms then gnorm_silu's bytes" { +test "the merged gated norm writes rms then gnorm_silu's bytes, with either gate" { 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); + for ([_]c_int{ 0, 1 }) |sigmoid| for ([_]usize{ 1, 4, 16, 128 }) |rows| try gnorm(t, &rng, rows, sigmoid); } diff --git a/zig/src/hip/launches/norms.zig b/zig/src/hip/launches/norms.zig index ca9a007c56c..cfeec4097de 100644 --- a/zig/src/hip/launches/norms.zig +++ b/zig/src/hip/launches/norms.zig @@ -51,8 +51,8 @@ pub fn tf_rms2(l: *const Launcher, x0: CF, w0: CF, y0: F, x1: CF, w1: CF, y1: F, 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 { +/// out = rms(y) * weight * round(silu(z), or sigmoid(z) when `sigmoid`) rounded to the kind, rows at most 1024 wide. +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, sigmoid: c_int, s: S) Error!void { if (width > 1024) return invalid("gnorm out"); var a: Args = .{}; try a.add(ad(y)); @@ -63,6 +63,7 @@ pub fn tf_gnorm_out(l: *const Launcher, y: CF, weight: CF, z: C, out: P, kind: c try a.add(rows); try a.add(width); try a.add(eps); + try a.add(sigmoid); try l.go(l.dec.gnorm_out, dim(cdiv(rows, 8), 1, 1), dim(256, 1, 1), 0, s, &a); } diff --git a/zig/src/hip/launches/recurrence.zig b/zig/src/hip/launches/recurrence.zig index 86e5369a16d..14829c7a65c 100644 --- a/zig/src/hip/launches/recurrence.zig +++ b/zig/src/hip/launches/recurrence.zig @@ -156,12 +156,13 @@ pub fn tf_gdn_gate_prefill(l: *const Launcher, av: C, bv: C, kind: c_int, a_log: 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 { +pub fn tf_gnorm_silu(l: *const Launcher, y: CF, z: C, out: P, kind: c_int, n: c_longlong, sigmoid: c_int, 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 a.add(sigmoid); try l.flat(l.op.gnorm_silu, n, s, &a); } diff --git a/zig/src/hip/ops/norms.zig b/zig/src/hip/ops/norms.zig index 5bfb46d2f02..9e0f8b4145d 100644 --- a/zig/src/hip/ops/norms.zig +++ b/zig/src/hip/ops/norms.zig @@ -20,11 +20,14 @@ pub fn rms2(o: Ops, x0: u64, w0: u64, y0: u64, x1: u64, w1: u64, y1: u64, rows: 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 { +/// The gated norm's gate: SiLU (Qwen3.5) or sigmoid (Flash Next's `output_gate_type`). +pub const Gate = enum(c_int) { silu = 0, sigmoid = 1 }; + +/// The linear attention's gated norm: out = rms(y) * weight * round(gate(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, gate: Gate) 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); + try zig.tf_gnorm_out(f(y), f(weight), p(z.ptr), p(out.ptr), @backingInt(z.kind), int(rows), int(width), eps, @backingInt(gate), o.stream); } /// x = round(x + y) and normed = rms(x) * weight (fp32) in one launch: a residual and the norm after it. @@ -34,6 +37,6 @@ pub fn addRms(o: Ops, x: Tensor, y: Tensor, weight: u64, normed: Tensor, rows: u 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); +pub fn gnormSilu(o: Ops, y: u64, z: Tensor, out: Tensor, n: usize, gate: Gate) Error!void { + try o.l.tf_gnorm_silu(f(y), p(z.ptr), p(out.ptr), @backingInt(out.kind), @intCast(n), @backingInt(gate), o.stream); } From 8d2c61182bdcf6d56bb664f4f5e25a3a775c52cd Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:17:36 +0200 Subject: [PATCH 44/52] feat(flashnext): the HIP admission's refusal names the card's grant and the scratch it keeps --- zig/src/families/flashnext/hip/native.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/flashnext/hip/native.zig b/zig/src/families/flashnext/hip/native.zig index 1718e0a5c96..fd778e12882 100644 --- a/zig/src/families/flashnext/hip/native.zig +++ b/zig/src/families/flashnext/hip/native.zig @@ -83,7 +83,7 @@ fn check(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Devi const text = readIndex(a, io, dir) catch |err| return refuse(a, problem, "cannot read {s}/model.safetensors.index.json ({s})", .{ dir, @errorName(err) }); const bytes = cardRoom(gpa, io, dev) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)}); const v = admit(a, gpa, &c, text, o.world, o.rank, o.window, bytes, problem) catch |err| return err; - if (!v.fits) return refuse(a, problem, "Flash Next {d}-bit on {d} rank(s) holds {d:.2} GiB of weights a rank ({d:.1} GiB of n-gram tables in host memory); {d:.2} GiB is left for a {d}-token window, which allows {d} tokens: lower --context, add ranks (--tp), or use a lower-bit checkpoint", .{ v.spec.bits, o.world, gibs(v.weights), gibs(v.host), gibs(bytes -| v.weights), o.window, v.most }); + if (!v.fits) return refuse(a, problem, "Flash Next {d}-bit on {d} rank(s) holds {d:.2} GiB of weights a rank ({d:.1} GiB of n-gram tables in host memory) and {d:.1} GiB of scratch, of the {d:.2} GiB this card grants: a {d}-token window does not fit (at most {d}); lower --context, add ranks (--tp), or use a lower-bit checkpoint", .{ v.spec.bits, o.world, gibs(v.weights), gibs(v.host), gibs(scratch_bytes), gibs(bytes), o.window, v.most }); return refuse(a, problem, "Flash Next {d}-bit fits rank {d} of {d} ({d:.2} GiB of weights, windows up to {d} tokens), but the HIP forward is not in this build yet", .{ v.spec.bits, o.rank, o.world, gibs(v.weights), v.most }); } From ca575f79f33cbc2d0018a2538503e1f809dbde80 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:52:44 +0200 Subject: [PATCH 45/52] feat(flashnext): serve on HIP: the lane backend, MTP drafts, a round's windows in one forward, 64-row prompt reuse --- zig/src/families/flashnext/hip.zig | 4 + zig/src/families/flashnext/hip/lanes.zig | 429 ++++++++++++++++++++ zig/src/families/flashnext/hip/native.zig | 70 +++- zig/src/families/flashnext/hip/snapshot.zig | 100 +++++ zig/tests/flashnext_hip/bench.py | 57 +++ zig/tests/flashnext_hip/rewind.py | 58 +++ 6 files changed, 712 insertions(+), 6 deletions(-) create mode 100644 zig/src/families/flashnext/hip/lanes.zig create mode 100644 zig/src/families/flashnext/hip/snapshot.zig create mode 100644 zig/tests/flashnext_hip/bench.py create mode 100644 zig/tests/flashnext_hip/rewind.py diff --git a/zig/src/families/flashnext/hip.zig b/zig/src/families/flashnext/hip.zig index a6a31abac2e..9bbdb45045b 100644 --- a/zig/src/families/flashnext/hip.zig +++ b/zig/src/families/flashnext/hip.zig @@ -13,6 +13,8 @@ pub const forward = @import("hip/forward.zig"); pub const mixers = @import("hip/mixers.zig"); pub const engine = @import("hip/engine.zig"); pub const head = @import("hip/head.zig"); +pub const lanes = @import("hip/lanes.zig"); +pub const snapshot = @import("hip/snapshot.zig"); /// The registry entry of the native server. pub const native = @import("hip/native.zig"); @@ -28,6 +30,8 @@ test { @import("std").testing.refAllDecls(forward); @import("std").testing.refAllDecls(mixers); @import("std").testing.refAllDecls(tables.Tables); + @import("std").testing.refAllDecls(lanes.Fx); @import("std").testing.refAllDecls(head); + @import("std").testing.refAllDecls(snapshot); _ = native; } diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig new file mode 100644 index 00000000000..beb7e3ec908 --- /dev/null +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -0,0 +1,429 @@ +//! The lane core's HIP backend for Flash Next: each stream its own caches, each window verified and kept exactly. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const serve = @import("hip_serve"); +const Engine = @import("engine.zig").Engine; +const cache = @import("cache.zig"); +const forward = @import("forward.zig"); +const head_mod = @import("head.zig"); +const load = @import("load.zig"); +const snapshot = @import("snapshot.zig"); +const pc = @import("engine_api").prompt_cache; + +const be = lanes.backend; +const draw = serve.draw; + +/// Drawn tokens a handle names, newest last. +const ring = 1024; +/// Drafts the head holds for a stream at most. +pub const max_depth = cache.max_window - 1; + +pub const Fill = struct { at: usize, stops: [16]u32 = undefined, count: usize = 0, next: usize = 0, from: usize = 0, kept0: u64 = 0 }; + +pub const Lane = struct { + caches: cache.Caches, + /// The head's caches (none on a rank that does not draft). + head: ?cache.Caches, + /// The residual streams of the last forward's rows: the head's input. + streams: hip.DeviceBuffer, + held: [max_depth]u32 = undefined, + held_n: usize = 0, + /// The prompt pass: the row it reached and the cuts where the prompt cache keeps a state (null once it is in). + fill: ?Fill = null, + /// The last verify's tokens until its keep. + pending: ?struct { tokens: [cache.max_window]u32, rows: usize } = null, + first_row: ?[]u16 = null, + id: u32 = 0, +}; + +/// The engine this thread's HIP calls go to. +threadlocal var bound: ?*Engine = null; + +pub const Fx = struct { + gpa: std.mem.Allocator, + e: *Engine, + streams: usize, + lanes: std.AutoHashMapUnmanaged(*const lanes.Stream, *Lane) = .empty, + drawn: [ring]u32 = undefined, + next: u64 = 0, + next_id: u32 = 0, + /// A one a stream for every row the head takes at once (a prompt chunk), and the draft vocabulary's token ids. + ones: hip.DeviceBuffer, + draft_ids: []u32, + drafts: u32, + /// The kept prompt states (null: no reuse). + store: ?pc.Store = null, + + pub fn init(gpa: std.mem.Allocator, e: *Engine, streams: usize) !*Fx { + const f = try gpa.create(Fx); + errdefer gpa.destroy(f); + const n = @max(e.o.chunk, cache.max_window) * e.cfg.hc_count; + const one: u16 = if (e.act == .f16) 0x3c00 else 0x3f80; + const host = try gpa.alloc(u16, n); + defer gpa.free(host); + @memset(host, one); + f.* = .{ .gpa = gpa, .e = e, .streams = streams, .ones = try hip.DeviceBuffer.fromHost(&e.driver, std.mem.sliceAsBytes(host)), .draft_ids = &.{}, .drafts = @min(max_depth, e.o.policy.mtp.drafts) }; + errdefer f.ones.free(); + if (e.weights.model.mtp != null) f.draft_ids = try load.draftIds(gpa); + return f; + } + + pub fn deinit(f: *Fx) void { + if (f.store) |*st| st.deinit(); + f.e.stream.synchronize() catch {}; + var it = f.lanes.valueIterator(); + while (it.next()) |l| f.free(l.*); + f.lanes.deinit(f.gpa); + f.ones.free(); + f.gpa.free(f.draft_ids); + f.gpa.destroy(f); + } + + /// Keep prompt states in `budget` host bytes on the prompt kernels' 64-row grid, each a token past its rows. + pub fn keepPrompts(f: *Fx, budget: u64) void { + if (budget == 0) return; + f.store = pc.Store.init(f.gpa, .{ .ptr = f, .vtable = &.{ .bytes = snapBytes, .save = snapSave, .restore = snapRestore, .drop = snapDrop } }, .{ .lookahead = 1, .planned = true, .grid = 64 }, budget); + } + + fn snapBytes(ptr: *anyopaque, at: u32) u64 { + const f: *Fx = @ptrCast(@alignCast(ptr)); + var buf: [64]bool = undefined; + const kinds = f.e.kinds(&buf) catch return std.math.maxInt(u64); + const main = cache.Layout.of(f.e.weights.model.dims, kinds, 64, f.e.act).stateBytes(at); + const head = if (f.e.weights.model.mtp) |h| cache.Layout.of(h.dims, &.{false}, 64, f.e.act).stateBytes(at) else 0; + return main + head; + } + + fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f = of(ptr); + const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const saved = try snapshot.save(f.gpa, &f.e.driver, f.e.stream, &lane.caches, if (lane.head) |*h| h else null, at, f.e.cfg.index_ratio); + return saved; + } + + fn snapRestore(ptr: *anyopaque, owner: ?*anyopaque, saved: pc.Saved) anyerror!void { + const f = of(ptr); + const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const s: *snapshot.Saved = @ptrCast(@alignCast(saved)); + try snapshot.restore(f.gpa, &f.e.driver, f.e.stream, s, &lane.caches, if (lane.head) |*h| h else null, f.e.cfg.index_ratio); + } + + fn snapDrop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *Fx = @ptrCast(@alignCast(ptr)); + const s: *snapshot.Saved = @ptrCast(@alignCast(saved)); + snapshot.drop(f.gpa, s); + } + + pub fn backend(f: *Fx) be.Backend { + return .{ .ptr = f, .vtable = &.{ + .prefill = prefillFn, + .prefill_step = prefillStepFn, + .first = firstFn, + .first_masked = firstMaskedFn, + .held = heldTokensFn, + .queue = queueFn, + .read = readFn, + .verify = verifyFn, + .keep = keepFn, + .draft = draftFn, + .tree = heldFn, + .release = releaseFn, + } }; + } + + pub fn facts(f: *const Fx) lanes.Model { + const drafting = f.e.weights.model.mtp != null and f.drafts > 0; + return .{ + .exact_width = cache.max_window, + .gpu_tokens = false, + .mtp = drafting, + .speculate = drafting, + .speculate_early = false, + .drafts = f.drafts, + .hidden_rows = true, + .batch_rows = @intCast(cache.max_window * f.streams), + .max_streams = @intCast(f.streams), + .draft_streams = false, + }; + } + + fn free(f: *Fx, l: *Lane) void { + f.e.stream.synchronize() catch {}; + l.caches.deinit(f.gpa); + if (l.head) |*h| h.deinit(f.gpa); + l.streams.free(); + if (l.first_row) |row| f.gpa.free(row); + f.gpa.destroy(l); + } + + fn of(ptr: *anyopaque) *Fx { + const f: *Fx = @ptrCast(@alignCast(ptr)); + if (bound != f.e) { + f.e.ctx.makeCurrent() catch |err| std.log.err("hipSetDevice on the lane thread: {s}", .{@errorName(err)}); + bound = f.e; + } + return f; + } + + fn take(f: *Fx, token: u32) u64 { + const at = f.next; + f.drawn[at % ring] = token; + f.next += 1; + return at; + } + + fn sampling(s: *const lanes.Stream) ?lanes.Sampling { + return s.sampling; + } + + /// The pending window's first `rows` rows kept. + fn mark(f: *Fx, lane: *Lane, rows: usize) !void { + const p = lane.pending orelse return; + try f.e.keepWindow(&lane.caches, p.tokens[0..p.rows], rows); + lane.pending = null; + } + + /// Whether a stream other than `mine` is past its prompt: a prompt's chunks then hold its rounds back. + fn decoding(f: *const Fx, mine: *const Lane) bool { + var it = f.lanes.valueIterator(); + while (it.next()) |l| if (l.* != mine and l.*.fill == null) return true; + return false; + } + + fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + while (!try prefillStepFn(ptr, s)) {} + } + + fn begin(f: *Fx, s: *lanes.Stream) !*Lane { + const prompt = s.prompt(); + const total = prompt.len + s.max_new + cache.max_window + 1; + if (prompt.len == 0 or total > f.e.o.capacity) return error.PromptTooLong; + const gop = try f.lanes.getOrPut(f.gpa, s); + if (gop.found_existing) f.free(gop.value_ptr.*); + errdefer f.lanes.removeByPtr(gop.key_ptr); + const e = f.e; + const m = &e.weights.model; + var caches = try e.caches(total); + errdefer caches.deinit(f.gpa); + var head: ?cache.Caches = if (m.mtp) |*h| try head_mod.caches(f.gpa, &e.driver, h, total, e.act, e.eos) else null; + errdefer if (head) |*h| h.deinit(f.gpa); + var streams = try hip.DeviceBuffer.alloc(&e.driver, cache.max_window * m.dims.wide() * m.act.size()); + errdefer streams.free(); + const lane = try f.gpa.create(Lane); + lane.* = .{ .caches = caches, .head = head, .streams = streams, .fill = .{ .at = 0 }, .id = f.next_id }; + f.next_id += 1; + gop.value_ptr.* = lane; + const fill = &lane.fill.?; + if (f.store) |*st| { + var arena: std.heap.ArenaAllocator = .init(f.gpa); + defer arena.deinit(); + fill.kept0 = st.counts.kept; + const plan = st.begin(arena.allocator(), prompt, s.history_len, s.shared_prefixes, &.{}, lane, &.{}) catch pc.Plan{}; + fill.at = plan.from; + fill.from = plan.from; + fill.count = @min(plan.marks.len, fill.stops.len); + for (plan.marks[0..fill.count], 0..) |mk, i| fill.stops[i] = mk; + } + s.cached = @intCast(fill.at); + return lane; + } + + /// One prompt chunk (64-row aligned cuts); the head absorbs its rows; the last chunk draws the first token. + fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!bool { + const f = of(ptr); + if (s.isCancelled()) return error.Cancelled; + const lane = if (f.lanes.get(s)) |l| (if (l.fill != null) l else try f.begin(s)) else try f.begin(s); + const e = f.e; + const m = &e.weights.model; + const prompt = s.prompt(); + const fill = &lane.fill.?; + const at = fill.at; + const stop: usize = if (fill.next < fill.count) fill.stops[fill.next] else prompt.len; + // the idle chunk alone, the shorter one while other streams decode between chunks (both on the 64-row grid) + const chunk: usize = if (f.decoding(lane)) e.o.policy.fill_rows else e.o.chunk; + const to = @min(stop, at + chunk); + const last = to == prompt.len; + const out = try e.prompt(&lane.caches, prompt[at..to]); + const rows = to - at; + const row_bytes = m.dims.wide() * m.act.size(); + if (lane.head) |*hc| { + // the head's keys for every prompt row with a next token (the last waits for the first draw) + const n = if (last) rows - 1 else rows; + if (n > 0) _ = try head_mod.run(e.ops(&e.arena), m, &e.host, hc, out.streams, prompt[at + 1 ..][0..n], at, f.ones); + } + fill.at = to; + if (fill.next < fill.count and to == fill.stops[fill.next]) { + if (f.store) |*st| _ = st.keep(prompt, @intCast(to), lane, &.{}, &.{}); + fill.next += 1; + } + if (!last) return false; + if (f.store) |*st| st.report(prompt.len, @intCast(fill.from), st.counts.kept - fill.kept0); + try hip.raw.copy(lane.streams, 0, out.streams.ptr + (rows - 1) * row_bytes, row_bytes, e.stream.handle); + if (s.grammar != null and lane.first_row == null) lane.first_row = try f.gpa.alloc(u16, e.cfg.vocab); + const o = e.ops(&e.arena); + const logits = try e.logits(o, forward.at(out.mixed, (rows - 1) * m.dims.hidden), 1); + var token: [1]u32 = undefined; + try e.drawer.draw(o, e.stream, logits, &.{.{ .sampling = sampling(s), .position = prompt.len, .keep = if (s.grammar != null) lane.first_row else null }}, &token, false); + _ = f.take(token[0]); + lane.fill = null; + return true; + } + + fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const f = of(ptr); + if (position != s.prompt_len) return error.PositionMismatch; + return f.next - 1; + } + + fn firstMaskedFn(ptr: *anyopaque, s: *lanes.Stream, position: u64, bits: []const u32) anyerror!u64 { + const f = of(ptr); + if (position != s.prompt_len) return error.PositionMismatch; + const lane = f.lanes.get(s) orelse return error.UnknownStream; + const kept = lane.first_row orelse return error.StructuresUnsupported; + const row = try f.gpa.dupe(u16, kept); + defer f.gpa.free(row); + return f.take(try f.e.drawer.drawHost(row, .{ .sampling = sampling(s), .position = position, .mask = bits })); + } + + fn heldTokensFn(ptr: *anyopaque, s: *lanes.Stream, out: []u32) anyerror!void { + const lane = of(ptr).lanes.get(s) orelse return error.UnknownStream; + if (out.len > lane.held_n) return error.NoHeldDrafts; + @memcpy(out, lane.held[0..out.len]); + } + + fn queueFn(_: *anyopaque, _: *lanes.Stream, _: be.Feed, _: u64) anyerror!u64 { + return error.NotPipelined; + } + + fn readFn(ptr: *anyopaque, handle: u64) anyerror!u32 { + const f = of(ptr); + if (handle >= f.next or f.next - handle > ring) return error.NoSuchToken; + return f.drawn[handle % ring]; + } + + /// Every window in one forward, each from its stream's kept length; every row drawn at its position. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const f = of(ptr); + const e = f.e; + const m = &e.weights.model; + if (windows.len > forward.max_segs) return error.WindowTooWide; + var tokens: [forward.max_segs][cache.max_window]u32 = undefined; + var segs: [forward.max_segs]forward.Seg = undefined; + var total: usize = 0; + for (windows, 0..) |w, i| { + if (w.parents != null) return error.TreesNotBuilt; + const lane = f.lanes.get(w.stream) orelse return error.UnknownStream; + if (lane.pending) |p| try f.mark(lane, p.rows); + const n = w.rows(); + if (n > cache.max_window) return error.WindowTooWide; + if (w.held > lane.held_n or (w.held > 0 and w.tokens.len > 0)) return error.NoHeldDrafts; + tokens[i][0] = w.pending; + if (w.held > 0) @memcpy(tokens[i][1..n], lane.held[0..w.held]) else @memcpy(tokens[i][1..n], w.tokens); + const len = lane.caches.len; + for (w.positions, 0..) |p, r| if (p != len + 1 + r) return error.PositionMismatch; + segs[i] = .{ .c = &lane.caches, .tokens = tokens[i][0..n], .pos = len }; + total += n; + } + const fw = try e.runMany(segs[0..windows.len], true); + const row_bytes = m.dims.wide() * m.act.size(); + var off: usize = 0; + for (windows) |w| { + const lane = f.lanes.get(w.stream).?; + try hip.raw.copy(lane.streams, 0, fw.streams.ptr + off * row_bytes, w.rows() * row_bytes, e.stream.handle); + off += w.rows(); + } + const o = e.ops(&e.arena); + const logits = try e.logits(o, fw.mixed, total); + var reqs: [forward.max_segs * cache.max_window]draw.Request = undefined; + var drawn: [forward.max_segs * cache.max_window]u32 = undefined; + off = 0; + for (windows) |w| { + const n = w.rows(); + const words = if (w.masks.len > 0) w.masks.len / n else 0; + for (w.positions, 0..) |p, r| reqs[off + r] = .{ .sampling = sampling(w.stream), .position = p, .mask = w.masks[r * words ..][0..words] }; + off += n; + } + if (total > e.drawer.rows) return error.WindowTooWide; + try e.drawer.draw(o, e.stream, logits, reqs[0..total], drawn[0..total], false); + off = 0; + for (windows, out, 0..) |w, *v, i| { + const n = w.rows(); + const lane = f.lanes.get(w.stream).?; + @memcpy(v.sampled[0..n], drawn[off..][0..n]); + @memcpy(v.drafts, if (w.held > 0) lane.held[0..w.held] else w.tokens); + lane.held_n = 0; + lane.pending = .{ .tokens = tokens[i], .rows = n }; + off += n; + } + } + + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const f = of(ptr); + for (windows, paths) |w, path| { + const lane = f.lanes.get(w.stream) orelse return error.UnknownStream; + for (path, 0..) |r, j| if (r != j) return error.TreesNotBuilt; + if (lane.pending != null) try f.mark(lane, path.len); + } + } + + /// The head absorbs each stream's kept rows (residual streams and the token after each), then chains its drafts. + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + const f = of(ptr); + const e = f.e; + const m = &e.weights.model; + const row_bytes = m.dims.wide() * m.act.size(); + for (requests) |r| { + const lane = f.lanes.get(r.stream) orelse return error.UnknownStream; + if (lane.pending) |p| try f.mark(lane, if (r.rows) |kept| kept.len else p.rows); + lane.held_n = 0; + if (r.position != lane.caches.len + 1) return error.PositionMismatch; + const hc = if (lane.head) |*h| h else continue; + const token: u32 = if (r.rows != null) r.follow[r.follow.len - 1] else switch (r.first orelse return error.NoFirstToken) { + .handle => |at| f.drawn[at % ring], + .value => |v| v, + }; + var follow_buf: [cache.max_window]u32 = undefined; + const follow: []const u32 = if (r.rows != null) r.follow else blk: { + follow_buf[0] = token; + break :blk follow_buf[0..1]; + }; + const start = lane.caches.len - follow.len; + try e.stream.synchronize(); + e.host.used = 0; + e.arena.reset(); + const o = e.ops(&e.arena); + var out = try head_mod.run(o, m, &e.host, hc, .{ .ptr = lane.streams.base(), .kind = m.act }, follow, start, f.ones); + var mixed = forward.at(out.mixed, (follow.len - 1) * m.dims.hidden); + var streams = out.streams.ptr + (follow.len - 1) * row_bytes; + const depth = @min(r.depth, max_depth); + // a chain past the first round ends after a draft the head gives under the confidence (--mtp-confidence) + const stop_under: f32 = if (r.rows != null) @floatCast(e.o.policy.mtp.confidence) else 0.0; + var d: usize = 0; + var chained: usize = 0; + while (d < depth) : (d += 1) { + var tok: [1]u32 = undefined; + var prob: [1]f32 = undefined; + try head_mod.draws(o, m, &e.host, e.stream, mixed, 1, f.draft_ids, &tok, &prob); + lane.held[d] = tok[0]; + chained = d + 1; + if (d + 1 == depth or prob[0] < stop_under) break; + out = try head_mod.run(o, m, &e.host, hc, .{ .ptr = streams, .kind = m.act }, &tok, lane.caches.len + d, f.ones); + mixed = out.mixed; + streams = out.streams.ptr; + } + lane.held_n = chained; + } + } + + fn heldFn(ptr: *anyopaque, s: *lanes.Stream, _: std.mem.Allocator) anyerror!?lanes.stream.Held { + const lane = of(ptr).lanes.get(s) orelse return error.UnknownStream; + return .{ .count = @intCast(lane.held_n) }; + } + + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { + const f = of(ptr); + const kv = f.lanes.fetchRemove(s) orelse return; + f.free(kv.value); + } +}; diff --git a/zig/src/families/flashnext/hip/native.zig b/zig/src/families/flashnext/hip/native.zig index fd778e12882..0aced9d9648 100644 --- a/zig/src/families/flashnext/hip/native.zig +++ b/zig/src/families/flashnext/hip/native.zig @@ -6,6 +6,9 @@ const config = @import("../config.zig"); const index = @import("../index.zig"); const plan = @import("plan.zig"); const Spec = @import("../spec.zig").Spec; +const Engine = @import("engine.zig").Engine; +const cache = @import("cache.zig"); +const lanes_mod = @import("lanes.zig"); pub const model_type = "qwen4_exp"; /// The MLX affine checkpoints the plan admits; the HIP products read 2- to 8-bit codes in groups of 32 to 128. @@ -76,25 +79,80 @@ fn cardRoom(gpa: std.mem.Allocator, io: std.Io, dev: hip.Device) !u64 { return pool.room(hip.usage(false).device); } -/// Admission, then the refusal that stands until the forward lands: the server says what fits and why it stops. -fn check(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) Refused { +/// Admission before anything loads: the format, the tensors and whether the rank's share and one stream fit. +fn check(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) Refused!void { var c = config.Config.read(gpa, io, dir) catch |err| return refuse(a, problem, "{s} is not a Flash Next checkpoint the HIP engine reads ({s})", .{ dir, @errorName(err) }); defer c.deinit(); const text = readIndex(a, io, dir) catch |err| return refuse(a, problem, "cannot read {s}/model.safetensors.index.json ({s})", .{ dir, @errorName(err) }); const bytes = cardRoom(gpa, io, dev) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)}); + if (o.world > 1) return refuse(a, problem, "Flash Next on HIP runs on one rank here: --tp {d} is not served", .{o.world}); const v = admit(a, gpa, &c, text, o.world, o.rank, o.window, bytes, problem) catch |err| return err; if (!v.fits) return refuse(a, problem, "Flash Next {d}-bit on {d} rank(s) holds {d:.2} GiB of weights a rank ({d:.1} GiB of n-gram tables in host memory) and {d:.1} GiB of scratch, of the {d:.2} GiB this card grants: a {d}-token window does not fit (at most {d}); lower --context, add ranks (--tp), or use a lower-bit checkpoint", .{ v.spec.bits, o.world, gibs(v.weights), gibs(v.host), gibs(scratch_bytes), gibs(bytes), o.window, v.most }); - return refuse(a, problem, "Flash Next {d}-bit fits rank {d} of {d} ({d:.2} GiB of weights, windows up to {d} tokens), but the HIP forward is not in this build yet", .{ v.spec.bits, o.rank, o.world, gibs(v.weights), v.most }); } +/// The positions a stream holds: the window and a verify's rows past it, on 64. +fn capacity(window: usize) usize { + return std.mem.alignForward(usize, window + cache.max_window + 1, 64); +} + +fn engineOf(gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype) !*Engine { + return Engine.open(gpa, io, dir, .{ .device = dev.index, .policy = dev.policy, .capacity = capacity(o.window), .chunk = @max(dev.policy.prefill_step, dev.policy.fill_rows) }); +} + +const Owned = struct { + gpa: std.mem.Allocator, + e: *Engine, + fx: *lanes_mod.Fx, + startup: []const u8, + + fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.fx.deinit(); + own.e.deinit(); + own.gpa.free(own.startup); + own.gpa.destroy(own); + } +}; + /// The engine for `dir` on `dev`; under tensor parallelism this is rank 0, which serves. pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) anyerror!Loaded { - return check(a, gpa, io, dev, dir, o, problem); + try check(a, gpa, io, dev, dir, o, problem); + const e = engineOf(gpa, io, dev, dir, o) catch |err| return refuse(a, problem, "the native HIP engine cannot load Flash Next from {s} ({s})", .{ dir, @errorName(err) }); + errdefer e.deinit(); + // the streams the memory left after the weights and the scratch holds at the window + const room = (hip.admission.budget(gpa, io, e.ctx) catch |err| return refuse(a, problem, "the native HIP engine cannot read the GPU's memory ({s})", .{@errorName(err)})).room(hip.usage(false).device); + const per = streamBytes(e, capacity(o.window)); + const fit = room / per; + if (fit == 0) return refuse(a, problem, "one stream at a {d}-token window takes {d:.2} GiB and {d:.2} GiB is left after the weights; lower --context or add ranks (--tp)", .{ o.window, gibs(per), gibs(room) }); + if (fit < o.streams and o.fixed) return refuse(a, problem, "--parallel {d} needs {d:.2} GiB at a {d}-token window and {d:.2} GiB is left: serve --parallel {d}, or lower --context", .{ o.streams, gibs(per * o.streams), o.window, gibs(room), fit }); + const streams = @min(fit, @max(o.streams, 1)); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + const fx = try lanes_mod.Fx.init(gpa, e, streams); + errdefer fx.deinit(); + // kept prompt states live in host memory: --prompt-cache-gib, else 16 GiB + fx.keepPrompts(@intFromFloat((o.cache_gib orelse 16.0) * (1 << 30))); + const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: Flash Next, {d:.2} GiB on the device, {d} stream{s} of {d} positions, {d:.2} GiB each; prompts in {d}-row chunks", .{ hip.kernels.arch, dev.index, o.rank, o.world, gibs(hip.usage(false).device), streams, if (streams == 1) "" else "s", capacity(o.window), gibs(per), e.o.chunk }); + own.* = .{ .gpa = gpa, .e = e, .fx = fx, .startup = startup }; + return .{ .backend = fx.backend(), .facts = fx.facts(), .rows = cache.max_window, .ctx = own, .deinit = Owned.release, .streams = streams, .startup = startup }; +} + +/// Device bytes a stream takes at `cap` positions: its caches, window snapshots, the head's caches and its rows. +fn streamBytes(e: *const Engine, cap: usize) usize { + var buf: [config.max_layers]bool = undefined; + const kinds = e.kinds(&buf) catch return std.math.maxInt(usize); + const l = cache.Layout.of(e.weights.model.dims, kinds, cap, e.act); + var head: usize = 0; + if (e.weights.model.mtp) |h| { + const hl = cache.Layout.of(h.dims, &.{false}, cap, e.act); + head = hl.bytes() + hl.cinBytes() + 4; + } + return l.bytes() + l.windowBytes() + l.cinBytes() + head + cache.max_window * e.weights.model.dims.wide() * e.act.size(); } -/// A rank above 0: holds its share of the model and runs rank 0's steps until rank 0 stops. +/// A rank above 0: refused, the engine runs on one rank. pub fn follow(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, dev: hip.Device, dir: []const u8, o: anytype, problem: *[]const u8) anyerror!void { - return check(a, gpa, io, dev, dir, o, problem); + try check(a, gpa, io, dev, dir, o, problem); } const gib: u64 = 1 << 30; diff --git a/zig/src/families/flashnext/hip/snapshot.zig b/zig/src/families/flashnext/hip/snapshot.zig new file mode 100644 index 00000000000..d54f3e05929 --- /dev/null +++ b/zig/src/families/flashnext/hip/snapshot.zig @@ -0,0 +1,100 @@ +//! A stream's state after its first `at` prompt tokens, copied to host memory and back: the prompt cache's entries. +const std = @import("std"); +const hip = @import("hip"); +const cache = @import("cache.zig"); + +/// One span of a cache's device memory a state at `at` holds. +const Region = struct { offset: usize, len: usize }; + +/// The spans of `c` holding the state at `at`: the sparse layers' first `at` rows a kv head at a time, the rest whole. +fn regions(c: *const cache.Caches, at: usize, ratio: usize, out: *std.ArrayList(Region), gpa: std.mem.Allocator) !void { + const l = c.layout; + const kv_heads = l.kv_heads; + const hd_bytes = l.head_dim * l.act; + const di_bytes = l.index_dim * l.act; + var base: usize = 0; + for (0..l.sparse) |_| { + for (0..2) |kv| for (0..kv_heads) |h| { + try out.append(gpa, .{ .offset = base + kv * l.kv_bytes + h * l.cap * hd_bytes, .len = at * hd_bytes }); + }; + try out.append(gpa, .{ .offset = base + 2 * l.kv_bytes, .len = at * di_bytes }); + try out.append(gpa, .{ .offset = base + 2 * l.kv_bytes + l.raw_bytes, .len = at / ratio * di_bytes }); + base += 2 * l.kv_bytes + l.raw_bytes + l.pooled_bytes; + } + try out.append(gpa, .{ .offset = base, .len = l.bytes() - base }); +} + +pub const Saved = struct { + at: u32, + pooled: usize, + history: [2]i64, + main: []u8, + head: []u8, + + pub fn bytes(s: *const Saved) u64 { + return s.main.len + s.head.len; + } +}; + +fn copyOut(d: *const hip.Runtime, c: *const cache.Caches, at: usize, ratio: usize, gpa: std.mem.Allocator) ![]u8 { + var list: std.ArrayList(Region) = .empty; + defer list.deinit(gpa); + try regions(c, at, ratio, &list, gpa); + var n: usize = 0; + for (list.items) |r| n += r.len; + const out = try gpa.alloc(u8, n); + errdefer gpa.free(out); + var off: usize = 0; + for (list.items) |r| { + if (r.len > 0) try hip.runtime.check(d.api.hipMemcpyDtoH(out[off..].ptr, @ptrFromInt(c.mem.base() + r.offset), r.len)); + off += r.len; + } + return out; +} + +fn copyIn(d: *const hip.Runtime, c: *const cache.Caches, at: usize, ratio: usize, bytes: []const u8, gpa: std.mem.Allocator) !void { + var list: std.ArrayList(Region) = .empty; + defer list.deinit(gpa); + try regions(c, at, ratio, &list, gpa); + var off: usize = 0; + for (list.items) |r| { + if (off + r.len > bytes.len) return error.SnapshotMismatch; + if (r.len > 0) try hip.runtime.check(d.api.hipMemcpyHtoD(@ptrFromInt(c.mem.base() + r.offset), @constCast(bytes[off..].ptr), r.len)); + off += r.len; + } + if (off != bytes.len) return error.SnapshotMismatch; +} + +/// The state of `c` (and the head's `head`) after `at` prompt tokens, copied to host memory; the stream is idle. +pub fn save(gpa: std.mem.Allocator, d: *const hip.Runtime, s: hip.Stream, c: *const cache.Caches, head: ?*const cache.Caches, at: usize, ratio: usize) !*Saved { + try s.synchronize(); + if (c.len != at) return error.SnapshotNotAtMark; + const out = try gpa.create(Saved); + errdefer gpa.destroy(out); + const main = try copyOut(d, c, at, ratio, gpa); + errdefer gpa.free(main); + const h: []u8 = if (head) |x| try copyOut(d, x, at, ratio, gpa) else &.{}; + out.* = .{ .at = @intCast(at), .pooled = c.pooled, .history = c.history, .main = main, .head = h }; + return out; +} + +/// `saved` made the live state of `c` and `head`: the next prompt chunk starts at its position. +pub fn restore(gpa: std.mem.Allocator, d: *const hip.Runtime, s: hip.Stream, saved: *const Saved, c: *cache.Caches, head: ?*cache.Caches, ratio: usize) !void { + try s.synchronize(); + if (saved.at + 1 > c.layout.cap) return error.SnapshotTooLong; + try copyIn(d, c, saved.at, ratio, saved.main, gpa); + if (head) |h| try copyIn(d, h, saved.at, ratio, saved.head, gpa); + c.len = saved.at; + c.pooled = saved.pooled; + c.history = saved.history; + if (head) |h| { + h.len = saved.at; + h.pooled = saved.at / ratio; + } +} + +pub fn drop(gpa: std.mem.Allocator, saved: *Saved) void { + gpa.free(saved.main); + if (saved.head.len > 0) gpa.free(saved.head); + gpa.destroy(saved); +} diff --git a/zig/tests/flashnext_hip/bench.py b/zig/tests/flashnext_hip/bench.py new file mode 100644 index 00000000000..991fb306ab6 --- /dev/null +++ b/zig/tests/flashnext_hip/bench.py @@ -0,0 +1,57 @@ +"""Streamed serving speed; usage: bench.py URL MODEL [PROMPT_TOKENS] [REPLY_TOKENS] [CONCURRENCY] [DRAFT].""" + +import json +import sys +import threading +import time +import urllib.request +from statistics import mean, median + +URL, MODEL = sys.argv[1], sys.argv[2] +PROMPT = int(sys.argv[3]) if len(sys.argv) > 3 else 2048 +REPLY = int(sys.argv[4]) if len(sys.argv) > 4 else 256 +CONC = int(sys.argv[5]) if len(sys.argv) > 5 else 1 +DRAFT = (sys.argv[6] if len(sys.argv) > 6 else "on") == "on" + + +def text(n, seed): + """About n tokens of distinct words (the tokenizer takes most as one or two tokens).""" + return " ".join(f"item{(i * 7919 + seed * 104729) % 100003}" for i in range(n // 3)) + "\nSummarize the list above in one long paragraph." + + +def run(seed, out): + body = {"model": MODEL, "messages": [{"role": "user", "content": text(PROMPT, seed)}], "max_tokens": REPLY, "temperature": 0.0, + "draft": DRAFT, "stream": True, "stream_options": {"include_usage": True}, "ignore_eos": True, + "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(URL + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + t0 = time.perf_counter() + stamps, usage = [], {} + with urllib.request.urlopen(request, timeout=3600) as reply: + for event in (raw.decode()[6:].strip() for raw in reply if raw.startswith(b"data: {")): + doc = json.loads(event) + usage = doc.get("usage") or usage + deltas = [c.get("delta", {}) for c in doc.get("choices", [])] + if any(x.get("content") or x.get("reasoning_content") for x in deltas): + stamps.append(time.perf_counter()) + out.append({"t0": t0, "stamps": stamps, "usage": usage}) + + +results = [] +threads = [threading.Thread(target=run, args=(i, results)) for i in range(CONC)] +start = time.perf_counter() +for t in threads: + t.start() +for t in threads: + t.join() +wall = time.perf_counter() - start +ttft = [r["stamps"][0] - r["t0"] for r in results if r["stamps"]] +itl = [b - a for r in results for a, b in zip(r["stamps"], r["stamps"][1:])] +prompt_tokens = sum(r["usage"].get("prompt_tokens", 0) for r in results) +reply_tokens = sum(r["usage"].get("completion_tokens", 0) for r in results) +decode = [(r["usage"].get("completion_tokens", 1) - 1) / (r["stamps"][-1] - r["stamps"][0]) for r in results if len(r["stamps"]) > 1] +print(json.dumps({ + "concurrency": CONC, "draft": DRAFT, "prompt_tokens_each": prompt_tokens // max(CONC, 1), "reply_tokens_each": reply_tokens // max(CONC, 1), + "ttft_ms_mean": round(1000 * mean(ttft), 1), "prefill_tok_s": round(prompt_tokens / max(sum(ttft), 1e-9) * CONC / CONC, 1), + "decode_tok_s_per_stream": round(mean(decode), 2), "decode_tok_s_total": round(sum(decode), 2), + "itl_ms_mean": round(1000 * mean(itl), 2) if itl else None, "itl_ms_p50": round(1000 * median(itl), 2) if itl else None, + "wall_s": round(wall, 2)})) diff --git a/zig/tests/flashnext_hip/rewind.py b/zig/tests/flashnext_hip/rewind.py new file mode 100644 index 00000000000..89dbc3edb21 --- /dev/null +++ b/zig/tests/flashnext_hip/rewind.py @@ -0,0 +1,58 @@ +"""Cache on equals cache off through rewinds, one server at a time; usage: rewind.py URL MODEL OUT.json [WANT.json].""" + +import json +import sys +import urllib.request + +URL, MODEL, OUT = sys.argv[1], sys.argv[2], sys.argv[3] +WANT = sys.argv[4] if len(sys.argv) > 4 else None +SYSTEM = "You are a careful assistant. Reference notes: " + " ".join(f"note{i % 89}x{(i * 7919) % 1013}" for i in range(1500)) + + +def chat(messages, draft): + """The reply's text and the prompt tokens the server says it took from kept states.""" + body = {"model": MODEL, "messages": messages, "max_tokens": 48, "temperature": 0.0, "draft": draft, + "chat_template_kwargs": {"enable_thinking": False}} + request = urllib.request.Request(URL + "/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=1800) as reply: + doc = json.loads(reply.read()) + cached = (doc.get("usage", {}).get("prompt_tokens_details") or {}).get("cached_tokens", 0) + return doc["choices"][0]["message"]["content"], cached + + +def script(): + """The steps of one conversation: turns, a regenerate, an edit, a delete, an edit of the first turn.""" + system = {"role": "system", "content": SYSTEM} + return [ + ("turn 1", lambda h: [system, {"role": "user", "content": "What is the first note?"}]), + ("turn 2", lambda h: h["turn 1"] + [{"role": "user", "content": "And the second one?"}]), + ("turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note5x5 listed?"}]), + ("regenerate turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note5x5 listed?"}]), + ("edit turn 3", lambda h: h["turn 2"] + [{"role": "user", "content": "Is note7x7 listed?"}]), + ("delete turn 3, then turn 4", lambda h: h["turn 2"] + [{"role": "user", "content": "Name the last note."}]), + ("edit turn 1", lambda h: [system, {"role": "user", "content": "What is the third note?"}]), + ("turn 2 again", lambda h: h["turn 1"] + [{"role": "user", "content": "And the second one?"}]), + ] + + +out = {} +for draft in (True, False): + history = {} + for name, build in script(): + messages = build(history) + text, cached = chat(messages, draft) + history[name] = messages + [{"role": "assistant", "content": text}] + out[f"{name}, drafts {'on' if draft else 'off'}"] = [text, cached] +json.dump(out, open(OUT, "w"), indent=1) +if WANT is None: + sys.exit(0) +want = json.load(open(WANT)) +bad = 0 +for key, (text, cached) in out.items(): + ok = text == want[key][0] + bad += not ok + print(f"{'PASS' if ok else 'FAIL'} rewind {key}: {cached} prompt tokens from kept states") + if not ok: + print(f" without the cache: {want[key][0]!r}\n with it: {text!r}") +print(f"rewind {'PASS' if bad == 0 else 'FAIL'}: {bad} differing replies") +sys.exit(1 if bad else 0) From 1ae10784cc720a62010bad99cb00769b5ed4862f Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:06:13 +0200 Subject: [PATCH 46/52] style(hip): the ops headers end without a blank line, as git diff --check wants --- zig/kernels/hip/ops/attention.hpp | 1 - zig/kernels/hip/ops/common.hpp | 1 - zig/kernels/hip/ops/draw.hpp | 1 - zig/kernels/hip/ops/elementwise.hpp | 1 - zig/kernels/hip/ops/linear.hpp | 1 - zig/kernels/hip/ops/moe.hpp | 1 - zig/kernels/hip/ops/rope.hpp | 1 - 7 files changed, 7 deletions(-) diff --git a/zig/kernels/hip/ops/attention.hpp b/zig/kernels/hip/ops/attention.hpp index aa5499542b2..c97bcf67f5a 100644 --- a/zig/kernels/hip/ops/attention.hpp +++ b/zig/kernels/hip/ops/attention.hpp @@ -46,4 +46,3 @@ extern "C" __global__ void tf_kv_write_at(const void* src, void* cache, int kind } } // namespace - diff --git a/zig/kernels/hip/ops/common.hpp b/zig/kernels/hip/ops/common.hpp index 4cebf7bcc0a..980e5b5645c 100644 --- a/zig/kernels/hip/ops/common.hpp +++ b/zig/kernels/hip/ops/common.hpp @@ -44,4 +44,3 @@ __device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(- __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 index 335f002a682..def5b8fba4e 100644 --- a/zig/kernels/hip/ops/draw.hpp +++ b/zig/kernels/hip/ops/draw.hpp @@ -134,4 +134,3 @@ extern "C" __global__ void tf_topk(const uint16_t* logits, int n, const int* ks, } } // namespace - diff --git a/zig/kernels/hip/ops/elementwise.hpp b/zig/kernels/hip/ops/elementwise.hpp index 9fbac8b884b..0b1d5bb7aed 100644 --- a/zig/kernels/hip/ops/elementwise.hpp +++ b/zig/kernels/hip/ops/elementwise.hpp @@ -79,4 +79,3 @@ extern "C" __global__ void tf_dense_rows(const void* x, int kind, const float* w } } // namespace - diff --git a/zig/kernels/hip/ops/linear.hpp b/zig/kernels/hip/ops/linear.hpp index fd2ce6950a9..e77529f1677 100644 --- a/zig/kernels/hip/ops/linear.hpp +++ b/zig/kernels/hip/ops/linear.hpp @@ -62,4 +62,3 @@ extern "C" __global__ void tf_gnorm_silu(const float* y, const void* z, void* ou } } // namespace - diff --git a/zig/kernels/hip/ops/moe.hpp b/zig/kernels/hip/ops/moe.hpp index 885f8881021..f12329e903a 100644 --- a/zig/kernels/hip/ops/moe.hpp +++ b/zig/kernels/hip/ops/moe.hpp @@ -215,4 +215,3 @@ extern "C" __global__ void __launch_bounds__(256) tf_router_rows_bf16(const void int r, int d, int e) { router_rows<2>(x, rows, logits, r, d, e); } - diff --git a/zig/kernels/hip/ops/rope.hpp b/zig/kernels/hip/ops/rope.hpp index 27c50aec8bd..12b481e481d 100644 --- a/zig/kernels/hip/ops/rope.hpp +++ b/zig/kernels/hip/ops/rope.hpp @@ -84,4 +84,3 @@ extern "C" __global__ void __launch_bounds__(256) tf_qk_rope(const void* src, in } } // namespace - From 5537d6a2f777e189d6cafc962ea8b22d882b9e08 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:34:40 +0200 Subject: [PATCH 47/52] fix(hip): the paged prefill tile calls expf, as the flat tile does --- zig/kernels/hip/attention/prefill.hip | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/kernels/hip/attention/prefill.hip b/zig/kernels/hip/attention/prefill.hip index e50c9ed37c8..87e39f57d46 100644 --- a/zig/kernels/hip/attention/prefill.hip +++ b/zig/kernels/hip/attention/prefill.hip @@ -168,11 +168,11 @@ __device__ void fa_dot2(const float* __restrict__ q, const Cache* __restrict__ k #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); + 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); + p[j] = next_m == -INFINITY ? 0.f : expf(acc[i][j] - next_m); sum += p[j]; } #pragma unroll From d91b07405afc3896d4503fd551784abc9cf16590 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:44:49 +0200 Subject: [PATCH 48/52] fix(hip): one fp32 DeltaNet recurrence at every length; the chunked prefill kernel goes gatedDelta sent 64 rows or any prefill to gdn_prefill.hip (fp16 products, __expf), so a prompt cut on either side of 64 rows was a different sum. Every length now runs the fp32 recurrence. The new test cuts a 200-row prompt at 1, 63, 64, 65 and 136 rows and checks the rows and state equal one call's bits; it fails with the chunked kernel. --- zig/build/hip.zig | 4 +- zig/kernels/hip/recurrence/gdn_prefill.hip | 471 --------------------- zig/src/hip/kernel_tests/gdn.zig | 76 +++- zig/src/hip/kernel_tests/rig.zig | 4 +- zig/src/hip/kernels.zig | 2 +- zig/src/hip/launches.zig | 11 +- zig/src/hip/launches/recurrence.zig | 90 +--- zig/src/hip/ops/ops.zig | 2 +- zig/src/hip/ops/recurrence.zig | 25 +- 9 files changed, 69 insertions(+), 616 deletions(-) delete mode 100644 zig/kernels/hip/recurrence/gdn_prefill.hip diff --git a/zig/build/hip.zig b/zig/build/hip.zig index c20bddcaf22..99e84273c32 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -76,7 +76,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu } /// 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", "recurrence/gdn_prefill.hip", "decode/decode.hip", "decode/plan.hip" }; +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" }; @@ -84,7 +84,7 @@ const headers = [_][]const u8{ "attention/attention_fa.hip", "decode/pages.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: [8][]align(8) const u8 = @splat(&.{});\n"; +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 { diff --git a/zig/kernels/hip/recurrence/gdn_prefill.hip b/zig/kernels/hip/recurrence/gdn_prefill.hip deleted file mode 100644 index eb637254379..00000000000 --- a/zig/kernels/hip/recurrence/gdn_prefill.hip +++ /dev/null @@ -1,471 +0,0 @@ -// Chunked Gated DeltaNet for long prompts after FLA's chunk_gated_delta_rule, in five kernels: prep, kt, wy, h, o. - -// fp16 operands and fp32 accumulation through v_dot2_f32_f16; the state and every sum stay fp32. - -// Shared-memory rows are 16-byte aligned and four banks apart: a 16-byte read of eight consecutive rows is one pass. - -#include - - -namespace { - -using half_t = _Float16; -using half2_t = _Float16 __attribute__((ext_vector_type(2))); - -constexpr int kBT = 64; // chunk -constexpr int kD = 128; // head size, keys and values -constexpr int kThreads = 256; -constexpr int kBV = 16; // value rows of a state block -constexpr int kLd = kD + 8; // a 128-wide fp16 row in shared memory -constexpr int kTLd = kBT + 8; // a 64-wide one -constexpr int kTile = kBT * kD; // a chunk's tile, in values - -struct alignas(16) Quad { - half2_t p[4]; -}; - -__device__ __forceinline__ float dot2(half2_t a, half2_t b, float c) { return __builtin_amdgcn_fdot2(a, b, c, false); } -__device__ __forceinline__ Quad ld_quad(const half_t* p) { return *reinterpret_cast(p); } -__device__ __forceinline__ Quad zero_quad() { - Quad z; - for (int i = 0; i < 4; ++i) z.p[i] = half2_t{static_cast(0), static_cast(0)}; - return z; -} - -// A barrier for data that moved through shared memory only: the global stores in flight need not land first. -__device__ __forceinline__ void lds_sync() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); - __builtin_amdgcn_s_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); -} - -// x from the lane whose index differs in bit 0, or in bit 1 (within a quad). -__device__ __forceinline__ float quad_xor1(float x) { - return __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(0, __builtin_bit_cast(int, x), 0xB1, 0xF, 0xF, true)); -} -__device__ __forceinline__ float quad_xor2(float x) { - return __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(0, __builtin_bit_cast(int, x), 0x4E, 0xF, 0xF, true)); -} - -// acc[r][c] += (row r of a) . (row c of b) over the 8-wide groups from g_first by g_stride below g_end, for c < NC. -template -__device__ __forceinline__ void tile_acc(float (&acc)[4][4], const half_t* a, int lda, const half_t* b, int b_step, - int g_first, int g_end, int g_stride) { -#pragma unroll 2 - for (int g = g_first; g < g_end; g += g_stride) { - Quad x[4], y[NC]; -#pragma unroll - for (int r = 0; r < 4; ++r) x[r] = ld_quad(a + r * lda + 8 * g); -#pragma unroll - for (int c = 0; c < NC; ++c) y[c] = ld_quad(b + c * b_step + 8 * g); -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < NC; ++c) -#pragma unroll - for (int i = 0; i < 4; ++i) acc[r][c] = dot2(x[r].p[i], y[c].p[i], acc[r][c]); - } -} - -// The same over every group with `nc` (1 to 4, the same for the whole wave) columns. -__device__ __forceinline__ void tile_acc_wave(float (&acc)[4][4], const half_t* a, int lda, const half_t* b, int b_step, - int nc) { - switch (nc) { - case 1: tile_acc<1>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; - case 2: tile_acc<2>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; - case 3: tile_acc<3>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; - default: tile_acc<4>(acc, a, lda, b, b_step, 0, kD / 8, 1); break; - } -} - -// A chunk tile as the 16-byte pieces a thread fetches, rows from `n` on zero, stored into shared rows of kLd. -struct Tile { - Quad piece[4]; - - __device__ __forceinline__ void fetch(const half_t* src, int n) { -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int idx = threadIdx.x + j * kThreads; - piece[j] = (idx >> 4) < n ? ld_quad(src + idx * 8) : zero_quad(); - } - } - - __device__ __forceinline__ void store(half_t* dst) const { -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int idx = threadIdx.x + j * kThreads; - *reinterpret_cast(&dst[(idx >> 4) * kLd + 8 * (idx & 15)]) = piece[j]; - } - } -}; - -} // namespace - -// q, k (key heads) and v (value heads) to fp16 tiles [chunk][head][64][128]. -extern "C" __global__ void __launch_bounds__(kThreads) -tf_gdn_prep(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, - half_t* __restrict__ qh, half_t* __restrict__ kh, half_t* __restrict__ vh, int length, int key_heads, - int value_heads) { - const long long id = static_cast(blockIdx.x) * kThreads + threadIdx.x; - const long long nk = static_cast(length) * key_heads * (kD / 4); - const long long nv = static_cast(length) * value_heads * (kD / 4); - if (id < nk + nv) { - const bool is_v = id >= nk; - const long long at = is_v ? id - nk : id; - const int heads = is_v ? value_heads : key_heads; - const int d4 = static_cast(at & 31); - const long long row = at >> 5; // t * heads + head - const int head = static_cast(row % heads); - const long long t = row / heads; - const long long out = (((t >> 6) * heads + head) * kBT + (t & 63)) * kD + 4 * d4; - auto put = [&](const float* src, half_t* dst) { - const float4 a = reinterpret_cast(src)[at]; - half2_t* o = reinterpret_cast(dst + out); - o[0] = half2_t{static_cast(a.x), static_cast(a.y)}; - o[1] = half2_t{static_cast(a.z), static_cast(a.w)}; - }; - if (is_v) { - put(v, vh); - } else { - put(q, qh); - put(k, kh); - } - } -} - -// kt[chunk][key head][key][token]: each chunk's keys transposed, tokens past the end zero. -extern "C" __global__ void __launch_bounds__(kThreads) -tf_gdn_kt(const half_t* __restrict__ kh, half_t* __restrict__ kt, int length, int key_heads) { - __shared__ alignas(16) half_t sT[kD * kTLd]; - const int tid = threadIdx.x; - const int chunk = blockIdx.x; - const int head = blockIdx.y; - const int n = min(kBT, length - chunk * kBT); - const half_t* tile = kh + (static_cast(chunk) * key_heads + head) * kTile; - for (int idx = tid; idx < kBT * (kD / 8); idx += kThreads) { - const int t = idx & 63, cg = idx >> 6; - Quad x = zero_quad(); - if (t < n) x = ld_quad(tile + t * kD + 8 * cg); -#pragma unroll - for (int i = 0; i < 4; ++i) { - sT[(8 * cg + 2 * i) * kTLd + t] = x.p[i][0]; - sT[(8 * cg + 2 * i + 1) * kTLd + t] = x.p[i][1]; - } - } - lds_sync(); - half_t* out = kt + (static_cast(chunk) * key_heads + head) * kD * kBT; - for (int idx = tid; idx < kD * (kBT / 8); idx += kThreads) { - const int key = idx >> 3, c8 = idx & 7; - *reinterpret_cast(&out[key * kBT + 8 * c8]) = ld_quad(&sT[key * kTLd + 8 * c8]); - } -} - -extern "C" __global__ void __launch_bounds__(kThreads) -tf_gdn_wy(const half_t* __restrict__ kh, const half_t* __restrict__ vh, const float* __restrict__ beta, - const float* __restrict__ gate, float* __restrict__ gc, half_t* __restrict__ w, half_t* __restrict__ u, int length, int key_heads, - int value_heads) { - __shared__ alignas(16) half_t sK[kBT * kLd]; - __shared__ alignas(16) float sA[kBT * kBT]; - __shared__ float sGc[kBT]; - __shared__ float sBeta[kBT]; - __shared__ float sBe[kBT]; - const int tid = threadIdx.x; - const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); - const int head = blockIdx.y; - const int chunk = blockIdx.x; - const int t0 = chunk * kBT; - const int n = min(kBT, length - t0); - const int key_head = head / (value_heads / key_heads); - const long long vtile = (static_cast(chunk) * value_heads + head) * kTile; - - Tile rows; - rows.fetch(kh + (static_cast(chunk) * key_heads + key_head) * kTile, n); - float rhs[kBT]; - const bool is_w = tid < kD; - const int col = tid & (kD - 1); - if (!is_w) { -#pragma unroll - for (int i = 0; i < kBT; ++i) rhs[i] = i < n ? static_cast(vh[vtile + i * kD + col]) : 0.f; - } - rows.store(sK); - if (tid < 32) { - // the chunk's running sum of log gate (a gate of 0 clamped), two tokens a lane - const long long at0 = static_cast(t0 + tid) * value_heads + head; - const long long at1 = at0 + 32LL * value_heads; - float a = tid < n ? logf(fmaxf(gate[at0], 1e-30f)) : 0.f; - float b = tid + 32 < n ? logf(fmaxf(gate[at1], 1e-30f)) : 0.f; -#pragma unroll - for (int d = 1; d < 32; d <<= 1) { - const float xa = __shfl_up(a, d, 32); - const float xb = __shfl_up(b, d, 32); - if (tid >= d) { - a += xa; - b += xb; - } - } - b += __shfl(a, 31, 32); - sGc[tid] = a; - sGc[tid + 32] = b; - if (tid < n) gc[at0] = a; - if (tid + 32 < n) gc[at1] = b; - } else if (tid < 96) { - const int i = tid - 32; - sBeta[i] = i < n ? beta[static_cast(t0 + i) * value_heads + head] : 0.f; - } - lds_sync(); - if (tid < kBT) sBe[tid] = sBeta[tid] * __expf(sGc[tid]); - - // A: each thread a 4 x 4 tile of rows 4 ti .. and columns tj + 16 c, the columns past the wave's last row skipped - { - const int ti = tid >> 4, tj = tid & 15; - const int nc = (8 * wave + 7) / 16 + 1; - float acc[4][4] = {}; - tile_acc_wave(acc, sK + ti * 4 * kLd, kLd, sK + tj * kLd, 16 * kLd, nc); -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) { - const int i = ti * 4 + r, j = tj + 16 * c; - sA[i * kBT + j] = i > j ? sBeta[i] * __expf(sGc[i] - sGc[j]) * acc[r][c] : 0.f; - } - } - lds_sync(); - if (is_w) { -#pragma unroll - for (int i = 0; i < kBT; ++i) rhs[i] = i < n ? sBe[i] * static_cast(sK[i * kLd + col]) : 0.f; - } else { -#pragma unroll - for (int i = 0; i < kBT; ++i) rhs[i] *= sBeta[i]; - } - - // (I + A) x = rhs down the rows, a column a thread: the first 128 threads w, the rest u - half_t* ocol = (is_w ? w : u) + vtile + col; -#pragma unroll - for (int i = 0; i < kBT; ++i) { - float s0 = 0.f, s1 = 0.f, s2 = 0.f, s3 = 0.f; - int m = 0; -#pragma unroll - for (; m + 4 <= i; m += 4) { - const float4 a = *reinterpret_cast(&sA[i * kBT + m]); - s0 = fmaf(a.x, rhs[m], s0); - s1 = fmaf(a.y, rhs[m + 1], s1); - s2 = fmaf(a.z, rhs[m + 2], s2); - s3 = fmaf(a.w, rhs[m + 3], s3); - } -#pragma unroll - for (; m < i; ++m) s0 = fmaf(sA[i * kBT + m], rhs[m], s0); - rhs[i] -= (s0 + s1) + (s2 + s3); - if (i < n) ocol[i * kD] = static_cast(rhs[i]); - } -} - -// vt[chunk][head][value][token] gets v_new = u - w H^T; hbuf[chunk][head][value][key] each chunk's start state (fp16). -extern "C" __global__ void __launch_bounds__(kThreads) -tf_gdn_h(const half_t* __restrict__ kt, const half_t* __restrict__ w, const half_t* __restrict__ u, - half_t* __restrict__ vt, const float* __restrict__ gc, float* __restrict__ state, half_t* __restrict__ hbuf, - int length, int key_heads, int value_heads) { - __shared__ alignas(16) half_t sH[kBV * kLd]; - __shared__ alignas(16) half_t sW[kBT * kLd]; - __shared__ alignas(16) half_t sKT[kD * kTLd]; - __shared__ alignas(16) half_t sVg[kBV * kTLd]; - __shared__ float sDecay[kBT]; - const int tid = threadIdx.x; - const int v0 = blockIdx.x * kBV; - const int head = blockIdx.y; - const int key_head = head / (value_heads / key_heads); - const int chunks = (length + kBT - 1) / kBT; - // the state: lane pairs share a (4 value rows, 4 keys) tile and both hold it - const int vq = tid >> 6, kg = (tid >> 1) & 31, half_id = tid & 1; - // the correction: a (4 tokens, 4 values) tile split over four lanes by key group - const int ks = tid & 3, ti = tid >> 4, vj = (tid >> 2) & 3; - - float h[4][4]; - float* st = state + (static_cast(head) * kD + v0 + 4 * vq) * kD + kg; -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) h[r][c] = st[r * kD + 32 * c]; - - Tile wt; - Quad ktp[4]; - half_t up[4]; - float g_next = 0.f, d_next = 0.f; - const int t_mine = 4 * ti + ks; - auto fetch_u = [&](int chunk) { - const int n = min(kBT, length - chunk * kBT); - const half_t* src = u + (static_cast(chunk) * value_heads + head) * kTile + t_mine * kD + v0 + vj; -#pragma unroll - for (int c = 0; c < 4; ++c) up[c] = t_mine < n ? src[4 * c] : static_cast(0); - }; - auto fetch_kt = [&](int chunk) { - const half_t* src = kt + (static_cast(chunk) * key_heads + key_head) * kD * kBT; -#pragma unroll - for (int j = 0; j < 4; ++j) ktp[j] = ld_quad(src + (tid + j * kThreads) * 8); - }; - auto fetch_gc = [&](int chunk) { - const int t0 = chunk * kBT; - const int n = min(kBT, length - t0); - g_next = gc[static_cast(t0 + n - 1) * value_heads + head]; - d_next = tid < n ? gc[static_cast(t0 + tid) * value_heads + head] : 0.f; - }; - auto fetch_w = [&](int chunk) { - wt.fetch(w + (static_cast(chunk) * value_heads + head) * kTile, min(kBT, length - chunk * kBT)); - }; - fetch_w(0); - fetch_kt(0); - fetch_u(0); - fetch_gc(0); - - for (int chunk = 0; chunk < chunks; ++chunk) { - const int n = min(kBT, length - chunk * kBT); - const float g_last = g_next; - // the start state: to shared memory for the correction, and out for o -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) - if ((r >> 1) == half_id) sH[(4 * vq + r) * kLd + kg + 32 * c] = static_cast(h[r][c]); - wt.store(sW); - if (tid < kBT) sDecay[tid] = tid < n ? __expf(g_last - d_next) : 0.f; - if (chunk + 1 < chunks) { - fetch_w(chunk + 1); - fetch_gc(chunk + 1); - } - lds_sync(); - - // the keys transposed for the update, the start state out -#pragma unroll - for (int j = 0; j < 4; ++j) { - const int idx = tid + j * kThreads; - *reinterpret_cast(&sKT[(idx >> 3) * kTLd + 8 * (idx & 7)]) = ktp[j]; - } - if (chunk + 1 < chunks) fetch_kt(chunk + 1); - { - const int row = tid >> 4, cg = tid & 15; - *reinterpret_cast( - &hbuf[((static_cast(chunk) * value_heads + head) * kD + v0 + row) * kD + 8 * cg]) = - ld_quad(&sH[row * kLd + 8 * cg]); - } - - // v_new[t][v] = u - sum_k w[t][k] H[v][k]: 4 x 4 tiles, the key groups split over four lanes - { - float acc[4][4] = {}; - tile_acc<4>(acc, sW + ti * 4 * kLd, kLd, sH + vj * kLd, 4 * kLd, ks, kD / 8, 4); -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) { - acc[r][c] += quad_xor1(acc[r][c]); - acc[r][c] += quad_xor2(acc[r][c]); - } -#pragma unroll - for (int c = 0; c < 4; ++c) { - const float mine = ks == 0 ? acc[0][c] : ks == 1 ? acc[1][c] : ks == 2 ? acc[2][c] : acc[3][c]; - const float vn = t_mine < n ? static_cast(up[c]) - mine : 0.f; - const int v = vj + 4 * c; - vt[((static_cast(chunk) * value_heads + head) * kD + v0 + v) * kBT + t_mine] = - static_cast(vn); - sVg[v * kTLd + t_mine] = static_cast(vn * sDecay[t_mine]); - } - } - if (chunk + 1 < chunks) fetch_u(chunk + 1); - lds_sync(); - - // H = exp(g_last) H + sum_t vg[t][v] kT[key][t]: the tokens split over a lane pair - { - float acc[4][4] = {}; - tile_acc<4>(acc, sVg + 4 * vq * kTLd, kTLd, sKT + kg * kTLd, 32 * kTLd, 4 * half_id, 4 * half_id + 4, 1); - const float decay = __expf(g_last); -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) h[r][c] = h[r][c] * decay + (acc[r][c] + quad_xor1(acc[r][c])); - } - } -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) - if ((r >> 1) == half_id) st[r * kD + 32 * c] = h[r][c]; -} - -// A block a (chunk, head): the scores once, then each half of the values (the next half's tiles fetched meanwhile). -extern "C" __global__ void __launch_bounds__(kThreads) -tf_gdn_o(const half_t* __restrict__ qh, const half_t* __restrict__ kh, const half_t* __restrict__ vt, - const half_t* __restrict__ hbuf, const float* __restrict__ gc, float* __restrict__ y, int length, - int key_heads, int value_heads) { - __shared__ alignas(16) half_t sQ[kBT * kLd]; - __shared__ alignas(16) half_t sK[kBT * kLd]; // the keys, then the start state's 64 value rows - __shared__ alignas(16) half_t sS[kBT * kTLd]; - __shared__ alignas(16) half_t sVT[kBT * kTLd]; - __shared__ float sGc[kBT]; - const int tid = threadIdx.x; - const int wave = __builtin_amdgcn_readfirstlane(tid >> 5); - const int chunk = blockIdx.x; - const int head = blockIdx.y; - const int t0 = chunk * kBT; - const int n = min(kBT, length - t0); - const int key_head = head / (value_heads / key_heads); - const int ti = tid >> 4, tj = tid & 15; - - const half_t* hsrc = hbuf + (static_cast(chunk) * value_heads + head) * kD * kD; - const half_t* vsrc = vt + (static_cast(chunk) * value_heads + head) * kD * kBT; - Tile tq, tk, th; - Quad pv[2]; - auto fetch_half = [&](int half) { -#pragma unroll - for (int j = 0; j < 4; ++j) th.piece[j] = ld_quad(hsrc + half * 64 * kD + (tid + j * kThreads) * 8); -#pragma unroll - for (int j = 0; j < 2; ++j) pv[j] = ld_quad(vsrc + half * 64 * kBT + (tid + j * kThreads) * 8); - }; - const long long ktile = (static_cast(chunk) * key_heads + key_head) * kTile; - tq.fetch(qh + ktile, n); - tk.fetch(kh + ktile, n); - fetch_half(0); - if (tid < kBT) sGc[tid] = tid < n ? gc[static_cast(t0 + tid) * value_heads + head] : 0.f; - tq.store(sQ); - tk.store(sK); - lds_sync(); - - // the masked, decayed scores q_t.k_j: a 4 x 4 tile of rows 4 ti .. and columns tj + 16 c - { - const int nc = (8 * wave + 7) / 16 + 1; - float acc[4][4] = {}; - tile_acc_wave(acc, sQ + ti * 4 * kLd, kLd, sK + tj * kLd, 16 * kLd, nc); -#pragma unroll - for (int r = 0; r < 4; ++r) -#pragma unroll - for (int c = 0; c < 4; ++c) { - const int i = ti * 4 + r, j = tj + 16 * c; - sS[i * kTLd + j] = static_cast(j <= i ? acc[r][c] * __expf(sGc[i] - sGc[j]) : 0.f); - } - } - lds_sync(); - - for (int half = 0; half < 2; ++half) { - // the start state over the keys (reusing the key tile) and the new values by token, then the next half's - th.store(sK); -#pragma unroll - for (int j = 0; j < 2; ++j) { - const int idx = tid + j * kThreads; - *reinterpret_cast(&sVT[(idx >> 3) * kTLd + 8 * (idx & 7)]) = pv[j]; - } - if (half == 0) fetch_half(1); - lds_sync(); - - float inter[4][4] = {}; - float intra[4][4] = {}; - tile_acc<4>(inter, sQ + ti * 4 * kLd, kLd, sK + tj * kLd, 16 * kLd, 0, kD / 8, 1); - tile_acc<4>(intra, sS + ti * 4 * kTLd, kTLd, sVT + tj * kTLd, 16 * kTLd, 0, ti / 2 + 1, 1); -#pragma unroll - for (int r = 0; r < 4; ++r) { - const int t = ti * 4 + r; - if (t >= n) continue; - const float e = __expf(sGc[t]); - float* row = y + (static_cast(t0 + t) * value_heads + head) * kD + half * 64 + tj; -#pragma unroll - for (int c = 0; c < 4; ++c) row[16 * c] = e * inter[r][c] + intra[r][c]; - } - if (half == 0) lds_sync(); - } -} diff --git a/zig/src/hip/kernel_tests/gdn.zig b/zig/src/hip/kernel_tests/gdn.zig index 0dd72ed0d27..fe6b8922da6 100644 --- a/zig/src/hip/kernel_tests/gdn.zig +++ b/zig/src/hip/kernel_tests/gdn.zig @@ -1,8 +1,9 @@ -//! The DeltaNet recurrence, token-serial and chunked, against a float64 recurrence on random inputs. +//! 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 }; @@ -105,7 +106,15 @@ fn relative(got: []const f32, want: []const f64) f64 { return max / scale; } -test "the serial and chunked DeltaNet stay within 5e-3 of the float64 recurrence at four lengths" { +/// 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{ @@ -135,19 +144,54 @@ test "the serial and chunked DeltaNet stay within 5e-3 of the float64 recurrence defer y.free(); var state = try t.upload(in.state); defer state.free(); - // `off` runs the token-serial kernel, `on` the chunked one for these lengths - for ([_]*const @import("../launches.zig").Launcher{ &t.off, &t.on }) |l| { - try state.upload(0, std.mem.sliceAsBytes(in.state)); - try y.fill8(0); - t.arena.reset(); - try t.ops(l).gatedDelta(rig.at(q), rig.at(k), rig.at(v), rig.at(gate), rig.at(beta), rig.at(state), rig.at(y), sh.length, sh.key_heads, sh.value_heads, d, d, null); - 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); - } + 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/rig.zig b/zig/src/hip/kernel_tests/rig.zig index 6afc5c6afd3..e011a1ba5f2 100644 --- a/zig/src/hip/kernel_tests/rig.zig +++ b/zig/src/hip/kernel_tests/rig.zig @@ -45,7 +45,7 @@ pub const Rig = struct { stream: Stream, /// Every kernel choice on, as a run takes them. on: Launcher, - /// Merged decode launches and the chunked DeltaNet off: the kernels they replace. + /// 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. @@ -62,7 +62,7 @@ pub const Rig = struct { 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, .chunked = false }, kernels.images); + 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; diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig index 513a88c1f5f..3323ec9e3b8 100644 --- a/zig/src/hip/kernels.zig +++ b/zig/src/hip/kernels.zig @@ -2,7 +2,7 @@ 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, gdn_prefill, decode, plan }; +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. diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index dcf6426df65..1df41fc0093 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -41,8 +41,6 @@ pub const PlanArgs = plan.PlanArgs; pub const PlanRef = plan.PlanRef; pub const PlanKeep = plan.Keep; pub const gdn_chunk = recurrence.gdn_chunk; -pub const GdnScratch = recurrence.GdnScratch; -pub const gdnScratch = recurrence.gdnScratch; pub const Launcher = struct { r: *const runtime.Runtime, @@ -64,7 +62,6 @@ pub const Launcher = struct { 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 - gdn_chunked: [5]Function, // prep, kt, wy, h, o softmax_stats: Function, sum_partials: Function, op: Ops, @@ -76,8 +73,6 @@ pub const Launcher = struct { fuse: bool, /// The 64-row prefill attention tile is on. wide: bool, - /// The DeltaNet prefill runs chunked (off keeps the one-token recurrence). - chunked: bool, const PlanFns = struct { kv_write: Function, @@ -126,7 +121,7 @@ pub const Launcher = struct { }; /// 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, chunked: bool = true }; + 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 { @@ -147,7 +142,6 @@ pub const Launcher = struct { const pl = l.mods[@backingInt(kernels.Group.plan)]; l.fuse = choices.fuse; l.wide = choices.wide; - l.chunked = choices.chunked; 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"), @@ -162,8 +156,6 @@ pub const Launcher = struct { }; 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") }; - const gp = l.mods[@backingInt(kernels.Group.gdn_prefill)]; - l.gdn_chunked = .{ try gp.function("tf_gdn_prep"), try gp.function("tf_gdn_kt"), try gp.function("tf_gdn_wy"), try gp.function("tf_gdn_h"), try gp.function("tf_gdn_o") }; l.op = .{ .embed_rows = try ops.function("tf_embed_rows"), .embed_dense = try ops.function("tf_embed_dense"), @@ -289,7 +281,6 @@ pub const Launcher = struct { pub const pagesWrite = plan.pagesWrite; pub const pagesGather = plan.pagesGather; pub const planGather = plan.planGather; - pub const gdnChunked = recurrence.gdnChunked; 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; diff --git a/zig/src/hip/launches/recurrence.zig b/zig/src/hip/launches/recurrence.zig index 86e5369a16d..a654d56a2bb 100644 --- a/zig/src/hip/launches/recurrence.zig +++ b/zig/src/hip/launches/recurrence.zig @@ -1,6 +1,5 @@ -//! DeltaNet launches: gate, serial and chunked recurrence, and the gated norm. +//! DeltaNet launches: gate, recurrence and the gated norm. -const std = @import("std"); const Launcher = @import("../launches.zig").Launcher; const util = @import("util.zig"); const S = util.S; @@ -16,22 +15,6 @@ const cdiv = util.cdiv; const tri = util.tri; const invalid = util.invalid; -/// The chunked DeltaNet's chunk, in rows. -pub const gdn_chunk = 64; - -/// Byte sizes of the chunked DeltaNet's scratch, rows padded to whole chunks. -pub const GdnScratch = struct { qk: usize, gc: usize, wu: usize, h: usize, total: usize }; - -pub fn gdnScratch(length: usize, key_heads: usize, value_heads: usize) GdnScratch { - const chunks = cdiv(length, gdn_chunk); - const rows = chunks * gdn_chunk; - const qk = std.mem.alignForward(usize, rows * key_heads * 128 * 2, 256); - const gc = std.mem.alignForward(usize, length * value_heads * 4, 256); - const wu = std.mem.alignForward(usize, rows * value_heads * 128 * 2, 256); - const h = chunks * value_heads * 128 * 128 * 2; - return .{ .qk = qk, .gc = gc, .wu = wu, .h = h, .total = 3 * qk + gc + 4 * wu + h }; -} - 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)); @@ -71,77 +54,6 @@ pub fn tf_gated_delta(l: *const Launcher, q: CF, k: CF, v: CF, gate: CF, beta: C } } -/// The chunked DeltaNet prefill of `length` rows (dk = dv = 128, batch 1), `scratch` of `gdnScratch` bytes. -pub fn gdnChunked(l: *const Launcher, q: CF, k: CF, v: CF, gate: CF, beta: CF, state: F, y: F, length: usize, key_heads: usize, value_heads: usize, scratch: u64, s: S) Error!void { - if (length < 1 or key_heads < 1 or @rem(value_heads, key_heads) != 0) return invalid("gdn chunked"); - const sc = gdnScratch(length, key_heads, value_heads); - const qh = scratch; - const kh = qh + sc.qk; - const kt = kh + sc.qk; - const vh = kt + sc.qk; - const gc = vh + sc.wu; - const w = gc + sc.gc; - const u = w + sc.wu; - const vt = u + sc.wu; - const hb = vt + sc.wu; - const chunks = cdiv(length, gdn_chunk); - const len: c_int = @intCast(length); - const hk: c_int = @intCast(key_heads); - const hv: c_int = @intCast(value_heads); - var a: Args = .{}; - try a.add(ad(q)); - try a.add(ad(k)); - try a.add(ad(v)); - try a.add(qh); - try a.add(kh); - try a.add(vh); - try a.add(len); - try a.add(hk); - try a.add(hv); - try l.go(l.gdn_chunked[0], dim(cdiv(length * (key_heads + value_heads) * 32, 256), 1, 1), dim(256, 1, 1), 0, s, &a); - var t: Args = .{}; - try t.add(kh); - try t.add(kt); - try t.add(len); - try t.add(hk); - try l.go(l.gdn_chunked[1], dim(chunks, key_heads, 1), dim(256, 1, 1), 0, s, &t); - var b: Args = .{}; - try b.add(kh); - try b.add(vh); - try b.add(ad(beta)); - try b.add(ad(gate)); - try b.add(gc); - try b.add(w); - try b.add(u); - try b.add(len); - try b.add(hk); - try b.add(hv); - try l.go(l.gdn_chunked[2], dim(chunks, value_heads, 1), dim(256, 1, 1), 0, s, &b); - var c: Args = .{}; - try c.add(kt); - try c.add(w); - try c.add(u); - try c.add(vt); - try c.add(gc); - try c.add(ad(state)); - try c.add(hb); - try c.add(len); - try c.add(hk); - try c.add(hv); - try l.go(l.gdn_chunked[3], dim(8, value_heads, 1), dim(256, 1, 1), 0, s, &c); - var d: Args = .{}; - try d.add(qh); - try d.add(kh); - try d.add(vt); - try d.add(hb); - try d.add(gc); - try d.add(ad(y)); - try d.add(len); - try d.add(hk); - try d.add(hv); - try l.go(l.gdn_chunked[4], dim(chunks, value_heads, 1), dim(256, 1, 1), 0, s, &d); -} - 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)); diff --git a/zig/src/hip/ops/ops.zig b/zig/src/hip/ops/ops.zig index da9dbedb110..beada05c68c 100644 --- a/zig/src/hip/ops/ops.zig +++ b/zig/src/hip/ops/ops.zig @@ -22,7 +22,7 @@ pub const Ops = struct { bf16: bool, stream: abi.Stream, arena: *Arena, - /// A prompt's span: products, router and recurrence take prefill's kernel, so rows have the same bits however cut. + /// 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, diff --git a/zig/src/hip/ops/recurrence.zig b/zig/src/hip/ops/recurrence.zig index 5971aafb59e..cf2b5f8be57 100644 --- a/zig/src/hip/ops/recurrence.zig +++ b/zig/src/hip/ops/recurrence.zig @@ -1,7 +1,6 @@ //! The linear attention: the conv, the gates and the DeltaNet recurrence. const t = @import("types.zig"); -const launches = @import("../launches.zig"); const Ops = @import("ops.zig").Ops; const Error = t.Error; const Tensor = t.Tensor; @@ -9,10 +8,6 @@ const p = t.p; const f = t.f; const int = t.int; -/// Rows from which the DeltaNet prefill runs chunked, and the rows of one chunked segment (a multiple of the chunk). -const gdn_min_rows = 64; -const gdn_segment = 4096; - 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); @@ -35,25 +30,7 @@ pub fn gdnGate(o: Ops, a: Tensor, b: Tensor, a_log: u64, dt_bias: u64, gate: u64 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 chunked recurrence in segments of `gdn_segment` rows, whose scratch the arena hands back after each. -fn gatedDeltaChunked(o: Ops, z: *const launches.Launcher, q: u64, k: u64, v: u64, gate: u64, beta: u64, state: u64, y: u64, length: usize, key_heads: usize, value_heads: usize) Error!void { - var start: usize = 0; - while (start < length) : (start += gdn_segment) { - const rows = @min(gdn_segment, length - start); - const mark = o.arena.mark(); - defer o.arena.release(mark); - const scratch = try o.arena.take(launches.gdnScratch(rows, key_heads, value_heads).total); - const qk = start * key_heads * 128 * 4; - const vy = start * value_heads * 128 * 4; - const gb = start * value_heads * 4; - try z.gdnChunked(f(q + qk), f(k + qk), f(v + vy), f(gate + gb), f(beta + gb), f(state), f(y + vy), rows, key_heads, value_heads, scratch, o.stream); - } -} - -/// The DeltaNet recurrence, state in place; a prefill of `gdn_min_rows` rows or more runs chunked unless reference. +/// 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 { - if (states == null and (length >= gdn_min_rows or o.prefill) and dk == 128 and dv == 128 and value_heads % key_heads == 0) { - if (o.l.chunked) return gatedDeltaChunked(o, o.l, q, k, v, gate, beta, state, y, length, key_heads, value_heads); - } 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); } From 1bdd859a717a63cf8b6a841d043b7ed10976617b Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:46:37 +0200 Subject: [PATCH 49/52] refactor(hip): the policy's gdn switch goes with the chunked recurrence it turned off --- zig/src/hip/policy.zig | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index f040d6109d1..3715e208931 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -34,11 +34,10 @@ pub const Policy = struct { attention: Attention = .auto, kernels: Pick = .auto, graphs: Choice = .auto, - /// Reference kernels one at a time: decode stream tile, prefill GEMM tile, fused decode tails, chunked recurrence. + /// Reference kernels one at a time: decode stream tile, prefill GEMM tile, fused decode tails. stream: Pick = .auto, gemm: Pick = .auto, fuse: Pick = .auto, - gdn: Pick = .auto, prefill_step: u32 = 1024, /// Prompt rows a chunk while other streams decode: a multiple of 64 dividing 1024 (the idle chunk). fill_rows: u32 = 512, @@ -68,11 +67,6 @@ pub const Policy = struct { return p.kernels != .reference and p.fuse != .reference; } - /// Whether the DeltaNet prefill runs chunked. - pub fn chunked(p: *const Policy) bool { - return p.kernels != .reference and p.gdn != .reference; - } - /// What the kernel launches choose under this policy. pub fn choices(p: *const Policy) Launcher.Choices { const matrix: affine.Matrix = switch (p.matrix) { @@ -80,7 +74,7 @@ pub const Policy = struct { .on => .on, .off => .off, }; - return .{ .fuse = p.fused(), .wide = p.wideAttention(), .chunked = p.chunked(), .products = .{ .matrix = matrix, .stream = p.streamOn(), .gemm = p.gemmOn() } }; + return .{ .fuse = p.fused(), .wide = p.wideAttention(), .products = .{ .matrix = matrix, .stream = p.streamOn(), .gemm = p.gemmOn() } }; } /// Whether the 64-row prefill attention tile is on. @@ -108,7 +102,7 @@ pub const Policy = struct { fn set(p: *Policy, key: []const u8, value: []const u8) Error!void { const eql = std.mem.eql; - if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "gdn")) p.gdn = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { + if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { p.prefill_step = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; } else if (eql(u8, key, "fill_rows")) { p.fill_rows = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; @@ -127,7 +121,6 @@ pub const Policy = struct { if (p.stream != .auto) try w.print(",stream={t}", .{p.stream}); if (p.gemm != .auto) try w.print(",gemm={t}", .{p.gemm}); if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); - if (p.gdn != .auto) try w.print(",gdn={t}", .{p.gdn}); if (p.graph_fail >= 0) try w.print(",graph_fail={d}", .{p.graph_fail}); if (p.rccl_lib.slice()) |path| try w.print(",rccl_lib={s}", .{path}); try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); @@ -140,7 +133,7 @@ pub const Policy = struct { const conf: u64 = @bitCast(p.mtp.confidence); const pack = [_]u32{ @backingInt(p.matrix), @backingInt(p.attention), @backingInt(p.kernels), @backingInt(p.graphs), - @backingInt(p.stream), @backingInt(p.gemm), @backingInt(p.fuse), @backingInt(p.gdn), + @backingInt(p.stream), @backingInt(p.gemm), @backingInt(p.fuse), }; var nibbles: [2]u32 = .{ 0, 0 }; for (pack, 0..) |v, i| nibbles[i / 8] |= v << @intCast(4 * (i % 8)); @@ -150,7 +143,7 @@ pub const Policy = struct { /// `local` with every field rank 0 sent; a rank keeps its own graph fault and library path. pub fn fromWords(w: [word_count]u32, local: Policy) Policy { var p = local; - var vals: [8]u32 = undefined; + var vals: [7]u32 = undefined; for (&vals, 0..) |*v, i| v.* = (w[i / 8] >> @intCast(4 * (i % 8))) & 0xf; p.matrix = @fromBackingInt(@intCast(vals[0])); p.attention = @fromBackingInt(@intCast(vals[1])); @@ -159,7 +152,6 @@ pub const Policy = struct { p.stream = @fromBackingInt(@intCast(vals[4])); p.gemm = @fromBackingInt(@intCast(vals[5])); p.fuse = @fromBackingInt(@intCast(vals[6])); - p.gdn = @fromBackingInt(@intCast(vals[7])); p.mtp = .{ .drafts = @truncate(w[1] >> 24), .confidence = @bitCast(@as(u64, w[3]) | @as(u64, w[4]) << 32) }; p.prefill_step = w[2]; p.slots = w[5]; @@ -228,7 +220,7 @@ test "apply sets fields and refuses what it does not know" { test "a policy survives its words" { var p: Policy = .{ .mtp = .{ .drafts = 2, .confidence = 0.25 }, .slots = 4, .graph_fail = 1 }; - try p.apply("matrix=on,attention=f32,graphs=off,gdn=reference,fill_rows=128"); + try p.apply("matrix=on,attention=f32,graphs=off,fuse=reference,fill_rows=128"); const back = Policy.fromWords(p.words(), .{ .graph_fail = 1 }); try std.testing.expectEqualDeep(p, back); } @@ -238,12 +230,12 @@ test "TF_POLICY speaks after the flags, and the reference switches" { const env: Policy.Env = .{ .vars = &.{.{ "TF_POLICY", "matrix=on,stream=reference,attention=f32,graphs=off" }} }; const p = try Policy.resolve("matrix=off", env, ¬es); try std.testing.expectEqual(Choice.on, p.matrix); - try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and p.chunked() and !p.wideAttention()); + try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and !p.wideAttention()); try std.testing.expect(!p.graphsOn()); try std.testing.expect(std.mem.indexOf(u8, notes.text(), "TF_POLICY=") != null); var reference: Policy = .{}; try reference.apply("kernels=reference"); - try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused() and !reference.chunked()); + try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused()); } test "graphs are on at any world size unless the policy turns them off" { From edc5b3fec4dae46a63e0951429fcdad254de2458 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:46:37 +0200 Subject: [PATCH 50/52] refactor(hip): the policy's gdn switch goes with the chunked recurrence it turned off --- zig/src/hip/policy.zig | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/zig/src/hip/policy.zig b/zig/src/hip/policy.zig index 30c9a2c1835..38d76560516 100644 --- a/zig/src/hip/policy.zig +++ b/zig/src/hip/policy.zig @@ -18,11 +18,10 @@ pub const Policy = struct { attention: Attention = .auto, kernels: Pick = .auto, graphs: Choice = .auto, - /// Reference kernels one at a time: decode stream tile, prefill GEMM tile, fused decode tails, chunked recurrence. + /// Reference kernels one at a time: decode stream tile, prefill GEMM tile, fused decode tails. stream: Pick = .auto, gemm: Pick = .auto, fuse: Pick = .auto, - gdn: Pick = .auto, prefill_step: u32 = 1024, /// Prompt rows a chunk while other streams decode: a multiple of 64 dividing 1024 (the idle chunk). fill_rows: u32 = 512, @@ -50,11 +49,6 @@ pub const Policy = struct { return p.kernels != .reference and p.fuse != .reference; } - /// Whether the DeltaNet prefill runs chunked. - pub fn chunked(p: *const Policy) bool { - return p.kernels != .reference and p.gdn != .reference; - } - /// What the kernel launches choose under this policy. pub fn choices(p: *const Policy) Launcher.Choices { const matrix: affine.Matrix = switch (p.matrix) { @@ -62,7 +56,7 @@ pub const Policy = struct { .on => .on, .off => .off, }; - return .{ .fuse = p.fused(), .wide = p.wideAttention(), .chunked = p.chunked(), .products = .{ .matrix = matrix, .stream = p.streamOn(), .gemm = p.gemmOn() } }; + return .{ .fuse = p.fused(), .wide = p.wideAttention(), .products = .{ .matrix = matrix, .stream = p.streamOn(), .gemm = p.gemmOn() } }; } /// Whether the 64-row prefill attention tile is on. @@ -94,7 +88,7 @@ pub const Policy = struct { fn set(p: *Policy, key: []const u8, value: []const u8) Error!void { const eql = std.mem.eql; - if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "gdn")) p.gdn = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { + if (eql(u8, key, "matrix")) p.matrix = try parseEnum(Choice, value) else if (eql(u8, key, "attention")) p.attention = try parseEnum(Attention, value) else if (eql(u8, key, "kernels")) p.kernels = try parseEnum(Pick, value) else if (eql(u8, key, "graphs")) p.graphs = try parseEnum(Choice, value) else if (eql(u8, key, "stream")) p.stream = try parseEnum(Pick, value) else if (eql(u8, key, "gemm")) p.gemm = try parseEnum(Pick, value) else if (eql(u8, key, "fuse")) p.fuse = try parseEnum(Pick, value) else if (eql(u8, key, "prefill_step")) { p.prefill_step = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; } else if (eql(u8, key, "fill_rows")) { p.fill_rows = std.fmt.parseInt(u32, value, 10) catch return error.BadValue; @@ -113,7 +107,6 @@ pub const Policy = struct { if (p.stream != .auto) try w.print(",stream={t}", .{p.stream}); if (p.gemm != .auto) try w.print(",gemm={t}", .{p.gemm}); if (p.fuse != .auto) try w.print(",fuse={t}", .{p.fuse}); - if (p.gdn != .auto) try w.print(",gdn={t}", .{p.gdn}); if (p.graph_fail >= 0) try w.print(",graph_fail={d}", .{p.graph_fail}); try w.print("; mtp drafts {d} under {d}, {d} snapshots", .{ p.mtp.drafts, p.mtp.confidence, p.slots }); } @@ -125,7 +118,7 @@ pub const Policy = struct { const conf: u64 = @bitCast(p.mtp.confidence); const pack = [_]u32{ @backingInt(p.matrix), @backingInt(p.attention), @backingInt(p.kernels), @backingInt(p.graphs), - @backingInt(p.stream), @backingInt(p.gemm), @backingInt(p.fuse), @backingInt(p.gdn), + @backingInt(p.stream), @backingInt(p.gemm), @backingInt(p.fuse), }; var nibbles: [2]u32 = .{ 0, 0 }; for (pack, 0..) |v, i| nibbles[i / 8] |= v << @intCast(4 * (i % 8)); @@ -135,7 +128,7 @@ pub const Policy = struct { /// `local` with every field rank 0 sent; a rank keeps its own graph fault. pub fn fromWords(w: [word_count]u32, local: Policy) Policy { var p = local; - var vals: [8]u32 = undefined; + var vals: [7]u32 = undefined; for (&vals, 0..) |*v, i| v.* = (w[i / 8] >> @intCast(4 * (i % 8))) & 0xf; p.matrix = @fromBackingInt(@intCast(vals[0])); p.attention = @fromBackingInt(@intCast(vals[1])); @@ -144,7 +137,6 @@ pub const Policy = struct { p.stream = @fromBackingInt(@intCast(vals[4])); p.gemm = @fromBackingInt(@intCast(vals[5])); p.fuse = @fromBackingInt(@intCast(vals[6])); - p.gdn = @fromBackingInt(@intCast(vals[7])); p.mtp = .{ .drafts = @truncate(w[1] >> 24), .confidence = @bitCast(@as(u64, w[3]) | @as(u64, w[4]) << 32) }; p.prefill_step = w[2]; p.slots = w[5]; @@ -213,7 +205,7 @@ test "apply sets fields and refuses what it does not know" { test "a policy survives its words" { var p: Policy = .{ .mtp = .{ .drafts = 2, .confidence = 0.25 }, .slots = 4, .graph_fail = 1 }; - try p.apply("matrix=on,attention=f32,graphs=off,gdn=reference,fill_rows=128"); + try p.apply("matrix=on,attention=f32,graphs=off,fuse=reference,fill_rows=128"); const back = Policy.fromWords(p.words(), .{ .graph_fail = 1 }); try std.testing.expectEqualDeep(p, back); } @@ -223,12 +215,12 @@ test "TF_POLICY speaks after the flags, and the reference switches" { const env: Policy.Env = .{ .vars = &.{.{ "TF_POLICY", "matrix=on,stream=reference,attention=f32,graphs=off" }} }; const p = try Policy.resolve("matrix=off", env, ¬es); try std.testing.expectEqual(Choice.on, p.matrix); - try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and p.chunked() and !p.wideAttention()); + try std.testing.expect(!p.streamOn() and p.gemmOn() and p.fused() and !p.wideAttention()); try std.testing.expect(!p.graphsOn(1) and !p.graphsOn(2)); try std.testing.expect(std.mem.indexOf(u8, notes.text(), "TF_POLICY=") != null); var reference: Policy = .{}; try reference.apply("kernels=reference"); - try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused() and !reference.chunked()); + try std.testing.expect(!reference.streamOn() and !reference.gemmOn() and !reference.fused()); } test "graphs follow the group unless the policy says" { From a5f8646964332f2a56407f42adbba1b0fdc7f500 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:16:33 +0200 Subject: [PATCH 51/52] refactor(flashnext): config.zig and index.zig import no core; widths.quantization looks a module's width up 1.0.11's widths reached core/quant from config.zig and index.zig, which the HIP module imports with core as a module: the HIP build stopped at an import outside its module path. Config.quantization becomes widths.quantization(config, path): the reader's table when Config.widths (now an opaque pointer) is set, else Config.declared(path, canonical), the config's own entries under the key spelling passed in. index.zig's walk takes the table's type as a parameter (void when only names are checked), with its own Width for the refusal. --- zig/src/families/flashnext/config.zig | 16 +-- zig/src/families/flashnext/host_test.zig | 10 +- zig/src/families/flashnext/index.zig | 162 ++++++++++++----------- zig/src/families/flashnext/pack.zig | 7 +- zig/src/families/flashnext/weights.zig | 3 +- zig/src/families/flashnext/widths.zig | 15 +++ 6 files changed, 117 insertions(+), 96 deletions(-) diff --git a/zig/src/families/flashnext/config.zig b/zig/src/families/flashnext/config.zig index 0f4cf471339..da6a4b47a9a 100644 --- a/zig/src/families/flashnext/config.zig +++ b/zig/src/families/flashnext/config.zig @@ -1,7 +1,6 @@ //! FlashNext text dimensions and quantization declarations are checked before weight or cache allocation. const std = @import("std"); const affine = @import("spec.zig"); -const keys = @import("../../core/quant/keys.zig"); pub const Kind = enum { linear_attention, sparse_attention }; pub const Gate = enum { sigmoid, silu }; @@ -55,8 +54,8 @@ pub const Config = struct { eos: [16]u32 = @splat(0), eos_count: usize = 0, global_affine: affine.Spec, - /// Set by a tensor reader: each lookup then goes through core/quant, which fills in no missing bits or group. - widths: ?*const @import("widths.zig").Widths = null, + /// A widths.Widths set by a tensor reader; widths.quantization reads it, so this file imports no core. + widths: ?*const anyopaque = null, pub fn deinit(c: *Config) void { c.parsed.deinit(); @@ -96,17 +95,14 @@ pub const Config = struct { return c.kinds[i]; } - pub fn quantization(c: *const Config, path: []const u8) !?affine.Spec { - if (c.widths) |w| { - const width = (try w.of(path)) orelse return null; - return try affine.Spec.init(width.bits, width.group); - } - const wanted = keys.canonical(path); + /// The config's own width for `path`, keys spelled by `canonical` (core/quant/keys.zig): this file imports no core. + pub fn declared(c: *const Config, path: []const u8, canonical: *const fn ([]const u8) []const u8) !?affine.Spec { + const wanted = canonical(path); var found = false; var answer: ?affine.Spec = c.global_affine; var it = c.quant.iterator(); while (it.next()) |item| { - if (!std.mem.eql(u8, keys.canonical(item.key_ptr.*), wanted)) continue; + if (!std.mem.eql(u8, canonical(item.key_ptr.*), wanted)) continue; const candidate: ?affine.Spec = switch (item.value_ptr.*) { .bool => |enabled| if (enabled) c.global_affine else null, .object => |value| if (value.count() == 0) null else try spec(value, 4), diff --git a/zig/src/families/flashnext/host_test.zig b/zig/src/families/flashnext/host_test.zig index bc198ce4ad2..562f2dc9051 100644 --- a/zig/src/families/flashnext/host_test.zig +++ b/zig/src/families/flashnext/host_test.zig @@ -113,13 +113,13 @@ test "FlashNext derived dimensions retain independent HC attention and recurrenc test "module quantization preserves false true and dictionary-default override semantics" { var c = try family.config.parse(std.testing.allocator, toy); defer c.deinit(); - try std.testing.expect((try c.quantization("language_model.model.layers.0.raw.weight")) == null); - const override = (try c.quantization("model.layers.0.override")).?; + const widths = @import("widths.zig"); + try std.testing.expect((try widths.quantization(&c, "language_model.model.layers.0.raw.weight")) == null); + const override = (try widths.quantization(&c, "model.layers.0.override")).?; try std.testing.expectEqual(@as(u8, 4), override.bits); try std.testing.expectEqual(@as(usize, 64), override.group); - try std.testing.expectEqual(@as(u8, 6), (try c.quantization("layers.0.inherit")).?.bits); - try std.testing.expectEqual(@as(usize, 32), (try c.quantization("unknown.projection")).?.group); - const widths = @import("widths.zig"); + try std.testing.expectEqual(@as(u8, 6), (try widths.quantization(&c, "layers.0.inherit")).?.bits); + try std.testing.expectEqual(@as(usize, 32), (try widths.quantization(&c, "unknown.projection")).?.group); try std.testing.expect(widths.launched(.{ .bits = override.bits, .group = @intCast(override.group) })); try std.testing.expect(widths.launched(.{ .bits = c.global_affine.bits, .group = @intCast(c.global_affine.group) })); try std.testing.expect(!widths.launched(.{ .bits = 7, .group = 64 }) and !widths.launched(.{ .bits = 4, .group = 16 })); diff --git a/zig/src/families/flashnext/index.zig b/zig/src/families/flashnext/index.zig index 44c3c6d012c..bd963cf231b 100644 --- a/zig/src/families/flashnext/index.zig +++ b/zig/src/families/flashnext/index.zig @@ -1,103 +1,111 @@ //! Public index admission proves required tensor names and safe shard basenames before payload headers are available. const std = @import("std"); const Config = @import("config.zig").Config; -const widths = @import("widths.zig"); + +/// A declared width, the fields of core/quant's mlx.Width, so this file imports no core. +pub const Width = struct { bits: u8, group: u16 }; /// The first required matrix the device kernels cannot read yet, by tensor stem, with its declared width. pub const Refusal = struct { buf: [256]u8 = undefined, len: usize = 0, - width: ?widths.Width = null, + width: ?Width = null, pub fn name(r: *const Refusal) []const u8 { return r.buf[0..r.len]; } - fn set(r: *Refusal, stem: []const u8, width: ?widths.Width) void { + fn set(r: *Refusal, stem: []const u8, width: anytype) void { r.len = @min(stem.len, r.buf.len); @memcpy(r.buf[0..r.len], stem[0..r.len]); - r.width = width; + r.width = if (width) |w| .{ .bits = w.bits, .group = w.group } else null; } }; -const Check = struct { - map: std.json.ObjectMap, - names: usize = 0, - runtime: ?*const widths.Widths = null, - refusal: ?*Refusal = null, - - fn take(c: *Check, name: []const u8) !void { - if (c.map.get(name) == null) return error.MissingFlashTensor; - c.names += 1; - } +/// The index walk; `Runtime` is widths.Widths when each matrix's width is checked, void when only names are. +fn Check(comptime Runtime: type) type { + return struct { + const C = @This(); + map: std.json.ObjectMap, + names: usize = 0, + runtime: ?*const Runtime = null, + refusal: ?*Refusal = null, + + fn take(c: *C, name: []const u8) !void { + if (c.map.get(name) == null) return error.MissingFlashTensor; + c.names += 1; + } - fn part(c: *Check, stem: []const u8, suffix: []const u8) !void { - var buf: [256]u8 = undefined; - try c.take(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ stem, suffix })); - } + fn part(c: *C, stem: []const u8, suffix: []const u8) !void { + var buf: [256]u8 = undefined; + try c.take(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ stem, suffix })); + } - fn matrix(c: *Check, stem: []const u8) !void { - try c.part(stem, "weight"); - var buf: [256]u8 = undefined; - const scales = c.map.get(try std.fmt.bufPrint(&buf, "{s}.scales", .{stem})) != null; - const biases = c.map.get(try std.fmt.bufPrint(&buf, "{s}.biases", .{stem})) != null; - if (scales != biases) return error.IncompleteFlashAffine; - if (scales) { - if (c.runtime) |w| { - const width = try w.of(stem); - if (width == null or !widths.launched(width.?)) { - if (c.refusal) |r| r.set(stem, width); - return error.UnsupportedFlashAffineKernel; - } + fn matrix(c: *C, stem: []const u8) !void { + try c.part(stem, "weight"); + var buf: [256]u8 = undefined; + const scales = c.map.get(try std.fmt.bufPrint(&buf, "{s}.scales", .{stem})) != null; + const biases = c.map.get(try std.fmt.bufPrint(&buf, "{s}.biases", .{stem})) != null; + if (scales != biases) return error.IncompleteFlashAffine; + if (scales) { + if (Runtime != void) if (c.runtime) |w| { + const width = try w.of(stem); + if (width == null or !w.reads(width.?)) { + if (c.refusal) |r| r.set(stem, width); + return error.UnsupportedFlashAffineKernel; + } + }; + try c.part(stem, "scales"); + try c.part(stem, "biases"); } - try c.part(stem, "scales"); - try c.part(stem, "biases"); } - } - fn proj(c: *Check, stem: []const u8, suffix: []const u8) !void { - var buf: [256]u8 = undefined; - try c.matrix(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ stem, suffix })); - } + fn proj(c: *C, stem: []const u8, suffix: []const u8) !void { + var buf: [256]u8 = undefined; + try c.matrix(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ stem, suffix })); + } - fn hc(c: *Check, stem: []const u8, inject: bool) !void { - try c.part(stem, "hc_norm.weight"); - for ([_][]const u8{ "input_mix_weight_down", "input_mix_weight_up" }) |suffix| try c.proj(stem, suffix); - if (inject) try c.proj(stem, "block_inject_weight"); - } + fn hc(c: *C, stem: []const u8, inject: bool) !void { + try c.part(stem, "hc_norm.weight"); + for ([_][]const u8{ "input_mix_weight_down", "input_mix_weight_up" }) |suffix| try c.proj(stem, suffix); + if (inject) try c.proj(stem, "block_inject_weight"); + } - fn layer(c: *Check, stem: []const u8, kind: @import("config.zig").Kind) !void { - var buf: [256]u8 = undefined; - for ([_][]const u8{ "attn_hyper_connection", "mlp_hyper_connection" }) |suffix| try c.hc(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ stem, suffix }), true); - for ([_][]const u8{ "mlp.gate", "mlp.shared_expert_gate", "mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.shared_expert.down_proj", "mlp.switch_mlp.gate_proj", "mlp.switch_mlp.up_proj", "mlp.switch_mlp.down_proj" }) |suffix| try c.proj(stem, suffix); - if (kind == .linear_attention) { - for ([_][]const u8{ "linear_attn.in_proj_qkv", "linear_attn.in_proj_z", "linear_attn.in_proj_b", "linear_attn.in_proj_a", "linear_attn.out_proj" }) |suffix| try c.proj(stem, suffix); - for ([_][]const u8{ "linear_attn.A_log", "linear_attn.dt_bias", "linear_attn.conv1d.weight", "linear_attn.norm.weight" }) |suffix| try c.part(stem, suffix); - } else { - for ([_][]const u8{ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "self_attn.indexer.index_qk_proj" }) |suffix| try c.proj(stem, suffix); - for ([_][]const u8{ "self_attn.q_norm.weight", "self_attn.k_norm.weight", "self_attn.indexer.q_layernorm.weight", "self_attn.indexer.k_layernorm.weight" }) |suffix| try c.part(stem, suffix); + fn layer(c: *C, stem: []const u8, kind: @import("config.zig").Kind) !void { + var buf: [256]u8 = undefined; + for ([_][]const u8{ "attn_hyper_connection", "mlp_hyper_connection" }) |suffix| try c.hc(try std.fmt.bufPrint(&buf, "{s}.{s}", .{ stem, suffix }), true); + for ([_][]const u8{ "mlp.gate", "mlp.shared_expert_gate", "mlp.shared_expert.gate_proj", "mlp.shared_expert.up_proj", "mlp.shared_expert.down_proj", "mlp.switch_mlp.gate_proj", "mlp.switch_mlp.up_proj", "mlp.switch_mlp.down_proj" }) |suffix| try c.proj(stem, suffix); + if (kind == .linear_attention) { + for ([_][]const u8{ "linear_attn.in_proj_qkv", "linear_attn.in_proj_z", "linear_attn.in_proj_b", "linear_attn.in_proj_a", "linear_attn.out_proj" }) |suffix| try c.proj(stem, suffix); + for ([_][]const u8{ "linear_attn.A_log", "linear_attn.dt_bias", "linear_attn.conv1d.weight", "linear_attn.norm.weight" }) |suffix| try c.part(stem, suffix); + } else { + for ([_][]const u8{ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "self_attn.indexer.index_qk_proj" }) |suffix| try c.proj(stem, suffix); + for ([_][]const u8{ "self_attn.q_norm.weight", "self_attn.k_norm.weight", "self_attn.indexer.q_layernorm.weight", "self_attn.indexer.k_layernorm.weight" }) |suffix| try c.part(stem, suffix); + } } - } - /// An n-gram table shard: one lookup reads a row of `row` values a group at a time, so its group divides the row. - fn table(c: *Check, stem: []const u8, row: usize) !void { - try c.matrix(stem); - const w = c.runtime orelse return; - const width = (try w.of(stem)) orelse return; - if (row % width.group == 0) return; - if (c.refusal) |r| r.set(stem, width); - return error.UnsupportedFlashAffineKernel; - } + /// An n-gram table shard: a lookup reads a row of `row` values a group at a time, so its group divides the row. + fn table(c: *C, stem: []const u8, row: usize) !void { + try c.matrix(stem); + if (Runtime == void) return; + const w = c.runtime orelse return; + const declared = try w.of(stem); + const width = declared orelse return; + if (row % width.group == 0) return; + if (c.refusal) |r| r.set(stem, declared); + return error.UnsupportedFlashAffineKernel; + } - fn ple(c: *Check, stem: []const u8, shards: usize, spelling: []const u8, row: usize) !void { - for ([_][]const u8{ "conv1d.weight", "norm_conv.weight", "norm_key.weight", "norm_query.weight", "ple_embedding.layer_multipliers", "ple_embedding.ngram_heads_offsets", "ple_embedding.ngram_heads_vocab_sizes" }) |suffix| try c.part(stem, suffix); - try c.proj(stem, "key_proj"); - try c.proj(stem, "value_proj"); - var buf: [256]u8 = undefined; - var name: [256]u8 = undefined; - for (0..shards) |i| try c.table(try std.fmt.bufPrint(&name, "{s}.{s}", .{ stem, try std.fmt.bufPrint(&buf, "ple_embedding.ngram_embedding.{s}{d}", .{ spelling, i }) }), row); - } -}; + fn ple(c: *C, stem: []const u8, shards: usize, spelling: []const u8, row: usize) !void { + for ([_][]const u8{ "conv1d.weight", "norm_conv.weight", "norm_key.weight", "norm_query.weight", "ple_embedding.layer_multipliers", "ple_embedding.ngram_heads_offsets", "ple_embedding.ngram_heads_vocab_sizes" }) |suffix| try c.part(stem, suffix); + try c.proj(stem, "key_proj"); + try c.proj(stem, "value_proj"); + var buf: [256]u8 = undefined; + var name: [256]u8 = undefined; + for (0..shards) |i| try c.table(try std.fmt.bufPrint(&name, "{s}.{s}", .{ stem, try std.fmt.bufPrint(&buf, "ple_embedding.ngram_embedding.{s}{d}", .{ spelling, i }) }), row); + } + }; +} /// Where the index keeps the MTP head: `language_model.mtp` (mlx-lm), else oMLX's top-level `mtp`. pub fn mtpRoot(map: std.json.ObjectMap) []const u8 { @@ -115,15 +123,15 @@ pub fn ngramSpelling(map: std.json.ObjectMap) []const u8 { pub const Inventory = struct { tensor_names: usize, required_names: usize, shards: usize, headers_verified: bool = false }; pub fn admit(gpa: std.mem.Allocator, bytes: []const u8, config: *const Config) !Inventory { - return admitWith(gpa, bytes, config, null, null); + return admitWith(void, gpa, bytes, config, null, null); } /// Each required matrix at its own module width, refused by name when no device kernel reads that width yet. -pub fn admitRuntime(gpa: std.mem.Allocator, bytes: []const u8, config: *const Config, w: *const widths.Widths, refusal: *Refusal) !Inventory { - return admitWith(gpa, bytes, config, w, refusal); +pub fn admitRuntime(gpa: std.mem.Allocator, bytes: []const u8, config: *const Config, w: anytype, refusal: *Refusal) !Inventory { + return admitWith(@TypeOf(w.*), gpa, bytes, config, w, refusal); } -fn admitWith(gpa: std.mem.Allocator, bytes: []const u8, config: *const Config, runtime: ?*const widths.Widths, refusal: ?*Refusal) !Inventory { +fn admitWith(comptime Runtime: type, gpa: std.mem.Allocator, bytes: []const u8, config: *const Config, runtime: ?*const Runtime, refusal: ?*Refusal) !Inventory { const p = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); defer p.deinit(); if (p.value != .object) return error.InvalidFlashIndex; @@ -137,7 +145,7 @@ fn admitWith(gpa: std.mem.Allocator, bytes: []const u8, config: *const Config, r if (file != .string or file.string.len == 0 or file.string[0] == '.' or std.mem.indexOfAny(u8, file.string, "/\\") != null or !std.mem.endsWith(u8, file.string, ".safetensors")) return error.UnsafeFlashShard; try files.put(gpa, file.string, {}); } - var c = Check{ .map = map.object, .runtime = runtime, .refusal = refusal }; + var c = Check(Runtime){ .map = map.object, .runtime = runtime, .refusal = refusal }; const spelling = ngramSpelling(map.object); // every shard is checked under this one, so an index mixing the two is refused try c.matrix("language_model.model.embed_tokens"); try c.matrix("language_model.lm_head"); diff --git a/zig/src/families/flashnext/pack.zig b/zig/src/families/flashnext/pack.zig index 2834475232d..7657ecd9b8d 100644 --- a/zig/src/families/flashnext/pack.zig +++ b/zig/src/families/flashnext/pack.zig @@ -5,6 +5,7 @@ const st = @import("../../core/safetensors.zig"); const ckpt = @import("../../core/checkpoint.zig"); const affine = @import("affine.zig"); const config_mod = @import("config.zig"); +const widths = @import("widths.zig"); const index_mod = @import("index.zig"); const pio = @import("pack_io.zig"); const quant_mlx = @import("../../core/quant/mlx.zig"); @@ -37,7 +38,7 @@ fn qlinear(ck: *ckpt.Checkpoint, cfg: *const config_mod.Config, path: []const u8 } fn qlinearAt(ck: *ckpt.Checkpoint, cfg: *const config_mod.Config, path: []const u8) !Q { - const spec = (try cfg.quantization(path)) orelse return error.NotQuantized; + const spec = (try widths.quantization(cfg, path)) orelse return error.NotQuantized; var buf: [320]u8 = undefined; const w = try ck.get(try std.fmt.bufPrint(&buf, "{s}.weight", .{path})); const s = try ck.get(try std.fmt.bufPrint(&buf, "{s}.scales", .{path})); @@ -149,7 +150,7 @@ fn denseRows(gpa: std.mem.Allocator, a: std.mem.Allocator, ck: *ckpt.Checkpoint, const w = try ck.get(try std.fmt.allocPrint(a, "{s}.weight", .{stem})); if (w.dtype == .bf16 and w.rank == 2) return .{ .bytes = w.bytes, .rows = w.dim(0), .cols = w.dim(1), .owned = false }; if (w.dtype != .u32 or w.rank != 2) return error.DenseRouterNotBf16; - const spec = (try cfg.quantization(stem)) orelse return error.DenseRouterNotBf16; + const spec = (try widths.quantization(cfg, stem)) orelse return error.DenseRouterNotBf16; const s = try ck.get(try std.fmt.allocPrint(a, "{s}.scales", .{stem})); const b = try ck.get(try std.fmt.allocPrint(a, "{s}.biases", .{stem})); const we = st.Entry{ .dtype = w.dtype, .rank = w.rank, .shape = w.shape, .begin = 0, .end = w.bytes.len }; @@ -344,7 +345,7 @@ pub fn build(gpa: std.mem.Allocator, io: Io, model_dir: []const u8, out_dir: []c const a = arena_state.allocator(); var cfg = try config_mod.Config.read(gpa, io, model_dir); defer cfg.deinit(); - var strict = try @import("widths.zig").Widths.init(gpa, &cfg); + var strict = try widths.Widths.init(gpa, &cfg); defer strict.deinit(); cfg.widths = &strict; // the vision tower's tensors stay unread: a rank-five entry must not stop the no-dump build diff --git a/zig/src/families/flashnext/weights.zig b/zig/src/families/flashnext/weights.zig index fd312d04784..b8ee3a561cc 100644 --- a/zig/src/families/flashnext/weights.zig +++ b/zig/src/families/flashnext/weights.zig @@ -4,6 +4,7 @@ const ckpt = @import("../../core/checkpoint.zig"); const st = @import("../../core/safetensors.zig"); const cfg = @import("config.zig"); const affine = @import("affine.zig"); +const widths = @import("widths.zig"); pub const Matrix = union(enum) { raw: ckpt.Tensor, @@ -43,7 +44,7 @@ pub const Reader = struct { if (weight.shape[rank - 2] != n or weight.shape[rank - 1] != k or (rank == 3 and weight.shape[0] != experts)) return error.InvalidFlashMatrix; return .{ .raw = weight }; } - const spec = (try r.config.quantization(path)) orelse return error.DisabledPackedProjection; + const spec = (try widths.quantization(r.config, path)) orelse return error.DisabledPackedProjection; const scales = try r.tensor(path, "scales"); const biases = try r.tensor(path, "biases"); const shape = try affine.matrix(entry(weight), entry(scales), entry(biases), spec); diff --git a/zig/src/families/flashnext/widths.zig b/zig/src/families/flashnext/widths.zig index d20cde622f1..55ec80fa66f 100644 --- a/zig/src/families/flashnext/widths.zig +++ b/zig/src/families/flashnext/widths.zig @@ -65,6 +65,11 @@ pub const Widths = struct { return try w.q.width(key); } + /// Whether a device kernel reads `width`, for index.zig's walk. + pub fn reads(_: *const Widths, width: Width) bool { + return launched(width); + } + /// The module's stored matrix checked against its own width, never one inferred from the shapes. pub fn shaped(w: *const Widths, path: []const u8, weight: st.Entry, scales: st.Entry, biases: st.Entry) !affine.Shape { const width = (try w.of(path)) orelse return error.UnquantizedAffineTensor; @@ -72,6 +77,16 @@ pub const Widths = struct { } }; +/// A module's width: the reader's table when `c.widths` is set, else the config's own entries under core's keys. +pub fn quantization(c: *const config.Config, path: []const u8) !?affine.Spec { + if (c.widths) |table| { + const w: *const Widths = @ptrCast(@alignCast(table)); + const width = (try w.of(path)) orelse return null; + return try affine.Spec.init(width.bits, width.group); + } + return c.declared(path, keys.canonical); +} + test { _ = @import("widths_test.zig"); } From 0652d0a873e9bfa4424c01294cce597ea2c2c56f Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:25:09 +0200 Subject: [PATCH 52/52] fix(flashnext): the HIP n-gram tables read a shard's declared width through Config.declared and core's keys --- zig/src/families/flashnext/hip/checkpoint_tables.zig | 3 ++- zig/src/families/flashnext/hip/tables.zig | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/zig/src/families/flashnext/hip/checkpoint_tables.zig b/zig/src/families/flashnext/hip/checkpoint_tables.zig index c6ec7c7f920..bc3a4ea77a4 100644 --- a/zig/src/families/flashnext/hip/checkpoint_tables.zig +++ b/zig/src/families/flashnext/hip/checkpoint_tables.zig @@ -1,5 +1,6 @@ //! The checkpoint as core/quant reads it for the HIP loader: tensors by name, code widths from the config. const std = @import("std"); +const core = @import("core"); const Config = @import("../config.zig").Config; /// Each side passes its own core's checkpoint and width types (one by path, one as a module). @@ -21,7 +22,7 @@ pub fn Tables(comptime Checkpoint: type, comptime Width: type) type { /// The width core/quant reads `key`'s words and group tables with. pub fn width(t: *const Self, key: []const u8) !Width { - const s = (try t.cfg.quantization(key)) orelse return error.UnsupportedQuantization; + const s = (try t.cfg.declared(key, core.quant.keys.canonical)) orelse return error.UnsupportedQuantization; return .{ .bits = s.bits, .group = @intCast(s.group) }; } }; diff --git a/zig/src/families/flashnext/hip/tables.zig b/zig/src/families/flashnext/hip/tables.zig index 828663972a4..37642d7b8d9 100644 --- a/zig/src/families/flashnext/hip/tables.zig +++ b/zig/src/families/flashnext/hip/tables.zig @@ -48,7 +48,7 @@ pub const Tables = struct { const w = try ck.get(try std.fmt.allocPrint(a, "{s}.weight", .{stem})); const sc = try ck.get(try std.fmt.allocPrint(a, "{s}.scales", .{stem})); const bi = try ck.get(try std.fmt.allocPrint(a, "{s}.biases", .{stem})); - if (spec == null) spec = (try c.quantization(stem)) orelse return error.UnsupportedQuantization; + if (spec == null) spec = (try c.declared(stem, core.quant.keys.canonical)) orelse return error.UnsupportedQuantization; if (w.shape[0] != n or sc.dtype != .bf16 or bi.dtype != .bf16) return error.UnexpectedNgramTable; s.* = .{ .words = w.bytes, .scales = sc.bytes, .biases = bi.bytes }; }