diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fd4758c4a8..67f825ad665 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- HIP decode: multi-row rounds score each slot's rows from one read of their keys (#N). + +- H3 on Metal: transformer products run on the `h3_gemm_32x64` kernel in 64-row bands and the decoder decodes 64 tiles a pass, with sums unchanged (#N). + +- GLM on CUDA: a prefill cancelled between chunks keeps its completed shared-cache prefix (#N). + - Qwen 3.5 on Metal: `TF_QWEN35_CHUNK` sets the prefill chunk size for measurement; the default stays 128 rows (#N). - CUDA: Ripple-65B-Preview (ricursive) serves on the native engine from the publisher's NVFP4 release as published, with prompt chunks and decode, lane rounds as CUDA graphs, greedy and sampled draws, kept states and the prompt cache; the bf16 release is refused by name, and structured output and forced tool calls are refused until masked sampling lands (#2302, fixes #2300). Thanks to @jrb-ai. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index cd7c6f1c4d8..3608e1ed871 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -208,6 +208,19 @@ enabled on RDNA3.5 for single-round `K <= 1024` plans), whose rows past an item' `item_rows = 0` byte for byte when the largest item holds 3 or 4 rows. Its controls run over items one row short and go red at gate 3. +HIP's shared-row decode score (`plan_rows.hip`: q fp32, d = 256, spans of 16,384 keys or more, launches of more than +one row) replaces `tf_plan_score256_*` byte for byte with two launches on its grid, a block a plan row. First +`tf_plan_lone_score256_*` scores the rows of one-row slots as `tf_plan_score256_*` does, at its occupancy, and its other +blocks leave. Then `tf_plan_rows_score256_*`, counted from each multi-row slot's `first`, has the block of every second +row score that row and the next of the same slot from one read of the keys; the other blocks leave, so a chunk never +crosses a slot. Its registrations run both head groups (16 over 2, 24 over 4) and both cache kinds as one operator, on +launches of 1 to 64 rows: slots of 3, 1, 4 and 2 rows one position apart (at the span's end, mid-span, across a block's +first key, at the span's start), and 5 and 7 slots of one row each, over spans of 16,384 to 262,144 keys with NaN and +infinite keys that some rows of a chunk see and others do not. Its controls go red at gate 3: one leads the chunks over +the whole launch (every slot's `first` 0 and its count every row), so a chunk crosses a slot, and one launches the +chunks alone, so no launch scores the rows of one-row slots. A row scored by both launches gets the same bits from +each, so no control can show it; each kernel's own exit test keeps the two sets apart. + The HIP relu^2 replacement retains every non-finite plant and checks both unfused bytes and every independent float64 output class. No inherited infinity discrepancy is accepted. The paired launch retains every table plant and checks both members' separate-launch bytes and every diff --git a/docs/recipes/minimax-h3-image-metal.md b/docs/recipes/minimax-h3-image-metal.md index beaf85f57a3..9e41cf18329 100644 --- a/docs/recipes/minimax-h3-image-metal.md +++ b/docs/recipes/minimax-h3-image-metal.md @@ -210,7 +210,7 @@ tensor units. 3. Each tile runs `post_quant_conv`, then its cells become tokens through `x_embedder`, with the 4 registers and one zero token appended. 4. The 2D rotary table is built, and the 24 blocks run, then `norm_out` and `proj_out`. -5. Each token's 768 values are unpatchified to its 16 x 16 pixels. Up to 16 tiles run in one command buffer. +5. Each token's 768 values are unpatchified to its 16 x 16 pixels. Up to 64 tiles run in one command buffer. 6. Tiles are blended in float32: the top band against the tile above, then the left band against the tile to the left, both as decoded. 7. The result is mapped to [0, 1] with ImageNet's statistics, clamped and truncated to bytes. diff --git a/docs/recipes/minimax-h3-metal.md b/docs/recipes/minimax-h3-metal.md index 0dd81fb9a84..85483173b8e 100644 --- a/docs/recipes/minimax-h3-metal.md +++ b/docs/recipes/minimax-h3-metal.md @@ -21,8 +21,9 @@ forward stage by stage. ## Arithmetic -- Block projections: the prefill kernels' `tfp::gemm_nax` (MLX 0.32.3's NAX GEMM), bf16 x w^T as the checkpoint - stores w, fp32 sums, bf16 out. The SwiGLU's first projection is one product over its stored [value; gate] rows. +- Block projections: H3's own `h3_gemm_32x64` (64 x 128 a threadgroup, 32 x 64 a warp), bf16 x w^T as the checkpoint + stores w, fp32 sums in MLX 0.32.3's NAX GEMM order, bf16 out: bit-equal to `tfp::gemm_nax`. Threadgroups walk 64 + row tiles under each weight tile. The SwiGLU's first projection is one product over its stored [value; gate] rows. - Norms, rotary, the gated adds and the SwiGLU round to bf16 where the reference's bf16 MLX arithmetic rounds. - Attention is FastH3's video sparse attention over 64-row tiles: a text, keyframe or audio tile attends every tile; a video tile attends the prefix tiles and its top 20% of video tiles by pooled score; the pooled branch is @@ -32,8 +33,8 @@ forward stage by stage. ## Kernel contract -Thirteen kernels are registered (`zig/tests/contract/metal_h3*.zig`), each against its formula in float64, and their -launches in `registry.zig`. The two GEMM entry points are the prefill source's own and are registered as launches. +The kernels are registered (`zig/tests/contract/metal_h3*.zig`), each against its formula in float64, and their +launches in `registry.zig`. The two products also match MLX's gemm_nax byte for byte at the served shapes. Kernels whose outputs pass through intermediate bf16 roundings declare them as `mids`; their test inputs are of one sign where a sum could cancel, so no rounding hides behind a small result. diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index 31db6c3c0fa..961bad3db39 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -18,7 +18,8 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu @import("h3_image_encoder.zig").compileHost(b, target, metal); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); - const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } } }); + const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } }; + const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports }); const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) }); const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core } } }) }); const compile = b.step("compile-h3-host", "Compile the actual H3 tools without compiling or executing shaders"); @@ -28,6 +29,10 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const rounding = b.addRunArtifact(b.addTest(.{ .root_module = modulation, .filters = &.{"modulation bf16:"} })); b.step("test-h3-modulation-bf16", "H3's host bf16 rounding against the copy it replaced, no GPU").dependOn(&rounding.step); test_step.dependOn(&rounding.step); + const block = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/block.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports }); + const bands = b.addRunArtifact(b.addTest(.{ .root_module = block, .filters = &.{"h3 gemm:"} })); + b.step("test-h3-gemm", "H3's transformer products in 64-tile bands against MLX's band of 4, on the GPU").dependOn(&bands.step); + test_step.dependOn(&bands.step); const ahead = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/read_ahead.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} }); const read_test = b.addTest(.{ .root_module = ahead }); const read_step = b.step("test-h3-read-ahead", "H3 whole-shard reads, truncated or missing files, and prefetch disabled"); diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 1df64746c45..ffea8c4ff64 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -501,6 +501,7 @@ const groups = [_]Source{ .{ .path = "qwen_vision.hip", .strict = true }, .{ .path = "draft/draft.hip" }, .{ .path = "exl3/exl3.hip" }, + .{ .path = "decode/plan_rows.hip" }, }; /// What the group sources include, so an edit to one rebuilds them. const headers = [_][]const u8{ diff --git a/zig/glm_image_cache_host.zig b/zig/glm_image_cache_host.zig index a8201e1a5ef..3763d3082ac 100644 --- a/zig/glm_image_cache_host.zig +++ b/zig/glm_image_cache_host.zig @@ -394,3 +394,107 @@ test "GLM image cache: suffix encoding wire and actual splice dispatch preserve try peer.take(0, none); try t.expectEqual(@as(usize, 0), peer.rowCount()); } + +/// Echo rank zero's reduction locally. The chunk control and the cache go through their serving paths. +const CancelWire = struct { + fn broadcast(_: u64, _: u64, _: usize, _: cuda.nccl.DataType, _: c_int, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) c_int { + return 0; + } + fn reduce(_: u64, _: u64, _: usize, _: cuda.nccl.DataType, _: cuda.nccl.RedOp, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) c_int { + return 0; + } + fn download(dst: ?*anyopaque, src: u64, n: usize) callconv(.c) c_int { + @memcpy(@as([*]u8, @ptrCast(dst.?))[0..n], @as([*]const u8, @ptrFromInt(src))[0..n]); + return 0; + } + fn device(d: *cuda.abi.Device) callconv(.c) c_int { + d.* = 0; + return 0; + } + fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) c_int { + out.* = 0; + return 0; + } +}; + +fn checkInterruptedPrefix(planned: []const u32) !void { + var c: Cache = .{}; + try c.init(); + defer c.deinit(); + var d = Device.driver(); + d.api.cuDeviceGetAttribute = CancelWire.attribute; + d.api.cuCtxGetDevice = CancelWire.device; + d.api.cuMemcpyDtoH_v2 = CancelWire.download; + cuda.download_stage.forget(); + defer cuda.download_stage.forget(); + defer { + cuda.copy_source.synchronizeStream(&d, null) catch {}; + cuda.copy_source.dropSpares(&d, cuda.copy_source.current()); + } + var lib: cuda.nccl.Library = .{ .lib = undefined, .api = undefined }; + lib.api.ncclBroadcast = CancelWire.broadcast; + lib.api.ncclAllReduce = CancelWire.reduce; + var word: f64 = 0; + var wire_buffer: [10000]u8 = undefined; + var wire_ids: [2049]u32 = undefined; + c.e.d = &d; + c.e.stream = .{ .d = &d, .handle = null }; + c.e.lib = &lib; + c.e.comm = null; + c.e.dropped = .empty; + c.e.announce = 0; + c.e.share.rank = 0; + c.e.share.world = 2; + c.e.settings = .{}; + c.e.m.glue.put_words = .{ .d = &d, .handle = null }; + c.e.heat_gate.bands = null; + c.e.prompt_profs = @splat(null); + c.e.profiling_prompt = null; + c.e.prompt_logprobs = null; + c.e.drafter = null; + c.e.l2pf = null; + c.e.images = null; + c.e.pair = null; + c.e.shared_buf = .{ .d = &d, .ptr = @intFromPtr(&word), .len = @sizeOf(f64), .borrowed = true }; + var seq: @TypeOf(c.e.cur.*) = .{ .st = undefined }; + c.e.seqs = .empty; + try c.e.seqs.append(a, &seq); + defer c.e.seqs.deinit(a); + var link: glm.follow.Link = .{ + .d = &d, + .lib = &lib, + .comm = null, + .stream = c.e.stream, + .ids = &wire_ids, + .gpa = a, + .wait = true, + .buf = .{ .d = &d, .ptr = @intFromPtr(&wire_buffer), .len = wire_buffer.len, .borrowed = true }, + }; + var back: glm.lanes.Lanes = .{ .x = .{ .e = &c.e, .link = &link } }; + defer back.deinit(); + const ids: [N]u32 = @splat(17); + var s = try lanes.Stream.init(a, .{ .id = "cancelled", .prompt = &ids, .max_new = 8 }); + defer s.deinit(a); + const lane = try back.claim(&s); + lane.fill = 2048; + lane.marks = try a.dupe(u32, planned); + c.model.words = .{ 31, 47 }; + try t.expect(s.reuse.hook == null); + try t.expectEqual(@as(u32, 0), try c.begin(&s)); + const b = back.backend(); + try b.vtable.cancel_prefill.?(b.ptr, &s); + try t.expectEqual(@as(usize, 1), c.model.live); + c.model.words = .{ 0, 0 }; + var retry = try lanes.Stream.init(a, .{ .id = "retry", .prompt = &ids, .max_new = 8 }); + defer retry.deinit(a); + try t.expectEqual(@as(u32, 2048), try c.begin(&retry)); + try t.expectEqual([2]u64{ 31, 47 }, c.model.words); +} + +test "GLM shared cache: cancellation before a scheduled mark preserves the completed prefix for retry" { + try checkInterruptedPrefix(&.{6144}); +} + +test "GLM shared cache: cancellation without scheduled marks preserves the completed prefix for retry" { + try checkInterruptedPrefix(&.{}); +} diff --git a/zig/kernels/hip/decode/plan.hip b/zig/kernels/hip/decode/plan.hip index d6b2a8a754e..1f5deba61c9 100644 --- a/zig/kernels/hip/decode/plan.hip +++ b/zig/kernels/hip/decode/plan.hip @@ -11,22 +11,6 @@ __device__ __forceinline__ float wave_sum(float x) { return __shfl(x, 0, 32); } -// x from lane ^ M of its 16-lane row (M < 16): a DPP row_xmask move, all lanes active. -template -__device__ __forceinline__ float row_xor(float x) { - return __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, x), 0x160 + M, 0xf, 0xf, false)); -} - -// wave_sum's folds, own value then partner's at xor 16, 8, 4, 2, 1, without LDS: every lane ends with the sum. -__device__ __forceinline__ float wave_sum_dpp(float x) { - const int w = __builtin_bit_cast(int, x); - x += __builtin_bit_cast(float, __builtin_amdgcn_permlanex16(w, w, 0x76543210u, 0xfedcba98u, false, false)); - x += row_xor<8>(x); - x += row_xor<4>(x); - x += row_xor<2>(x); - return x + row_xor<1>(x); -} - // 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) { @@ -56,42 +40,8 @@ __device__ void plan_kv_write_act_body(const void* keys, const void* values, int cache[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; - -// Keys a wave scores on long spans and on short ones: their loads go out together, each head's query read once. -constexpr int kScoreKeys = 4; +// Keys a wave scores on short spans (kScoreKeys on long ones, plan.hpp). constexpr int kScoreKeysShort = 2; -// Steps of its waves' keys a long-span block walks at d = 256 (launches/plan.zig's score_steps). -constexpr int kScoreSteps = 8; -// load() of a 16-bit cache element as a global load: a flat load also counts on lgkmcnt, which LDS reads wait on. -__device__ __forceinline__ float cache_load(const void* p, int kind, long long i) { - const uint16_t bits = ((const __attribute__((address_space(1))) uint16_t*)p)[i]; - return kind == 1 ? __half2float(__ushort_as_half(bits)) : bf16_to_float(bits); -} - -// A wave's KEYS keys from key0 at d = 256 into k, lane l taking elements l + 32 i; keys past `visible` are not loaded. -template -__device__ __forceinline__ void score_fetch(float (&k)[KEYS][8], const void* keys, int kind, const unsigned* pages, - unsigned pool, int kv, int key0, int visible, int lane) { -#pragma unroll - for (int j = 0; j < KEYS; ++j) { - if (key0 + j >= visible) break; - const long long base = page_at(pages, pool, kv, key0 + j, 256); -#pragma unroll - for (int i = 0; i < 8; ++i) k[j][i] = cache_load(keys, kind, base + lane + i * 32); - } -} - -// Lane 0's KEYS scores of a head from `at`: one 16-byte store when `whole` (aligned rows, span a multiple of KEYS). -template -__device__ __forceinline__ void score_store(float* at, const float (&sc)[KEYS], bool whole, int key0, int span) { - if (whole && KEYS == 4) { - *reinterpret_cast(at) = make_float4(sc[0], sc[1 % KEYS], sc[2 % KEYS], sc[3 % KEYS]); - } else { - for (int j = 0; j < KEYS; ++j) if (key0 + j < span) at[j] = sc[j]; - } -} // score_keys over a plan's rows: a warp scores KEYS keys for each of the block's heads; q fp32 or of kind QKIND. template @@ -155,69 +105,6 @@ __device__ void plan_score_body(const void* __restrict__ q, float* __restrict__ } } -// plan_score_body on long spans at d = 256 (tf_plan_score256_*): no element tests, kScoreSteps steps a block. -template -__device__ void plan_score256_body(const void* __restrict__ q, float* __restrict__ scores, int span, int heads, - int kv_heads, int d, float scale, PlanArgs plan, int layer) { - constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps; - extern __shared__ float qs[]; // the block's query heads, group * d - const int batch = blockIdx.z, group = heads / gridDim.y, head0 = blockIdx.y * group; - const long long q0 = (static_cast(batch) * heads + head0) * d; - for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = load(q, QKIND, q0 + i); // kind 0: q fp32 - __syncthreads(); - const int visible = min(plan.pos[batch] + 1, span); - const int lane = threadIdx.x & 31; - const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); - float* __restrict__ rows = scores + (static_cast(batch) * heads + head0) * span; - const void* keys = reinterpret_cast(desc[plan_first(layer)]); - const unsigned* pages = plan_pages(plan, desc); - const unsigned pool = plan.pool; - const int kv = head0 / (heads / kv_heads); - const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block - const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS; - const bool whole = (span % KEYS) == 0 && (reinterpret_cast(rows) & 15) == 0; - float kreg[KEYS][8] = {}; - score_fetch(kreg, keys, KIND, pages, pool, kv, first, visible, lane); -#pragma unroll 1 - for (int step = 0; step < STEPS; ++step) { - const int key0 = first + step * stride; - if (key0 >= span) break; // the same for the whole wave - float next[KEYS][8] = {}; - score_fetch(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, visible, lane); - if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them - float none[KEYS]; - for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY; - for (int g = 0; lane == 0 && g < group; ++g) { - score_store(rows + key0 + static_cast(g) * span, none, whole, key0, span); - } - } else { -#pragma unroll - for (int g = 0; g < kMaxGroup; ++g) { - if (g < group) { // the same for the whole block, so every lane reaches the folds - float qv[8]; -#pragma unroll - for (int i = 0; i < 8; ++i) qv[i] = qs[g * 256 + lane + i * 32]; - float dot[KEYS]; -#pragma unroll - for (int j = 0; j < KEYS; ++j) { - float partial = 0.f; -#pragma unroll - for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i]; - dot[j] = wave_sum_dpp(partial); - } - if (lane == 0) { - float sc[KEYS]; -#pragma unroll - for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY; - score_store(rows + key0 + static_cast(g) * span, sc, whole, key0, span); - } - } - } - } - __builtin_memcpy(kreg, next, sizeof(kreg)); - } -} - // 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, diff --git a/zig/kernels/hip/decode/plan.hpp b/zig/kernels/hip/decode/plan.hpp index 7e3af96b47b..807c49df5bd 100644 --- a/zig/kernels/hip/decode/plan.hpp +++ b/zig/kernels/hip/decode/plan.hpp @@ -3,6 +3,7 @@ #include #include "decode/pages.hpp" +#include "ops/common.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 { @@ -28,3 +29,123 @@ __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); } + +// The d = 256 long-span score's pieces (plan.hip's tf_plan_score256_*, plan_rows.hip's kernels). +namespace { + +// x from lane ^ M of its 16-lane row (M < 16): a DPP row_xmask move, all lanes active. +template +__device__ __forceinline__ float row_xor(float x) { + return __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, x), 0x160 + M, 0xf, 0xf, false)); +} + +// wave_sum's folds, own value then partner's at xor 16, 8, 4, 2, 1, without LDS: every lane ends with the sum. +__device__ __forceinline__ float wave_sum_dpp(float x) { + const int w = __builtin_bit_cast(int, x); + x += __builtin_bit_cast(float, __builtin_amdgcn_permlanex16(w, w, 0x76543210u, 0xfedcba98u, false, false)); + x += row_xor<8>(x); + x += row_xor<4>(x); + x += row_xor<2>(x); + return x + row_xor<1>(x); +} + +// 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; + +// Keys a wave scores on long spans (plan.hip's kScoreKeysShort on short ones): their loads go out together. +constexpr int kScoreKeys = 4; +// Steps of its waves' keys a long-span block walks at d = 256 (launches/plan.zig's score_steps). +constexpr int kScoreSteps = 8; +// load() of a 16-bit cache element as a global load: a flat load also counts on lgkmcnt, which LDS reads wait on. +__device__ __forceinline__ float cache_load(const void* p, int kind, long long i) { + const uint16_t bits = ((const __attribute__((address_space(1))) uint16_t*)p)[i]; + return kind == 1 ? __half2float(__ushort_as_half(bits)) : bf16_to_float(bits); +} + +// A wave's KEYS keys from key0 at d = 256 into k, lane l taking elements l + 32 i; keys past `visible` are not loaded. +template +__device__ __forceinline__ void score_fetch(float (&k)[KEYS][8], const void* keys, int kind, const unsigned* pages, + unsigned pool, int kv, int key0, int visible, int lane) { +#pragma unroll + for (int j = 0; j < KEYS; ++j) { + if (key0 + j >= visible) break; + const long long base = page_at(pages, pool, kv, key0 + j, 256); +#pragma unroll + for (int i = 0; i < 8; ++i) k[j][i] = cache_load(keys, kind, base + lane + i * 32); + } +} + +// Lane 0's KEYS scores of a head from `at`: one 16-byte store when `whole` (aligned rows, span a multiple of KEYS). +template +__device__ __forceinline__ void score_store(float* at, const float (&sc)[KEYS], bool whole, int key0, int span) { + if (whole && KEYS == 4) { + *reinterpret_cast(at) = make_float4(sc[0], sc[1 % KEYS], sc[2 % KEYS], sc[3 % KEYS]); + } else { + for (int j = 0; j < KEYS; ++j) if (key0 + j < span) at[j] = sc[j]; + } +} + +// plan_score_body on long spans at d = 256 (tf_plan_score256_*): no element tests, kScoreSteps steps a block. +template +__device__ void plan_score256_body(const void* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps; + extern __shared__ float qs[]; // the block's query heads, group * d + const int batch = blockIdx.z, group = heads / gridDim.y, head0 = blockIdx.y * group; + const long long q0 = (static_cast(batch) * heads + head0) * d; + for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = load(q, QKIND, q0 + i); // kind 0: q fp32 + __syncthreads(); + const int visible = min(plan.pos[batch] + 1, span); + const int lane = threadIdx.x & 31; + const unsigned long long* desc = plan_desc(plan, plan.slot[batch]); + float* __restrict__ rows = scores + (static_cast(batch) * heads + head0) * span; + const void* keys = reinterpret_cast(desc[plan_first(layer)]); + const unsigned* pages = plan_pages(plan, desc); + const unsigned pool = plan.pool; + const int kv = head0 / (heads / kv_heads); + const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block + const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS; + const bool whole = (span % KEYS) == 0 && (reinterpret_cast(rows) & 15) == 0; + float kreg[KEYS][8] = {}; + score_fetch(kreg, keys, KIND, pages, pool, kv, first, visible, lane); +#pragma unroll 1 + for (int step = 0; step < STEPS; ++step) { + const int key0 = first + step * stride; + if (key0 >= span) break; // the same for the whole wave + float next[KEYS][8] = {}; + score_fetch(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, visible, lane); + if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them + float none[KEYS]; + for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY; + for (int g = 0; lane == 0 && g < group; ++g) { + score_store(rows + key0 + static_cast(g) * span, none, whole, key0, span); + } + } else { +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) { // the same for the whole block, so every lane reaches the folds + float qv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) qv[i] = qs[g * 256 + lane + i * 32]; + float dot[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) { + float partial = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i]; + dot[j] = wave_sum_dpp(partial); + } + if (lane == 0) { + float sc[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY; + score_store(rows + key0 + static_cast(g) * span, sc, whole, key0, span); + } + } + } + } + __builtin_memcpy(kreg, next, sizeof(kreg)); + } +} + +} // namespace diff --git a/zig/kernels/hip/decode/plan_rows.hip b/zig/kernels/hip/decode/plan_rows.hip new file mode 100644 index 00000000000..3b14a65e4bf --- /dev/null +++ b/zig/kernels/hip/decode/plan_rows.hip @@ -0,0 +1,111 @@ +// A round's multi-row slots scored from one read of their keys, the others alone (q fp32, d 256, long spans). + +#include "ops/common.hpp" +#include "decode/plan.hpp" + +namespace { + +// Rows of one slot a block scores (launches/plan.zig's score_rows): their queries share the block's LDS. +constexpr int kRows = 2; + +// A row's place in its slot's list when that slot lists more than one row, else -1: the row is scored alone. +__device__ __forceinline__ int plan_shared_at(const PlanArgs& plan, int batch) { + const int slot = plan.slot[batch], at = batch - plan.first[slot], count = plan.count[slot]; + return count > 1 && at >= 0 && at < count ? at : -1; +} + +// plan_score256_body (plan.hpp) for a row that scores alone: its bits and its block's LDS are tf_plan_score256_*'s. +template +__device__ void plan_lone_score256_body(const float* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + if (plan_shared_at(plan, blockIdx.z) >= 0) return; // tf_plan_rows_score256_* scores it + plan_score256_body(q, scores, span, heads, kv_heads, d, scale, plan, layer); +} + +// plan_score256_body on a chunk of a multi-row slot's rows: the keys read once, each row's dots in the tree's order. +template +__device__ void plan_rows_score256_body(const float* __restrict__ q, float* __restrict__ scores, int span, int heads, + int kv_heads, int d, float scale, PlanArgs plan, int layer) { + constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps; + extern __shared__ float qs[]; // the chunk's rows' query heads of the block, rows * group * d + const int batch = blockIdx.z, slot = plan.slot[batch], at = plan_shared_at(plan, batch); + if (at < 0 || at % kRows != 0) return; // a row scored alone, or the chunk's first row's block scores it + const int rows = min(min(kRows, plan.count[slot] - at), static_cast(gridDim.z) - batch); + const int group = heads / gridDim.y, head0 = blockIdx.y * group; + for (int i = threadIdx.x; i < rows * group * 256; i += blockDim.x) { + const int r = i / (group * 256); + qs[i] = q[(static_cast(batch + r) * heads + head0) * 256 + (i - r * group * 256)]; + } + __syncthreads(); + int most = 0; + for (int r = 0; r < rows; ++r) most = max(most, min(plan.pos[batch + r] + 1, span)); + const int lane = threadIdx.x & 31; + const unsigned long long* desc = plan_desc(plan, slot); + const void* keys = reinterpret_cast(desc[plan_first(layer)]); + const unsigned* pages = plan_pages(plan, desc); + const unsigned pool = plan.pool; + const int kv = head0 / (heads / kv_heads); + const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block + const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS; + float kreg[KEYS][8] = {}; + score_fetch(kreg, keys, KIND, pages, pool, kv, first, most, lane); +#pragma unroll 1 + for (int step = 0; step < STEPS; ++step) { + const int key0 = first + step * stride; + if (key0 >= span) break; // the same for the whole wave + float next[KEYS][8] = {}; + score_fetch(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, most, lane); +#pragma unroll 1 + for (int r = 0; r < rows; ++r) { + const int visible = min(plan.pos[batch + r] + 1, span); + float* __restrict__ out = scores + (static_cast(batch + r) * heads + head0) * span; + const bool whole = (span % KEYS) == 0 && (reinterpret_cast(out) & 15) == 0; + if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them + float none[KEYS]; + for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY; + for (int g = 0; lane == 0 && g < group; ++g) { + score_store(out + key0 + static_cast(g) * span, none, whole, key0, span); + } + } else { +#pragma unroll + for (int g = 0; g < kMaxGroup; ++g) { + if (g < group) { // the same for the whole block, so every lane reaches the folds + float qv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) qv[i] = qs[(r * group + g) * 256 + lane + i * 32]; + float dot[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) { + float partial = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i]; + dot[j] = wave_sum_dpp(partial); + } + if (lane == 0) { + float sc[KEYS]; +#pragma unroll + for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY; + score_store(out + key0 + static_cast(g) * span, sc, whole, key0, span); + } + } + } + } + } + __builtin_memcpy(kreg, next, sizeof(kreg)); + } +} + +} // namespace + +extern "C" { + +// tf_plan_score256_*'s arguments and grid: _lone_ scores the rows that score alone, _rows_ the multi-row slots' chunks. +#define TF_PLAN_ROWS_SCORE256(Name, Body, KIND) __global__ void __launch_bounds__(128) Name(const float* q, \ + float* scores, int span, int heads, int kv_heads, int d, float scale, PlanArgs plan, int layer) { \ + Body(q, scores, span, heads, kv_heads, d, scale, plan, layer); } +TF_PLAN_ROWS_SCORE256(tf_plan_lone_score256_f16, plan_lone_score256_body, 1) +TF_PLAN_ROWS_SCORE256(tf_plan_lone_score256_bf16, plan_lone_score256_body, 2) +TF_PLAN_ROWS_SCORE256(tf_plan_rows_score256_f16, plan_rows_score256_body, 1) +TF_PLAN_ROWS_SCORE256(tf_plan_rows_score256_bf16, plan_rows_score256_body, 2) + +} // extern "C" diff --git a/zig/kernels/metal/h3/h3_gemm.metal b/zig/kernels/metal/h3/h3_gemm.metal new file mode 100644 index 00000000000..972956c9764 --- /dev/null +++ b/zig/kernels/metal/h3/h3_gemm.metal @@ -0,0 +1,110 @@ +// H3's products, 64 x 128 a threadgroup and 32 x 64 a warp; each output's K chain is MLX's, 32-deep steps in order. +namespace tfp { + +template +inline void h3_step(thread frag (&acc)[2][4], const device bfloat* A, const device bfloat* B, int lda, int ldb, + int kk, int kn, int rows, int cols, short2 home) { + frag a[2][2], b[2][4]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + if (BOUND) frag_get_in(a[m][k], A, lda, 16 * m, kk + 16 * k, home, rows, kk + kn); + else frag_get(a[m][k], A, lda, 16 * m, kk + 16 * k, home); + } + } + TF_UNROLL + for (short k = 0; k < 2; k++) { + TF_UNROLL + for (short n = 0; n < 4; n++) { + if (BOUND) frag_get_in(b[k][n], B, ldb, 16 * n, kk + 16 * k, home, cols, kk + kn); + else frag_get(b[k][n], B, ldb, 16 * n, kk + 16 * k, home); + } + } + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + mma_16x32(acc[m][0], acc[m][1], a[m][k], b[k][0], b[k][1]); + mma_16x32(acc[m][2], acc[m][3], a[m][k], b[k][2], b[k][3]); + } + } +} + +// D [P[0], P[1]] = A [P[0], P[2]] * B^T [P[1], P[2]], N a multiple of 128; AM false bounds the rows. +template +inline void h3_gemm(const device bfloat* A, const device bfloat* B, device bfloat* D, const device int* P, uint3 tg, + uint sg, uint lane) { + const int swz = P[8]; + const int ty = (int(tg.y) << swz) + (int(tg.x) & ((1 << swz) - 1)), tx = int(tg.x) >> swz; + if (tx >= P[6] || ty >= P[7]) return; + const int lda = P[3], ldb = P[4], ldd = P[5]; + const int row = ty * 64 + 32 * int(sg / 2), col = tx * 128 + 64 * int(sg % 2); + A += long(P[13]) + long(P[10]) * tg.z + long(row) * lda; + B += long(P[14]) + long(P[11]) * tg.z + long(col) * ldb; + D += long(P[12]) * tg.z + long(row) * ldd + col; + const int rows = AM ? 32 : min(32, P[0] - row), cols = 64; + const bool full = AM || rows == 32; + const bool live = rows > 0; + const short2 home = frag_home(ushort(lane)); + frag acc[2][4]; + TF_UNROLL + for (short m = 0; m < 2; m++) TF_UNROLL for (short n = 0; n < 4; n++) acc[m][n] = frag(0); + const int kblocks = P[9]; +#pragma clang loop unroll(disable) + for (int kb = 0; kb < kblocks; kb++) { + threadgroup_barrier(mem_flags::mem_none); + if (full) { +#pragma clang loop unroll(disable) + for (int kk = 0; kk < 256; kk += 32) h3_step(acc, A, B, lda, ldb, kk, 32, rows, cols, home); + } else if (live) { +#pragma clang loop unroll(disable) + for (int kk = 0; kk < 256; kk += 32) h3_step(acc, A, B, lda, ldb, kk, 32, rows, cols, home); + } + A += 256; + B += 256; + } + const int rest = P[2] - kblocks * 256; + if (rest > 0) { + simdgroup_barrier(mem_flags::mem_none); + if (live) { +#pragma clang loop unroll(disable) + for (int kk = 0; kk < rest; kk += 32) h3_step(acc, A, B, lda, ldb, kk, max(0, rest - kk), rows, cols, home); + } + } + if (!live) return; + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short n = 0; n < 4; n++) { + if (full) frag_put(acc[m][n], D, ldd, 16 * m, 16 * n, home); + else frag_put_in(acc[m][n], D, ldd, 16 * m, 16 * n, home, rows, cols); + } + } +} + +} // namespace tfp + +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void h3_gemm_32x64( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::h3_gemm(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); +} + +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void h3_gemm_32x64_ragged( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::h3_gemm(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); +} diff --git a/zig/kernels/metal/h3/kernels.zig b/zig/kernels/metal/h3/kernels.zig index 855e4b13ba3..6c564556add 100644 --- a/zig/kernels/metal/h3/kernels.zig +++ b/zig/kernels/metal/h3/kernels.zig @@ -1,6 +1,11 @@ //! MiniMax H3's Metal kernels: three sources joined and compiled at load, after the prefill kernels' gemm_nax. pub const source = @embedFile("h3_rows.metal") ++ @embedFile("h3_routing.metal") ++ @embedFile("h3_attention.metal"); +/// H3's own products, after `source`: they need gemm_nax's fragments ahead of them. +pub const gemm_source = @embedFile("h3_gemm.metal"); /// MLX's bf16 GEMM, x w^T with N a multiple of 128 and M a multiple of 64 (whole) or not (ragged). pub const gemm_whole = "custom_kernel_tf_gemm_nax_bf16_n_t_t_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"; pub const gemm_ragged = "custom_kernel_tf_gemm_nax_bf16_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"; -pub const names = [_][:0]const u8{ "h3_rows_in", "h3_norm", "h3_gate_add", "h3_gate_mix", "h3_swiglu", "h3_final_norm", "h3_rows_out", "h3_heads", "h3_pool", "h3_tile_scores", "h3_topk", "h3_coarse", "h3_attention", "h3_modulation", gemm_whole, gemm_ragged }; +/// H3's products at 64 x 128 a threadgroup and 32 x 64 a warp. +pub const gemm_32x64 = "h3_gemm_32x64"; +pub const gemm_32x64_ragged = "h3_gemm_32x64_ragged"; +pub const names = [_][:0]const u8{ "h3_rows_in", "h3_norm", "h3_gate_add", "h3_gate_mix", "h3_swiglu", "h3_final_norm", "h3_rows_out", "h3_heads", "h3_pool", "h3_tile_scores", "h3_topk", "h3_coarse", "h3_attention", "h3_modulation", gemm_32x64, gemm_32x64_ragged }; diff --git a/zig/runtime_sources/modes_test.zig b/zig/runtime_sources/modes_test.zig index 2eea128df64..e258527a620 100644 --- a/zig/runtime_sources/modes_test.zig +++ b/zig/runtime_sources/modes_test.zig @@ -65,7 +65,7 @@ test "Metal runtime source modes: H3 preserves the loader's complete prefix and const gemm = try std.mem.replaceOwned(u8, a, gemm_text, "#include \"../nax.h\"", sources.nax); for ([_]usize{ 56, 16 }, [_]usize{ 288, 4 }, [_][]const u8{ "", "#define H3_TEST 1\n" }) |heads, tiles, defines| { const sizes = try std.fmt.allocPrint(a, "#define H3_HEADS {d}\n#define H3_SLOTS {d}\n#define H3_TILES {d}\n{s}\n{s}", .{ heads, tiles * 64, tiles, defines, kernels.source }); - const before = try std.mem.concat(a, u8, &.{ gemm, sizes }); + const before = try std.mem.concat(a, u8, &.{ gemm, sizes, kernels.gemm_source }); const after = try h3.library(a, heads, tiles * 64, tiles, defines); try t.expect(std.mem.eql(u8, before, after)); } diff --git a/zig/src/core/contract/hip_records.zig b/zig/src/core/contract/hip_records.zig index 8165561207e..947c156939d 100644 --- a/zig/src/core/contract/hip_records.zig +++ b/zig/src/core/contract/hip_records.zig @@ -494,7 +494,7 @@ const own_records = [own_count]Record{ }, }, } ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++ @import("hip_records_draft.zig").records ++ @import("hip_records_exl3.zig").records ++ - @import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records; + @import("hip_records_score.zig").records ++ @import("hip_records_score_rows.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records; pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++ @import("hip_records_item.zig").records ++ @import("hip_records_qwen3.zig").records ++ @import("hip_records_columns.zig").records ++ diff --git a/zig/src/core/contract/hip_records_families.zig b/zig/src/core/contract/hip_records_families.zig index 6db017bdc6e..ef35a44fd52 100644 --- a/zig/src/core/contract/hip_records_families.zig +++ b/zig/src/core/contract/hip_records_families.zig @@ -37,6 +37,7 @@ test "HIP record counts stay pinned in their owning files" { @import("hip_records_relu2_widths.zig").records.len, @import("hip_records_router.zig").records.len, @import("hip_records_score.zig").records.len, + @import("hip_records_score_rows.zig").records.len, @import("hip_records_skew.zig").records.len, @import("hip_records_sparse.zig").records.len, @import("hip_records_stream_plain.zig").records.len, diff --git a/zig/src/core/contract/hip_records_score_rows.zig b/zig/src/core/contract/hip_records_score_rows.zig new file mode 100644 index 00000000000..8ade2c924be --- /dev/null +++ b/zig/src/core/contract/hip_records_score_rows.zig @@ -0,0 +1,38 @@ +//! Gate 5's records of plan_rows.hip's kernels: a multi-row launch's rows that score alone, and its slots' chunks. +const limits = @import("limits.zig"); +const Record = @import("hip_records.zig").Record; + +const U = limits.HipUsage; + +/// 128 threads, the queries of `rows` rows of at most kMaxGroup heads of 256 in dynamic LDS. +fn rowsScore(comptime symbol: []const u8, comptime rows: u32, usage: [limits.rdna.len]U) Record { + const name = "planned walk " ++ symbol; + return .{ .launch = .{ .name = name, .symbol = symbol, .image = "plan_rows", .threads = 128, .dynamic = rows * 16 * 256 * 4 }, .usage = usage }; +} + +pub const records = [4]Record{ + rowsScore("tf_plan_lone_score256_f16", 1, .{ + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), + rowsScore("tf_plan_lone_score256_bf16", 1, .{ + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 108, .sgprs = 77, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), + rowsScore("tf_plan_rows_score256_f16", 2, .{ + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), + rowsScore("tf_plan_rows_score256_bf16", 2, .{ + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + .{ .vgprs = 115, .sgprs = 95, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, + }), +}; diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index ebe578ee1da..11d8199b706 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -353,6 +353,8 @@ pub const metal = joins.metal_before ++ [_]M{ .{ .name = "h3 routed attention h3_attention", .threads = 256, .tg_memory = 25856, .offline = false }, .{ .name = "h3 gemm whole custom_kernel_tf_gemm_nax_bf16_n_t_t_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "h3 gemm ragged custom_kernel_tf_gemm_nax_bf16_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "h3 product 32x64 h3_gemm_32x64", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "h3 product 32x64 ragged h3_gemm_32x64_ragged", .threads = 128, .tg_memory = 0, .reserved = 128 }, .{ .name = "qwen vision qwv_gemm_bf16_nt_00", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "qwen vision qwv_gemm_bf16_nt_01", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "qwen vision qwv_gemm_bf16_nt_10", .threads = 256, .tg_memory = 0, .reserved = 256 }, diff --git a/zig/src/families/glm/cuda_lanes.zig b/zig/src/families/glm/cuda_lanes.zig index 37eedcc152a..c38cfbeb047 100644 --- a/zig/src/families/glm/cuda_lanes.zig +++ b/zig/src/families/glm/cuda_lanes.zig @@ -266,10 +266,11 @@ pub const Lanes = struct { const self = of(ptr); const l = self.lanes.getPtr(s) orelse return; const at = l.fill orelse return; - if (at <= s.cached or s.reuse.hook == null) return; - try self.x.bind(l.slot); + if (at <= s.cached) return; var keeps: share_mod.Keeps = undefined; - _ = self.x.chunk(s.prompt(), at, false, null, .{ .ptr = null, .check = cancelNow }, self.marksOf(s, &keeps)) catch |err| { + const marks = self.marksOf(s, &keeps) orelse return; + try self.x.bind(l.slot); + _ = self.x.chunk(s.prompt(), at, false, null, .{ .ptr = null, .check = cancelNow }, marks) catch |err| { if (err == error.Cancelled) return; return err; }; diff --git a/zig/src/families/glm/cuda_share.zig b/zig/src/families/glm/cuda_share.zig index ad4ec25ea7c..7966bcc0974 100644 --- a/zig/src/families/glm/cuda_share.zig +++ b/zig/src/families/glm/cuda_share.zig @@ -152,5 +152,6 @@ pub const Keeps = struct { /// The same content key names lookup and every completed or interrupted keep. pub fn marks(e: *engine.Engine, slot: u32, s: *const Stream, at: []const u32, keeps: *Keeps) ?engine.Marks { keeps.* = .{ .e = e, .slot = slot, .prompt = cacheKey(s) orelse return null, .images = s.images }; - return if (at.len == 0) null else .{ .at = at, .ctx = keeps, .call = Keeps.at, .interrupted = Keeps.at }; + // A cancellation can keep its last completed cut even when no later mark was scheduled. + return .{ .at = at, .ctx = keeps, .call = Keeps.at, .interrupted = Keeps.at }; } diff --git a/zig/src/families/h3/block.zig b/zig/src/families/h3/block.zig index 2e7022b5ab0..4f33f6f2fcb 100644 --- a/zig/src/families/h3/block.zig +++ b/zig/src/families/h3/block.zig @@ -1,4 +1,4 @@ -//! One FastH3 block in bf16: products on tfp::gemm_nax (MLX's GEMM, fp32 sums), FastH3's routed attention in bf16. +//! One FastH3 block in bf16: products on h3_gemm_32x64 (fp32 sums, MLX's K order), routed attention in bf16. const std = @import("std"); const mtl = @import("metal"); const h3 = @import("h3.zig"); @@ -8,19 +8,28 @@ const kernels = @import("h3_kernels"); const Model = h3.Model; const Ref = h3.Ref; +/// Threadgroups walk 2^swizzle row tiles under each weight tile: 64 keep it cached, where MLX's swizzle 2 walks 4. +const swizzle = 6; + /// d (rows, n) = x (rows, k) w^T for w (n, k) in bf16. fn gemm(m: *const Model, enc: mtl.ComputeEncoder, x: mtl.Buffer, w: Ref, d: mtl.Buffer, n: usize, k: usize) void { + const pipe = if (m.rows % 64 == 0) m.pipeline(kernels.gemm_32x64) else m.pipeline(kernels.gemm_32x64_ragged); + product(enc, pipe, swizzle, x, w, d, m.rows, n, k, 128); +} + +fn product(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, s: usize, x: mtl.Buffer, w: Ref, d: mtl.Buffer, rows: usize, n: usize, k: usize, comptime threads: usize) void { + const band = @as(usize, 1) << @intCast(s); const tn = n / 128; - const tm = (m.rows + 63) / 64; - enc.setPipeline(if (m.rows % 64 == 0) m.pipeline(kernels.gemm_whole) else m.pipeline(kernels.gemm_ragged)); + const tm = (rows + 63) / 64; + enc.setPipeline(pipe); enc.setBuffer(x, 0, 0); enc.setBuffer(w.buffer, w.offset, 1); var p: [16]i32 = @splat(0); - const values = [_]usize{ m.rows, n, k, k, k, n, tn, tm, 2, k / 256 }; + const values = [_]usize{ rows, n, k, k, k, n, tn, tm, s, k / 256 }; for (values, 0..) |v, i| p[i] = @intCast(v); enc.setBytes(std.mem.asBytes(&p), 2); enc.setBuffer(d, 0, 3); - enc.dispatchThreads(mtl.Size.of(tn * 4 * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); + enc.dispatchGroups(mtl.Size.of(tn * band, (tm + band - 1) / band, 1), mtl.Size.of(32, 4, threads / 128)); } /// The stream's modulated norm to bf16 rows in xn; with `gates` it first adds the branch in `y` gated by that part. @@ -130,3 +139,71 @@ pub fn run(m: *Model, pass: *h3.Pass, index: usize) void { gemm(m, enc.*, m.act, b.fc2, m.y, m.hidden, m.mlp); m.lap(pass, "mlp out"); } + +test "h3 gemm: 32x64-warp products write every tile as MLX's 32x32 band of 4 does, across a band edge and a ragged tile" { + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + if (!device.tensorUnits()) return error.SkipZigTest; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const queue = try device.queue(); + defer queue.deinit(); + const a = std.testing.allocator; + const text = try @import("source.zig").library(a, 56, 18432, 288, ""); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const whole_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_whole, false); + defer whole_pipe.deinit(); + const ragged_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_ragged, false); + defer ragged_pipe.deinit(); + const wide_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_32x64, false); + defer wide_pipe.deinit(); + const wide_ragged_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_32x64_ragged, false); + defer wide_ragged_pipe.deinit(); + const n = 256; + const k = 512; + const guard = 64 * n; // one more row tile than the product writes, which must stay untouched + var prng = std.Random.DefaultPrng.init(81); + // a whole band of 64 tiles, one tile past it, and 65 tiles plus a ragged tail + for ([_]usize{ 64 * 64 + 24, 64 * 65, 64 * 65 + 24 }) |rows| { + const whole = rows % 64 == 0; + const shared = mtl.ResourceOptions.shared; + const x = try device.buffer(rows * k * 2, shared); + defer x.deinit(); + const w = try device.buffer(n * k * 2, shared); + defer w.deinit(); + // bf16 values of magnitude [1, 2): seven random mantissa bits and a random sign + for ([_][]u16{ x.slice(u16, rows * k), w.slice(u16, n * k) }) |values| { + for (values) |*v| v.* = 0x3f80 | (prng.random().int(u16) & 0x807f); + } + const old = try device.buffer((rows * n + guard) * 2, shared); + defer old.deinit(); + const wide = try device.buffer((rows * n + guard) * 2, shared); + defer wide.deinit(); + for ([_]mtl.Buffer{ old, wide }) |d| @memset(d.slice(u16, rows * n + guard), 0xffff); // a NaN no product of these inputs makes + // MLX's geometry: 32 x 32 a warp, 256 threads; ours: 32 x 64, 128 threads + { + const cb = queue.commandBuffer(); + const enc = cb.compute(.concurrent); + product(enc, if (whole) whole_pipe else ragged_pipe, 2, x, .{ .buffer = w }, old, rows, n, k, 256); + enc.end(); + cb.commit(); + cb.wait(); + try std.testing.expect(cb.failure() == null); + } + { + const cb = queue.commandBuffer(); + const enc = cb.compute(.concurrent); + product(enc, if (whole) wide_pipe else wide_ragged_pipe, swizzle, x, .{ .buffer = w }, wide, rows, n, k, 128); + enc.end(); + cb.commit(); + cb.wait(); + try std.testing.expect(cb.failure() == null); + } + const after = wide.slice(u16, rows * n + guard); + try std.testing.expectEqualSlices(u16, old.slice(u16, rows * n + guard), after); + try std.testing.expect(std.mem.indexOfScalar(u16, after[0 .. rows * n], 0xffff) == null); + for (after[rows * n ..]) |v| try std.testing.expectEqual(@as(u16, 0xffff), v); + } +} diff --git a/zig/src/families/h3/image.zig b/zig/src/families/h3/image.zig index 4e9acb74824..7faf05f2d71 100644 --- a/zig/src/families/h3/image.zig +++ b/zig/src/families/h3/image.zig @@ -18,5 +18,6 @@ pub const Runner = prompt.Runner; pub const Vision = prompt.Vision; pub const Decoder = decoder.Decoder; +pub const most_batch = decoder.most_batch; pub const host = decoder.host; pub const vae = decoder.vae; diff --git a/zig/src/families/h3/source.zig b/zig/src/families/h3/source.zig index 59f2f03b8d5..407ab3d21d6 100644 --- a/zig/src/families/h3/source.zig +++ b/zig/src/families/h3/source.zig @@ -13,7 +13,7 @@ pub fn library(a: std.mem.Allocator, heads: usize, slots: usize, tiles: usize, d defer a.free(source); const gemm = try std.mem.replaceOwned(u8, a, gemmSource(), "#include \"../nax.h\"", sources.nax); defer a.free(gemm); - return std.mem.concat(a, u8, &.{ gemm, source }); + return std.mem.concat(a, u8, &.{ gemm, source, kernels.gemm_source }); } fn gemmSource() []const u8 { diff --git a/zig/src/hip/kernel_tests/attention.zig b/zig/src/hip/kernel_tests/attention.zig index f767f03e300..efe95dfb1b3 100644 --- a/zig/src/hip/kernel_tests/attention.zig +++ b/zig/src/hip/kernel_tests/attention.zig @@ -226,6 +226,110 @@ test "the planned decode walk over pages writes the flat walk's bits for grouped try decode(t, &rng, 16, 4, 128, 16384, &.{16381}); } +/// A round's slots in one planned walk against each row walked alone: the scores' and rows' bits, on poisoned caches. +fn slots(t: *Rig, rng: *rig.Rng, heads: usize, kv_heads: usize, span: usize, counts: []const usize, ends: []const usize) !void { + const d = 256; + const scale: f32 = 1 / @sqrt(@as(f32, d)); + var rows: usize = 0; + for (counts) |n| rows += n; + const pos = try gpa.alloc(i32, rows); + defer gpa.free(pos); + const slot = try gpa.alloc(i32, rows); + defer gpa.free(slot); + const first = try gpa.alloc(i32, counts.len); + defer gpa.free(first); + const count = try gpa.alloc(i32, counts.len); + defer gpa.free(count); + const descs = try gpa.alloc(u64, counts.len); + defer gpa.free(descs); + var bufs: std.ArrayList(DeviceBuffer) = .empty; + defer { + for (bufs.items) |*b| b.free(); + bufs.deinit(gpa); + } + const words = 4; + const nan: u16 = if (t.bf16) 0x7fc5 else 0x7e05; + const inf: u16 = if (t.bf16) 0x7f80 else 0x7c00; + var row: usize = 0; + for (counts, ends, 0..) |n, end, s| { + first[s] = @intCast(row); + count[s] = @intCast(n); + for (0..n) |i| { + pos[row + i] = @intCast(end - n + i); + slot[row + i] = @intCast(s); + } + row += n; + // the slot's own cache: a NaN key only its last row sees, an infinite one past its rows, an infinite value + const c = try Cache.make(t, rng, kv_heads, span, d); + defer c.free(); + for (0..kv_heads) |h| { + c.k[(h * span + end - 1) * d + 3 + h] = nan; + if (end < span) c.k[(h * span + end) * d + 7] = inf; + c.v[(h * span + end - n) * d + 11] = inf; + } + for ([_][]const u16{ c.k, c.v }) |src| { + const pooled = try c.pool(src, kv_heads, span, d); + defer gpa.free(pooled); + try bufs.append(gpa, try t.upload(pooled)); + } + const desc = try gpa.alloc(u64, words + (c.table.len + 1) / 2); + defer gpa.free(desc); + @memset(desc, 0); + desc[2] = at(bufs.items[bufs.items.len - 2]); + desc[3] = at(bufs.items[bufs.items.len - 1]); + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. c.table.len * 4], std.mem.sliceAsBytes(c.table)); + try bufs.append(gpa, try t.upload(desc)); + descs[s] = at(bufs.items[bufs.items.len - 1]); + } + const hq = try gpa.alloc(f32, rows * heads * d); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit(); + const zero = [_]i32{0}; + const lone = [_]i32{1}; + var ins: [8]DeviceBuffer = undefined; // q, the plan's pos, slot, first, count and descriptors, a one-row plan's + for (&ins, [_][]const u8{ std.mem.sliceAsBytes(hq), std.mem.sliceAsBytes(pos), std.mem.sliceAsBytes(slot), std.mem.sliceAsBytes(first), std.mem.sliceAsBytes(count), std.mem.sliceAsBytes(descs), std.mem.asBytes(&zero), std.mem.asBytes(&lone) }) |*b, host| { + b.* = try t.upload(host); + try bufs.append(gpa, b.*); + } + const tiles = span / 128; + const scratch = [_]usize{ rows * heads * span * 4, rows * heads * d * 4, rows * heads * 2 * 4, rows * heads * tiles * d * 4 }; + var outs: [2][4]DeviceBuffer = undefined; // the shared walk's scores and rows, then each row's alone; stats, partials + for (&outs) |*o| for (o, scratch) |*b, len| { + b.* = try t.alloc(len); + try bufs.append(gpa, b.*); + try b.fill8(0xff); + }; + const p: plan.PlanRef = .{ .rows = rows, .slots = counts.len, .args = .{ .pos = at(ins[1]), .slot = at(ins[2]), .first = at(ins[3]), .count = at(ins[4]), .desc = at(ins[5]), .pages = words, .pool = @intCast(span / page) } }; + const s = t.stream.handle; + try t.on.planCausal(at(ins[0]), at(outs[0][1]), at(outs[0][0]), at(outs[0][2]), at(outs[0][3]), p, 0, heads, kv_heads, d, span, scale, t.kind(), s); + // row r alone: a one-row plan over its slot, its q, scores and output at row r's place + for (0..rows) |r| { + const desc = at(ins[5]) + 8 * @as(usize, @intCast(slot[r])); + const one: plan.PlanRef = .{ .rows = 1, .slots = 1, .args = .{ .pos = at(ins[1]) + 4 * r, .slot = at(ins[6]), .first = at(ins[6]), .count = at(ins[7]), .desc = desc, .pages = words, .pool = @intCast(span / page) } }; + try t.on.planCausal(at(ins[0]) + r * heads * d * 4, at(outs[1][1]) + r * heads * d * 4, at(outs[1][0]) + r * heads * span * 4, at(outs[1][2]), at(outs[1][3]), one, 0, heads, kv_heads, d, span, scale, t.kind(), s); + } + try t.stream.synchronize(); + for (0..2) |i| { + const shared = try rig.download(u32, outs[0][i]); + defer gpa.free(shared); + const alone = try rig.download(u32, outs[1][i]); + defer gpa.free(alone); + try std.testing.expectEqualSlices(u32, alone, shared); + } +} + +test "a round's slots in one planned walk write each row's bits walked alone, a slot's rows sharing a read of its keys" { + const t = try Rig.open(1 << 20); + defer t.close(); + var rng: rig.Rng = .{ .state = 0x5107 }; + // slots of 3, 1, 2 and 4 rows: at the span's end, mid-span, across a block's edge, at the span's start + try slots(t, &rng, 16, 2, 32768, &.{ 3, 1, 2, 4 }, &.{ 32768, 9001, 16385, 4 }); + try slots(t, &rng, 24, 4, 16384, &.{ 1, 4, 3 }, &.{ 16384, 130, 8195 }); + // every slot one row (streams with no drafts), and slots of 1, 2, 3 and 4 rows together + try slots(t, &rng, 16, 2, 32768, &.{ 1, 1, 1, 1 }, &.{ 32768, 9001, 16385, 1 }); + try slots(t, &rng, 24, 4, 32768, &.{ 2, 1, 1, 3, 1, 4 }, &.{ 32768, 20000, 16385, 9001, 128, 4 }); +} + /// 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; diff --git a/zig/src/hip/kernels.zig b/zig/src/hip/kernels.zig index 69ce080ebb0..e2af8c14e25 100644 --- a/zig/src/hip/kernels.zig +++ b/zig/src/hip/kernels.zig @@ -20,6 +20,7 @@ pub const Group = enum { qwen_vision, draft, exl3, + plan_rows, }; pub const group_count = @typeInfo(Group).@"enum".field_names.len; diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 2bdad452847..1429108ea29 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -52,6 +52,8 @@ pub const exl3 = @import("launches/exl3.zig"); pub const ConvArgs = conv.ConvArgs; pub const PlanArgs = plan.PlanArgs; pub const PlanRef = plan.PlanRef; +/// Rows of one slot a block of the shared-row score kernels takes. +pub const score_rows = plan.score_rows; pub const PlanKeep = plan.Keep; /// The stream tile's columns a lane, for launches that copy its geometry. pub const stream_pick = @import("launches/stream_pick.zig"); @@ -126,6 +128,9 @@ pub const Launcher = struct { score2_act: [2]Function, score256: [2]Function, // d 256 on long spans, kScoreSteps steps a block score256_act: [2]Function, + /// score256, q fp32, in a multi-row launch (plan_rows.hip): one-row slots' rows, then the others' chunks + score256_lone: [2]Function, + score256_rows: [2]Function, sum_act: Function, attend: [2]Function, apply: [2]Function, @@ -205,6 +210,7 @@ pub const Launcher = struct { const pre = l.mods[@backingInt(kernels.Group.prefill)]; const dec = l.mods[@backingInt(kernels.Group.decode)]; const pl = l.mods[@backingInt(kernels.Group.plan)]; + const plr = l.mods[@backingInt(kernels.Group.plan_rows)]; l.fuse = choices.fuse; l.wide = choices.wide; l.edge = edge_pass; @@ -220,6 +226,8 @@ pub const Launcher = struct { .score2_act = .{ try pl.function("tf_plan_score2_act_f16"), try pl.function("tf_plan_score2_act_bf16") }, .score256 = .{ try pl.function("tf_plan_score256_f16"), try pl.function("tf_plan_score256_bf16") }, .score256_act = .{ try pl.function("tf_plan_score256_act_f16"), try pl.function("tf_plan_score256_act_bf16") }, + .score256_lone = .{ try plr.function("tf_plan_lone_score256_f16"), try plr.function("tf_plan_lone_score256_bf16") }, + .score256_rows = .{ try plr.function("tf_plan_rows_score256_f16"), try plr.function("tf_plan_rows_score256_bf16") }, .sum_act = try pl.function("tf_sum_partials_act"), .attend = .{ try pl.function("tf_plan_attend_f16"), try pl.function("tf_plan_attend_bf16") }, .apply = .{ try pl.function("tf_plan_apply_f16"), try pl.function("tf_plan_apply_bf16") }, @@ -391,6 +399,7 @@ pub const Launcher = struct { pub const planKvWrite = plan.planKvWrite; pub const planCausal = plan.planCausal; pub const planCausalAs = plan.planCausalAs; + pub const planScore = plan.planScore; pub const planKvWriteAct = plan.planKvWriteAct; pub const planTap = plan.planTap; pub const tapRows = plan.tapRows; diff --git a/zig/src/hip/launches/plan.zig b/zig/src/hip/launches/plan.zig index f9f86d428b6..f1e6a4afd5b 100644 --- a/zig/src/hip/launches/plan.zig +++ b/zig/src/hip/launches/plan.zig @@ -98,6 +98,11 @@ const score_keys_short = 2; const score_span = 16384; /// Steps of its warps' keys a tf_plan_score256_* block walks (plan.hip's kScoreSteps). const score_steps = 8; +/// Rows of one slot a tf_plan_rows_score256_* block scores from one read of their keys (plan_rows.hip's kRows). +pub const score_rows = 2; + +/// Which blocks score a walk's rows: a block a row, or a slot's rows in chunks of `score_rows` a block. +pub const Rows = enum { one, shared }; /// 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 { @@ -123,7 +128,7 @@ pub fn planCausalAs( act: bool, 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"); + try planScore(l, q, scores, p, layer, heads, kv_heads, d, span, scale, kind, act, roundRows(p.rows), s); const which: usize = @intCast(kind - 1); const rows = p.rows; const tiles: c_int = @intCast(cdiv(span, 128)); @@ -132,28 +137,6 @@ pub fn planCausalAs( 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); - // four warps a block score their keys for the block's heads; short spans take fewer keys a warp to fill the card - const long = span >= score_span; - const keys: usize = if (long) score_keys else score_keys_short; - // d = 256 (the Qwen checkpoints) on long spans takes its own kernels, a block walking score_steps steps - const wide = long and d == 256; - const fns = if (wide) (if (act) l.plan.score256_act else l.plan.score256) else if (act) (if (long) l.plan.score_act else l.plan.score2_act) else if (long) l.plan.score else l.plan.score2; - const steps: usize = if (wide) score_steps else 1; - try l.go(fns[which], dim(cdiv(span, 4 * keys * steps), blocks, rows), dim(128, 1, 1), @intCast(group * d * 4), s, &a); var b: Args = .{}; try b.add(scores); try b.add(stats); @@ -171,7 +154,7 @@ pub fn planCausalAs( try c.add(d_c); try c.add(p.args); try c.add(layer_c); - const apply = @divExact(heads, applyGroup(group, @intCast(tiles), heads, rows)); + const apply = @divExact(heads, applyGroup(scoreGroup(heads, kv_heads), @intCast(tiles), heads, rows)); try l.go(l.plan.apply[which], dim(tiles, apply, rows), dim(256, 1, 1), 0, s, &c); var e: Args = .{}; try e.add(partials); @@ -182,6 +165,71 @@ pub fn planCausalAs( try l.go(if (act) l.plan.sum_act else l.sum_partials, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &e); } +/// The score blocks of a walk's launch: one-row launches keep a block a row, wider ones share a slot's key loads. +fn roundRows(rows: usize) Rows { + return if (rows > 1) .shared else .one; +} + +/// Query heads a score block takes, of one KV head (at most plan.hip's kMaxGroup): the cache is read once for them. +fn scoreGroup(heads: usize, kv_heads: usize) usize { + var group = @divExact(heads, kv_heads); + while (group > 16) group = @divExact(group, smallestFactor(group)); + return group; +} + +/// Rows a score block works: a chunk of its slot's when `rows` shares them at d = 256 on long spans with q fp32. +fn blockRows(rows: Rows, d: usize, span: usize, act: bool) usize { + return if (rows == .shared and d == 256 and span >= score_span and !act) score_rows else 1; +} + +/// planCausalAs's score step: each row's scores (rows, heads, span) fp32 against its slot's keys, -inf past its own. +pub fn planScore( + l: *const Launcher, + q: u64, + scores: u64, + p: PlanRef, + layer: usize, + heads: usize, + kv_heads: usize, + d: usize, + span: usize, + scale: f32, + kind: c_int, + act: bool, + rows: Rows, + 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 group = scoreGroup(heads, kv_heads); + var a: Args = .{}; + try a.add(q); + try a.add(scores); + 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(p.args); + try a.add(@as(c_int, @intCast(layer))); + // four warps a block score their keys for the block's heads; short spans take fewer keys a warp to fill the card + const long = span >= score_span; + const keys: usize = if (long) score_keys else score_keys_short; + // d = 256 (the Qwen checkpoints) on long spans takes its own kernels, a block walking score_steps steps + const wide = long and d == 256; + const steps: usize = if (wide) score_steps else 1; + const grid = dim(cdiv(span, 4 * keys * steps), @divExact(heads, group), p.rows); + const lds: u32 = @intCast(group * d * 4); + const chunk = blockRows(rows, d, span, act); + if (chunk > 1) { + // the rows of one-row slots at the one-row kernel's occupancy, then the chunks of the others, both on this grid + try l.go(l.plan.score256_lone[which], grid, dim(128, 1, 1), lds, s, &a); + return l.go(l.plan.score256_rows[which], grid, dim(128, 1, 1), @intCast(chunk * lds), s, &a); + } + const fns = if (wide) (if (act) l.plan.score256_act else l.plan.score256) else if (act) (if (long) l.plan.score_act else l.plan.score2_act) else if (long) l.plan.score else l.plan.score2; + try l.go(fns[which], grid, dim(128, 1, 1), lds, s, &a); +} + /// Keys the one-block walk (`planAttend`) takes at most. pub const attend_span = 4096; @@ -326,6 +374,19 @@ pub fn planGdnReplay(l: *const Launcher, keep: u64, p: PlanRef, key_heads: usize try l.go(l.plan.gdn_replay[wide], dim(@divExact(dv, 8), value_heads, p.slots * layers), dim(32, 8, 1), 0, s, &a); } +test "a slot's rows share the score's key loads only past one row, at d 256 on long spans with q fp32" { + const std = @import("std"); + try std.testing.expectEqual(Rows.one, roundRows(1)); + try std.testing.expectEqual(Rows.shared, roundRows(2)); + try std.testing.expectEqual(@as(usize, score_rows), blockRows(roundRows(4), 256, score_span, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(roundRows(1), 256, 1 << 18, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(.shared, 256, score_span - 1, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(.shared, 128, 1 << 18, false)); + try std.testing.expectEqual(@as(usize, 1), blockRows(.shared, 256, 1 << 18, true)); + try std.testing.expectEqual(@as(usize, 8), scoreGroup(16, 2)); + try std.testing.expectEqual(@as(usize, 16), scoreGroup(64, 2)); +} + test "a small walk splits the heads of a KV head, a wide one keeps them together" { const std = @import("std"); try std.testing.expectEqual(@as(usize, 1), applyGroup(16, 1, 32, 1)); diff --git a/zig/tests/contract/metal_bolt.zig b/zig/tests/contract/metal_bolt.zig index 16bbefd8946..f0d96be4beb 100644 --- a/zig/tests/contract/metal_bolt.zig +++ b/zig/tests/contract/metal_bolt.zig @@ -24,7 +24,7 @@ fn gemvDepth(s: c.Shape) usize { pub const Mut = struct { name: []const u8, find: []const u8, with: []const u8, gate: g.Gate }; /// `text` with every `m.find` replaced (the substitution must land, or the control proves nothing). -fn mutated(a: std.mem.Allocator, text: []const u8, m: Mut) ![]u8 { +pub fn mutated(a: std.mem.Allocator, text: []const u8, m: Mut) ![]u8 { if (std.mem.indexOf(u8, text, m.find) == null) return error.ControlDidNotApply; return std.mem.replaceOwned(u8, a, text, m.find, m.with); } diff --git a/zig/tests/contract/metal_h3.zig b/zig/tests/contract/metal_h3.zig index 76f28aa2984..cc26857f5f4 100644 --- a/zig/tests/contract/metal_h3.zig +++ b/zig/tests/contract/metal_h3.zig @@ -2,14 +2,16 @@ const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); +const sources = @import("kernel_sources"); const h3k = @import("h3_kernels"); const rig_ = @import("rig.zig"); const ref = @import("metal_h3_ref.zig"); +const bolt = @import("metal_bolt.zig"); const c = contract.spec; const g = contract.gates; -pub const Which = enum { rows_in, rows_out, norm, final_norm, gate_add, gate_mix, swiglu, swiglu_gate_first, heads, pool, tile_scores, coarse, attention, modulation }; +pub const Which = enum { rows_in, rows_out, norm, final_norm, gate_add, gate_mix, swiglu, swiglu_gate_first, heads, pool, tile_scores, coarse, attention, modulation, product, product_ragged }; /// The geometry the test kernels are compiled for: two heads, up to 16 tiles of 64 slots. const heads = 2; @@ -42,6 +44,7 @@ fn none(_: c.Shape) usize { } const soft_why = "softmax weights in [0, 1], rounded to bf16 before the value product: the bf16 output hides the sums' error"; +const mlx_gemm = "MLX's gemm_nax (32 x 32 a warp, swizzle 2)"; const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; pub fn spec(w: Which) c.Spec { @@ -61,6 +64,9 @@ pub fn spec(w: Which) c.Spec { .coarse => .{ .name = "metal h3 pooled branch h3_coarse", .accum = .f32, .depth = tileChain, .ops = 6, .out = .f32, .tiles = .{ .{ .size = 4 }, .{}, .{} }, .served = &.{.{ .rows = tiles, .n = 128, .k = tiles }}, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = soft_why } }, .modulation => .{ .name = "metal h3 AdaLN tables h3_modulation", .accum = .f32, .depth = laneChain, .ops = 1, .out = .bf16, .tiles = .{ .{}, .{ .size = 18 * 32, .step = 18, .min = 18 }, .{ .size = 32 } }, .served = &.{ .{ .rows = 16, .n = 18 * 64, .k = 2688 }, .{ .rows = 3, .n = 18 * 16, .k = 2688 } } }, .attention => .{ .name = "metal h3 routed attention h3_attention", .accum = .f32, .depth = attnChain, .ops = 8, .mids = 1, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = tiles, .n = 128, .k = tiles * 64 }, .{ .rows = tiles, .n = 128, .k = 6 * 64 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = soft_why } }, + // q at 65 row tiles, one past a band of 64; attention out at one tile (FastH3 and MiniMax-H3-Image alike) + .product => .{ .name = "metal h3 product h3_gemm_32x64", .accum = .f32, .depth = kChain, .out = .bf16, .replaces = mlx_gemm, .served = &.{ .{ .rows = 4160, .n = 7168, .k = 5376 }, .{ .rows = 64, .n = 5376, .k = 7168 } } }, + .product_ragged => .{ .name = "metal h3 product ragged h3_gemm_32x64_ragged", .accum = .f32, .depth = kChain, .out = .bf16, .replaces = mlx_gemm, .tiles = .{ .{ .size = 64 }, .{}, .{} }, .served = &.{ .{ .rows = 4184, .n = 7168, .k = 5376 }, .{ .rows = 24, .n = 5376, .k = 7168 } } }, }; } @@ -80,6 +86,28 @@ fn function(w: Which) []const u8 { .coarse => "h3_coarse", .attention => "h3_attention", .modulation => "h3_modulation", + .product => h3k.gemm_32x64, + .product_ragged => h3k.gemm_32x64_ragged, + }; +} + +/// The MLX entry point a product replaced, launched beside it on the same inputs. +fn baseline(w: Which) ?[]const u8 { + return switch (w) { + .product => h3k.gemm_whole, + .product_ragged => h3k.gemm_ragged, + else => null, + }; +} + +/// A product's planted control: its 32-deep K steps reversed, so its bytes must leave MLX's at the shapes gate. +fn control(w: Which) ?bolt.Mut { + const ks = "for (int kk = 0; kk < 256; kk += 32) h3_step<"; + const back = "for (int kk = 224; kk >= 0; kk -= 32) h3_step<"; + return switch (w) { + .product => .{ .name = "control: metal h3 product h3_gemm_32x64, whole tiles' K steps reversed", .find = ks ++ "false>", .with = back ++ "false>", .gate = .shapes }, + .product_ragged => .{ .name = "control: metal h3 product ragged h3_gemm_32x64_ragged, edge tile's K steps reversed", .find = ks ++ "true>", .with = back ++ "true>", .gate = .shapes }, + else => null, }; } @@ -90,6 +118,9 @@ pub const H3 = struct { rig: rig_.Rig, which: Which, pipe: mtl.Pipeline, + mut: ?bolt.Mut = null, + /// A product's replaced MLX kernel. + base: ?mtl.Pipeline = null, shape: c.Shape = undefined, arena: std.heap.ArenaAllocator, in: ref.In = .{ .rows = 0, .n = 0, .k = 0 }, @@ -99,20 +130,39 @@ pub const H3 = struct { fresh: []const u8 = &.{}, outs: usize = 0, - pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which) !H3 { - const src = try std.mem.concat(a, u8, &.{ defines, h3k.source }); - defer a.free(src); - return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = which, .pipe = try rig_.pipeline(device, src, function(which)), .arena = std.heap.ArenaAllocator.init(a) }; + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which, mut: ?bolt.Mut) !H3 { + const rig: rig_.Rig = .{ .a = a, .device = device, .queue = queue }; + const mlx = baseline(which) orelse { + const src = try std.mem.concat(a, u8, &.{ defines, h3k.source }); + defer a.free(src); + return .{ .a = a, .rig = rig, .which = which, .pipe = try rig_.pipeline(device, src, function(which)), .arena = std.heap.ArenaAllocator.init(a) }; + }; + // the products' library as source.zig builds it: gemm_nax with nax.h inlined, then h3_gemm + const gemm = for (sources.prefill) |f| { + if (std.mem.eql(u8, f.name, "gemm_nax")) break f.text; + } else return error.UnknownSource; + const nax = try std.mem.replaceOwned(u8, a, gemm, "#include \"../nax.h\"", sources.nax); + defer a.free(nax); + const both = try std.mem.concat(a, u8, &.{ nax, h3k.gemm_source }); + defer a.free(both); + const src = if (mut) |m| try bolt.mutated(a, both, m) else both; + defer if (mut != null) a.free(src); + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const pipe = try mtl.Pipeline.init(device, lib, function(which), false); + errdefer pipe.deinit(); + return .{ .a = a, .rig = rig, .which = which, .pipe = pipe, .mut = mut, .base = try mtl.Pipeline.init(device, lib, mlx, false), .arena = std.heap.ArenaAllocator.init(a) }; } pub fn deinit(self: *H3) void { self.rig.deinit(); self.pipe.deinit(); + if (self.base) |b| b.deinit(); self.arena.deinit(); } pub fn kernel(self: *H3) g.Kernel { - return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + return .{ .spec = bolt.under(spec(self.which), self.mut), .ctx = self, .vt = &vt, .control = if (self.mut) |m| m.gate else null }; } const vt = g.hooks(H3); @@ -163,6 +213,12 @@ pub const H3 = struct { self.nbufs += 1; } + /// The replaced kernel's output: device memory the gates neither feed nor read. + pub fn baseOutput(self: *H3, bytes: usize) !void { + self.bufs[self.nbufs] = try self.rig.scratch(bytes); + self.nbufs += 1; + } + pub fn prepare(self: *H3, shape: c.Shape, fill: g.Fill, seed: u64) !bool { self.rig.reset(); _ = self.arena.reset(.retain_capacity); @@ -188,7 +244,7 @@ pub const H3 = struct { const scratch = try self.a.alloc(f64, @max(2 * self.in.n, 1024) + self.in.k); defer self.a.free(scratch); switch (self.which) { - .rows_in, .rows_out => ref.dot(self.in, s, scratch, want, mag), + .rows_in, .rows_out, .product, .product_ragged => ref.dot(self.in, s, scratch, want, mag), .norm => ref.norm(self.in, s, scratch, want, mag), .final_norm => ref.finalNorm(self.in, s, scratch, want, mag), .gate_add => ref.gated(self.in, false, want, mag), @@ -213,6 +269,10 @@ pub const H3 = struct { defer self.a.free(mag); return self.compute(.{ .acc = acc, .order = order }, out, mag); } + + pub fn replaced(self: *H3) ![]const u8 { + return @import("metal_h3_prep.zig").replaced(self); + } }; /// Every H3 kernel, on a device with tensor units: metal_main.zig's registration. @@ -227,14 +287,19 @@ pub const Suite = struct { if (!s.device.tensorUnits()) return; for (std.enums.values(Which)) |w| { if (only) |o| if (std.mem.indexOf(u8, spec(w).name, o) == null) continue; - const x = try s.a.create(H3); - errdefer s.a.destroy(x); - x.* = try H3.init(s.a, s.device, s.queue, w); - try s.list.append(s.a, x); - try s.kernels.append(s.a, x.kernel()); + try s.add(w, null); + if (control(w)) |m| try s.add(w, m); } } + fn add(s: *Suite, w: Which, mut: ?bolt.Mut) !void { + const x = try s.a.create(H3); + errdefer s.a.destroy(x); + x.* = try H3.init(s.a, s.device, s.queue, w, mut); + try s.list.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + pub fn deinit(s: *Suite) void { for (s.list.items) |x| { x.deinit(); diff --git a/zig/tests/contract/metal_h3_prep.zig b/zig/tests/contract/metal_h3_prep.zig index 30ab6fabcbb..74907c714ad 100644 --- a/zig/tests/contract/metal_h3_prep.zig +++ b/zig/tests/contract/metal_h3_prep.zig @@ -25,6 +25,11 @@ fn mirror(x: []f64, w: []f64, k: usize, rows: usize, n: usize) void { }; } +/// A product's launched rows: the whole kernel runs whole 64-row tiles, past the rows a gate checks. +fn launched(self: *const H3) usize { + return if (self.which == .product) (self.shape.rows + 63) / 64 * 64 else self.shape.rows; +} + /// Tile sizes: most whole, some short (the last rows of a segment), never empty. fn sizes(self: *H3, n: usize, rng: std.Random) ![]i32 { const v = try self.arena.allocator().alloc(i32, n); @@ -211,9 +216,26 @@ pub fn prepare(self: *H3, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { self.outs = rows * heads * 128; return true; }, + .product, .product_ragged => { + // gate 4's mirror stays exact in fp32 (|terms| <= 32^2, k / 2 of one sign) and passes fp16's range + const lo: f64 = if (stress) -4 else -1; + const x = try self.values(s.rows * s.k, lo, -lo, fill, rng, true, true); + const w = try self.values(s.n * s.k, lo, -lo, fill, rng, true, false); + if (stress) mirror(x, w, s.k, s.rows, s.n); + const pad = try self.values((launched(self) - s.rows) * s.k, lo, -lo, .random, rng, true, false); + const bias = try al.alloc(f64, s.n); + @memset(bias, 0); + self.in.a = x; + self.in.b = w; + self.in.d = bias; + try self.upload(if (pad.len == 0) x else try std.mem.concat(al, f64, &.{ x, pad }), true); + try self.upload(w, true); + try self.output(launched(self) * s.n * 2); + try self.baseOutput(launched(self) * s.n * 2); + }, } self.outs = switch (self.which) { - .rows_in, .rows_out, .swiglu, .swiglu_gate_first, .modulation => s.rows * s.n, + .rows_in, .rows_out, .swiglu, .swiglu_gate_first, .modulation, .product, .product_ragged => s.rows * s.n, .norm => 2 * s.rows * s.n, .final_norm, .gate_add, .gate_mix => s.rows * s.n, .heads => 3 * heads * slots * 128, @@ -314,5 +336,33 @@ pub fn launch(self: *H3, e: mtl.ComputeEncoder) !void { bind(self, e, 6, 8); e.dispatchGroups(mtl.Size.of(s.rows, heads, 1), mtl.Size.of(256, 1, 1)); }, + .product, .product_ragged => product(self, e, self.pipe, 2, 6, 128), } } + +/// block.zig's product launch: x, w, the sizes, d into buffer `out`; `swizzle` and `threads` as the kernel runs them. +fn product(self: *H3, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, out: usize, swizzle: u5, threads: usize) void { + const s = self.shape; + const band = @as(usize, 1) << swizzle; + const tn = s.n / 128; + const tm = (launched(self) + 63) / 64; + var p: [16]i32 = @splat(0); + for ([_]usize{ launched(self), s.n, s.k, s.k, s.k, s.n, tn, tm, swizzle, s.k / 256 }, 0..) |v, i| p[i] = @intCast(v); + e.setPipeline(pipe); + bind(self, e, 0, 0); + bind(self, e, 1, 1); + e.setBytes(std.mem.asBytes(&p), 2); + bind(self, e, out, 3); + e.dispatchGroups(mtl.Size.of(tn * band, (tm + band - 1) / band, 1), mtl.Size.of(32, 4, threads / 128)); +} + +/// The replaced MLX kernel's bytes on the prepared inputs, written to the scratch buffer. +pub fn replaced(self: *H3) ![]const u8 { + const len = launched(self) * self.shape.n * 2; + const out = self.rig.bytes(self.bufs[3], len); + @memset(out, 0xff); + const p = self.rig.begin(); + product(self, p.e, self.base.?, 3, 2, 256); + try self.rig.finish(p); + return out; +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index e8aa170afdd..bb01e76b36e 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -273,11 +273,12 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp if (!assemble) return undefined; text = sources.core_contract_controls; if (has(fun, "big_tg")) head = "#define TF_CTL_BIG_TG 1\n"; - } else if (std.mem.startsWith(u8, d.name, "h3 gemm ") or std.mem.startsWith(u8, d.name, "nemotron ssd gemm ")) { + } else if (std.mem.startsWith(u8, d.name, "h3 gemm ") or std.mem.startsWith(u8, d.name, "h3 product ") or std.mem.startsWith(u8, d.name, "nemotron ssd gemm ")) { if (!assemble) return undefined; - text = for (sources.prefill) |f| { + const gemm = for (sources.prefill) |f| { if (std.mem.eql(u8, f.name, "gemm_nax")) break f.text; } else return error.UnknownLaunch; + text = if (std.mem.startsWith(u8, d.name, "h3 product ")) try std.mem.concat(a, u8, &.{ gemm, @import("h3_kernels").gemm_source }) else gemm; frags = true; } else if (std.mem.startsWith(u8, d.name, "flashnext prompt attention ")) { if (!assemble) return undefined; diff --git a/zig/tests/h3_image_decoder.zig b/zig/tests/h3_image_decoder.zig index 221aeac541e..87cc3ae79f0 100644 --- a/zig/tests/h3_image_decoder.zig +++ b/zig/tests/h3_image_decoder.zig @@ -18,8 +18,8 @@ const usage = \\ ; -/// Tiles a pass decodes at most. -const batch = 16; +/// Tiles a pass decodes at most: the decoder's scratch is sized for this many, and every tile's pixels are independent. +const batch = dec.most_batch; fn read(init: std.process.Init, a: std.mem.Allocator, path: []const u8, most: usize) ![]u8 { return std.Io.Dir.cwd().readFileAlloc(init.io, path, a, .limited(most)) catch |err| { diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index 34a466f3f2d..f37d581d794 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -13,6 +13,7 @@ const mamba_k = @import("contract_mamba.zig"); const scan_k = @import("contract_scan.zig"); const moe_k = @import("contract_nemo_moe.zig"); const walk_k = @import("contract_walk.zig"); +const walk_rows_k = @import("contract_walk_rows.zig"); const prefill_k = @import("contract_prefill.zig"); const add_rms_k = @import("contract_add_rms.zig"); const tail_k = @import("contract_tail.zig"); @@ -200,6 +201,11 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { for (&qwen_walks, 0..) |*w, i| w.* = .qwenAt(a, &r, s, &l, i); defer for (&qwen_walks) |*w| w.deinit(); for (&qwen_walks) |*w| try kernels.append(a, w.kernel()); + // d = 256's score of a launch's slots, a slot's rows on one read of its keys: each head group, both kinds; controls + var row_walks: [walk_rows_k.count_all]walk_rows_k.RowsScore = undefined; + for (&row_walks, 0..) |*w, i| w.* = .init(a, &r, s, &l, i); + defer for (&row_walks) |*w| w.deinit(); + for (&row_walks) |*w| try kernels.append(a, w.kernel()); var prefills: [2]prefill_k.Prefill = undefined; for (&prefills, [_]bool{ true, false }) |*p, paged| p.* = .init(a, &r, s, &l, paged); defer for (&prefills) |*p| p.deinit(); diff --git a/zig/tests/hip/contract_walk_rows.zig b/zig/tests/hip/contract_walk_rows.zig new file mode 100644 index 00000000000..fb15839473a --- /dev/null +++ b/zig/tests/hip/contract_walk_rows.zig @@ -0,0 +1,418 @@ +//! plan_rows.hip's two-launch score step under the contract: slots, poisoned caches, tf_plan_score256_*'s bits. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const sums = contract.rows; + +const page = 64; +const d = 256; +/// Spans the d = 256 score kernels take from (launches/plan.zig's score_span). +const long_span = 16384; +/// Gate 4's keys repeat every `period` positions, so its float64 sums are worked once a period. +const period = 61; + +/// Query heads over KV heads: Qwen3.6-35B-A3B's 16 over 2 and Qwen3.8-27B's 24 over 4. +pub const Case = struct { heads: usize, kv: usize }; +pub const cases = [_]Case{ .{ .heads = 16, .kv = 2 }, .{ .heads = 24, .kv = 4 } }; + +/// served[0] takes gates 1-2 (slots of 3, 1 and 4 rows, a span with a scalar tail), gate 4 the 262,144-key span. +const served = blk: { + var t: [cases.len][7]c.Shape = undefined; + for (cases, 0..) |x, i| t[i] = .{ + .{ .rows = 8, .n = x.heads, .k = 16387 }, + .{ .rows = 16, .n = x.heads, .k = 65536 }, + .{ .rows = 4, .n = x.heads, .k = 131072 }, + .{ .rows = 2, .n = x.heads, .k = 262144 }, + .{ .rows = 64, .n = x.heads, .k = 16384 }, + .{ .rows = 5, .n = x.heads, .k = 65536 }, + .{ .rows = 7, .n = x.heads, .k = 131072 }, + }; + break :blk t; +}; + +/// The real launches, or a control's: chunks led across slots (first 0, count every row), or the chunks' launch alone. +pub const Fault = enum { none, crossing, alone }; + +/// The registrations: each case in fp16 and bf16 caches, then each control in each. +pub const count_all = 2 * cases.len + 4; + +const kernel_names = [2][]const u8{ "tf_plan_rows_score256_f16", "tf_plan_rows_score256_bf16" }; +const lone_names = [2][]const u8{ "tf_plan_lone_score256_f16", "tf_plan_lone_score256_bf16" }; +const replaced_names = [2][]const u8{ "tf_plan_score256_f16", "tf_plan_score256_bf16" }; + +/// Each case's names [case][bf16], and the controls' [bf16]. +const names = blk: { + var t: [cases.len][2][]const u8 = undefined; + for (cases, 0..) |x, i| for (0..2) |bf| { + const what = "hip {s} then {s}, {d} heads over {d}: one-row slots alone, the others' rows on one read of their keys"; + t[i][bf] = std.fmt.comptimePrint(what, .{ lone_names[bf], kernel_names[bf], x.heads, x.kv }); + }; + break :blk t; +}; +const control_names = blk: { + var t: [2][2][]const u8 = undefined; + for (0..2) |bf| { + t[0][bf] = "control: hip " ++ kernel_names[bf] ++ ", chunks led across slots (first 0, count every row)"; + t[1][bf] = "control: hip " ++ kernel_names[bf] ++ " alone, the one-row slots' launch left out"; + } + break :blk t; +}; + +/// Case `i`'s spec in kind `k`: the bits of the one-row kernel it replaces, edges at a chunk's rows and a block's keys. +pub fn spec(i: usize, k: kit.Kind, fault: Fault) c.Spec { + const bf = @intFromBool(k == .bf16); + return .{ + .name = if (fault == .none) names[i][bf] else control_names[@intFromBool(fault == .alone)][bf], + .accum = .f32, + .depth = depth, + .ops = 1, // the scale + .out = .f32, + .replaces = replaced_names[bf], + .tiles = .{ .{ .size = hip.launches.score_rows }, .{}, .{ .size = long_span + 128, .min = long_span } }, + .served = &served[i], + }; +} + +/// A lane's eight products and sums, the five folds of the wave. +fn depth(_: c.Shape) usize { + return 2 * 8 + 5; +} + +/// Rows a slot holds: one each for an odd count from 5 (streams with no drafts), else cycling 3, 1, 4, 2. +fn counts(a: std.mem.Allocator, rows: usize) ![]usize { + var out: std.ArrayList(usize) = .empty; + const cycle: []const usize = if (rows % 2 == 1 and rows >= 5) &.{1} else &.{ 3, 1, 4, 2 }; + var left = rows; + while (left > 0) : (left -= out.items[out.items.len - 1]) try out.append(a, @min(left, cycle[out.items.len % cycle.len])); + return out.toOwnedSlice(a); +} + +/// Slot s's last row's visible keys: the span's end, mid-span, one past a block's first key, or the span's start. +fn lastVisible(s: usize, rows: usize, k: usize) usize { + const v = switch (s % 4) { + 0 => k - s / 4 * 7, + 1 => k / 2 + 5 + s / 4 * 64, + 2 => k / 4 / 128 * 128 + 1 + s / 4, + else => rows + s / 4, + }; + return std.math.clamp(v, rows, k); +} + +fn mix(x: u32) u32 { + var h = x; + h ^= h >> 16; + h *%= 0x7feb352d; + h ^= h >> 15; + h *%= 0x846ca68b; + h ^= h >> 16; + return h; +} + +/// A finite value of the kind, any sign and mantissa, magnitude in [2^-4, 2^2), as its 16 bits. +fn finite(k: kit.Kind, h: u32) u16 { + const sign: u16 = @intCast(h >> 31); + return if (k == .bf16) + sign << 15 | @as(u16, @intCast(123 + (h >> 8) % 6)) << 7 | @as(u16, @intCast(h & 0x7f)) + else + sign << 15 | @as(u16, @intCast(11 + (h >> 10) % 6)) << 10 | @as(u16, @intCast(h & 0x3ff)); +} + +/// A NaN of payload h (quiet or signaling) or an infinity of either sign, as the kind's 16 bits. +fn nonFinite(k: kit.Kind, h: u32) u16 { + const top: u16 = if (k == .bf16) 0x7f80 else 0x7c00; + const mant: u32 = if (k == .bf16) 0x7f else 0x3ff; + return switch (h % 3) { + 0 => @as(u16, @intCast((h >> 31) << 15)) | top | @as(u16, @intCast(1 + (h >> 8) % mant)), + 1 => top, + else => 0x8000 | top, + }; +} + +/// Gate 4's key element: integers in [1, 255] of either sign, the second half negated but for one, repeating. +fn stressKey(k: kit.Kind, h: usize, pos: usize, j: usize) u16 { + const r = mix(@intCast((h * period + pos % period) * 128 + j % 128)); + const v: f64 = @floatFromInt(1 + r % 255); + const x = if (r >> 31 == 1) -v else v; + var b: [2]u8 = undefined; + kit.put(k, &b, 0, if (j < 128) x else if (j == 128) 1 - x else -x); // integers of 256 or less are exact in both + return std.mem.readInt(u16, &b, .little); +} + +/// Gate 4's query element: integers in [1, 63], the second half equal to the first, so a dot is its first query. +fn stressQuery(i: usize) f64 { + return @floatFromInt(1 + mix(@intCast(i / d * 128 + i % d % 128)) % 63); +} + +fn scale() f32 { + return 1 / @sqrt(@as(f32, d)); +} + +/// shape.rows rows over slots of `counts` rows, each slot's own pages in one pool; the scores of every row and head. +pub const RowsScore = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + k: kit.Kind, + case: usize, + fault: Fault = .none, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + stress: bool = false, + q: []f64 = &.{}, // [rows][heads][d] + pool: []u16 = &.{}, // the keys in the kind, [kv][pages][page][d] + pages: usize = 0, + /// Each slot's page table, and each row's slot and visible keys. + tables: [][]u32 = &.{}, + slot: []usize = &.{}, + vis: []usize = &.{}, + plan: hip.launches.PlanRef = undefined, + /// The control's plan: every slot's first 0 and its count every row. + crossing: hip.launches.PlanRef = undefined, + q32: u64 = 0, + out: u64 = 0, + tree: u64 = 0, // the replaced kernel's scores + + /// Registration i of `count_all`: each case in fp16 then bf16 caches, then each control likewise. + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, i: usize) RowsScore { + const control = i >= 2 * cases.len; + return .{ + .rig = .{ .a = a, .r = rt, .s = s }, + .l = l, + .k = if (i % 2 == 1) .bf16 else .f16, + .case = if (control) 0 else i / 2, + .fault = if (!control) .none else if (i < 2 * cases.len + 2) .crossing else .alone, + .arena = .init(a), + }; + } + + pub fn deinit(self: *RowsScore) void { + self.arena.deinit(); + self.rig.deinit(); + } + + /// A control keeps its case's spec under its own name and must go red at gate 3. + pub fn kernel(self: *RowsScore) g.Kernel { + return .{ .spec = spec(self.case, self.k, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault != .none) .shapes else null }; + } + + const vt = g.hooks(RowsScore); + + /// Element 0 of position `pos` of KV head `h` in slot `s`'s pages. + fn at(self: *const RowsScore, s: usize, h: usize, pos: usize) usize { + return ((h * self.pages + self.tables[s][pos / page]) * page + pos % page) * d; + } + + pub fn prepare(self: *RowsScore, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const kv = cases[self.case].kv; + if (shape.rows == 0 or shape.k < long_span or shape.n % kv != 0) return false; + self.rig.reset(); + _ = self.arena.reset(.free_all); + self.shape = shape; + self.stress = fill == .stress; + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const keys = shape.k; + const per = try counts(a, shape.rows); + const slots = per.len; + // each slot's rows at consecutive positions up to its last row's, and its pages, permuted over one pool + self.slot = try a.alloc(usize, shape.rows); + self.vis = try a.alloc(usize, shape.rows); + const first = try a.alloc(i32, slots); + const many = try a.alloc(i32, slots); + const need = try a.alloc(usize, slots); + var row: usize = 0; + self.pages = 0; + for (per, 0..) |n, s| { + const last = lastVisible(s, n, keys); + first[s] = @intCast(row); + many[s] = @intCast(n); + for (0..n) |i| { + self.slot[row + i] = s; + self.vis[row + i] = last - (n - 1) + i; + } + row += n; + need[s] = (last + page - 1) / page; + self.pages += need[s]; + } + self.tables = try a.alloc([]u32, slots); + var next: usize = 0; + for (self.tables, need) |*t, n| { + t.* = try a.alloc(u32, n); + for (t.*, next..) |*p, i| p.* = @intCast(if (self.pages % 5 == 0) self.pages - 1 - i else (i * 5 + 3) % self.pages); + next += n; + } + self.pool = try a.alloc(u16, kv * self.pages * page * d); + const salt: u32 = @truncate(seed); + for (self.tables, 0..) |t, s| for (0..kv) |h| for (0..t.len * page) |pos| { + const row_at = self.at(s, h, pos); + const hk = mix(@as(u32, @truncate((s * kv + h) * keys + pos)) *% 0x27d4eb2f +% salt); + for (self.pool[row_at..][0..d], 0..) |*x, j| { + x.* = if (self.stress) stressKey(self.k, h, pos, j) else finite(self.k, mix(hk ^ @as(u32, @intCast(j)) *% 0x9e3779b1)); + } + // one key in 41 holds a NaN or an infinity at one element, seen by some rows and past others + if (!self.stress and hk % 41 == 0) self.pool[row_at + hk / 41 % d] = nonFinite(self.k, mix(hk)); + }; + if (!self.stress) for (per, need, 0..) |n, pages, s| { + const last = lastVisible(s, n, keys); + // the key only a slot's last row sees, and the one past all its rows, both non-finite + for ([_]usize{ last - 1, last }) |pos| if (pos < pages * page) for (0..kv) |h| { + self.pool[self.at(s, h, pos) + (pos + h) % d] = nonFinite(self.k, mix(@intCast(pos + h))); + }; + }; + // queries: fp32 values in [-1, 1) away from zero, gate 4's integers, or one NaN at gate 1 + self.q = try a.alloc(f64, shape.rows * shape.n * d); + for (self.q, 0..) |*v, i| { + const x = rng.float(f64) * 2 - 1; + v.* = if (self.stress) stressQuery(i) else @as(f32, @floatCast(if (@abs(x) < 0x1p-8) 0.5 else x)); + } + if (fill == .nonfinite) self.q[0] = std.math.nan(f64); // row 0, head 0 + const qb = try kit.f32Bytes(a, self.q); + // quiet NaNs of distinct payloads in row 1's head 1 + if (!self.stress and shape.rows > 1) for (0..4) |e| { + const i = (shape.n + 1) * d + e * 37; + std.mem.writeInt(u32, qb[4 * i ..][0..4], 0x7fc00000 | @as(u32, @intCast(e * 0x1235 + 1)), .little); + self.q[i] = std.math.nan(f64); + }; + self.q32 = try self.rig.input(qb); + const pool = try self.rig.input(std.mem.sliceAsBytes(self.pool)); + // each slot's descriptor [cached, kept, k pool, v pool], then its page table + const words = 4; + const descs = try a.alloc(u64, slots); + for (self.tables, descs) |t, *dev| { + const desc = try a.alloc(u64, words + (t.len + 1) / 2); + @memset(desc, 0); + desc[2] = pool; + @memcpy(std.mem.sliceAsBytes(desc[words..])[0 .. t.len * 4], std.mem.sliceAsBytes(t)); + dev.* = try self.rig.input(std.mem.sliceAsBytes(desc)); + } + const pos = try a.alloc(i32, shape.rows); + const slot = try a.alloc(i32, shape.rows); + for (pos, slot, self.vis, self.slot) |*p, *s, v, x| { + p.* = @intCast(v - 1); + s.* = @intCast(x); + } + const args: hip.launches.PlanArgs = .{ + .pos = try self.rig.input(std.mem.sliceAsBytes(pos)), + .slot = try self.rig.input(std.mem.sliceAsBytes(slot)), + .first = try self.rig.input(std.mem.sliceAsBytes(first)), + .count = try self.rig.input(std.mem.sliceAsBytes(many)), + .desc = try self.rig.input(std.mem.sliceAsBytes(descs)), + .pages = words, + .pool = @intCast(self.pages), + }; + self.plan = .{ .rows = shape.rows, .slots = slots, .args = args }; + self.crossing = self.plan; + if (self.fault == .crossing) { + const zero = try a.alloc(i32, slots); + @memset(zero, 0); + const all = try a.alloc(i32, slots); + @memset(all, @intCast(shape.rows)); + self.crossing.args.first = try self.rig.input(std.mem.sliceAsBytes(zero)); + self.crossing.args.count = try self.rig.input(std.mem.sliceAsBytes(all)); + } + self.out = try self.rig.output(self.count() * 4); + self.tree = try self.rig.scratch(self.count() * 4); + return true; + } + + pub fn run(self: *RowsScore) !void { + const s = self.shape; + if (self.fault == .alone) return self.chunksAlone(); + const p = if (self.fault == .crossing) self.crossing else self.plan; + try self.l.planScore(self.q32, self.out, p, 0, s.n, cases[self.case].kv, d, s.k, scale(), @backingInt(self.k), false, .shared, self.rig.s.handle); + try self.rig.s.synchronize(); + } + + /// The control's launch: planScore's tf_plan_rows_score256_* on its grid and LDS, without tf_plan_lone_score256_*. + fn chunksAlone(self: *RowsScore) !void { + const s = self.shape; + const kv = cases[self.case].kv; + var a: hip.launch.Args = .{}; + try a.add(self.q32); + try a.add(self.out); + for ([_]usize{ s.k, s.n, kv, d }) |x| try a.add(@as(c_int, @intCast(x))); + try a.add(scale()); + try a.add(self.plan.args); + try a.add(@as(c_int, 0)); + const grid: hip.launch.Dim3 = .{ .x = @intCast((s.k + 127) / 128), .y = @intCast(kv), .z = @intCast(s.rows) }; + const lds: u32 = @intCast(hip.launches.score_rows * s.n / kv * d * 4); + const f = self.l.plan.score256_rows[@intCast(@backingInt(self.k) - 1)]; + try hip.launch.launch(f, .{ .grid = grid, .block = .{ .x = 128 }, .shared = lds }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + /// tf_plan_score256_*'s bytes on the same plan: a block a row. + pub fn replaced(self: *RowsScore) ![]const u8 { + const s = self.shape; + try self.l.planScore(self.q32, self.tree, self.plan, 0, s.n, cases[self.case].kv, d, s.k, scale(), @backingInt(self.k), false, .one, self.rig.s.handle); + return self.rig.bytes(self.tree, self.count() * 4); + } + + pub fn count(self: *RowsScore) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + /// q k * scale in float64 for the keys a row sees, -inf past them; each score's magnitude is its terms' sum. + pub fn reference(self: *RowsScore, want: []f64, mag: []f64) !void { + try self.work(want, mag, null); + } + + /// Gate 4's scores with each dot's products summed in the accumulator and order, then scaled. + pub fn simulate(self: *RowsScore, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.work(out, null, .{ acc, order }); + } + + /// Every row's scores, each dot in float64 or (`sim`) as an accumulator sums it; gate 4's once a period. + fn work(self: *RowsScore, out: []f64, mag: ?[]f64, sim: ?struct { c.Accum, g.Order }) !void { + const s = self.shape; + const sc: f64 = scale(); + const kv = cases[self.case].kv; + const heads = s.n / kv; + for (0..s.rows) |r| for (0..s.n) |h| { + const base = (r * s.n + h) * s.k; + @memset(out[base + self.vis[r] .. base + s.k], -std.math.inf(f64)); + if (mag) |m| @memset(m[base..][0..s.k], 0); + }; + var krow: [d]f64 = undefined; + var terms: [d]f64 = undefined; + var r0: usize = 0; + while (r0 < s.rows) { + var r1 = r0 + 1; + while (r1 < s.rows and self.slot[r1] == self.slot[r0]) r1 += 1; + var most: usize = 0; + for (self.vis[r0..r1]) |v| most = @max(most, v); + const reach = if (self.stress) @min(most, period) else most; + for (0..kv) |hk| for (0..reach) |pos| { + const row_at = self.at(self.slot[r0], hk, pos); + for (&krow, self.pool[row_at..][0..d]) |*x, bits| x.* = kit.get(self.k, std.mem.asBytes(&bits), 0); + for (r0..r1) |r| if (pos < self.vis[r]) for (hk * heads..(hk + 1) * heads) |h| { + var dot: f64 = 0; + var abs: f64 = 0; + for (self.q[(r * s.n + h) * d ..][0..d], krow, &terms) |x, y, *t| { + t.* = x * y; + dot += t.*; + abs += @abs(t.*); + } + if (sim) |how| dot = sums.sumIn(how[0], how[1], &terms); + const i = (r * s.n + h) * s.k + pos; + out[i] = dot * sc; + if (mag) |m| m[i] = abs * sc; + }; + }; + if (self.stress) for (r0..r1) |r| for (0..s.n) |h| { + const base = (r * s.n + h) * s.k; + for (@min(period, self.vis[r])..self.vis[r]) |pos| { + out[base + pos] = out[base + pos - period]; + if (mag) |m| m[base + pos] = m[base + pos - period]; + } + }; + r0 = r1; + } + } +};