From 3ef77dcd463802c21a6081ed329adc5a5d81cef9 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:30:17 -0500 Subject: [PATCH 01/13] inkling2 metal: sliding attention in 32-key chunks, global attention in the fewest 1,024-key folds a slot --- .../inkling2/metal/attention_plan.zig | 11 +++- .../inkling2/metal/attention_test.zig | 65 ++++++++++--------- 2 files changed, 43 insertions(+), 33 deletions(-) diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index 2b4a494f67e..a259cd009d5 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -6,7 +6,7 @@ pub const head_dim = config.head_dim; pub const d_rel = config.d_rel; pub const extent = 1024; pub const tile_keys = 64; -pub const sliding_chunk = 256; +pub const sliding_chunk = 32; pub const global_chunk = 16384; pub const global_sub = 1024; pub const subs = global_chunk / global_sub; @@ -51,7 +51,7 @@ pub const Layer = struct { return .{ .window = window, .ring = ringFor(window, rows), .chunk = sliding_chunk, .tau = false }; } pub fn global(capacity: u32) Layer { - return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = global_chunk, .tau = true }; + return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = globalChunk(capacity), .tau = true }; } pub fn cacheBytes(l: Layer, kv: usize) usize { return @as(usize, l.ring) * kv * head_dim * 2; @@ -60,6 +60,13 @@ pub const Layer = struct { pub const Prep = struct { qk_clip: f32 = 22.627416997969522, rel_clip: f32 = 8, floor: f32 = 8192, alpha: f32 = 0.1, eps: f32 = 1e-6 }; pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1 }; +/// The fewest keys a launch slot that fits `capacity` in 64 slots; any whole number of 1,024-key folds gives the same bits. +pub fn globalChunk(capacity: u32) u32 { + var chunk: u32 = global_sub; + while (@as(u64, chunk) * 64 < capacity and chunk < global_chunk) chunk *= 2; + return chunk; +} + pub fn ringFor(window: u32, rows: u32) u32 { return @intCast(std.mem.alignForward(usize, @as(usize, window) + rows - 1, tile_keys)); } diff --git a/zig/src/families/inkling2/metal/attention_test.zig b/zig/src/families/inkling2/metal/attention_test.zig index bdc6d2e1d34..86d78760586 100644 --- a/zig/src/families/inkling2/metal/attention_test.zig +++ b/zig/src/families/inkling2/metal/attention_test.zig @@ -32,11 +32,11 @@ test "inkling2 metal Mini ring and window boundaries" { try t.expectEqual(@as(u32, 1088), p.ringFor(1024, 2)); try t.expectEqual(@as(u32, 3072), p.Layer.sliding(1024, 2048).ring); const l = p.Layer.sliding(1024, 1); - try t.expectEqual(@as(u32, 5), p.slotsFor(l, 1048576)); - try t.expectEqual(@as(?usize, 3), p.partialSlot(l, 3, 1023)); - try t.expectEqual(@as(?usize, null), p.partialSlot(l, 4, 1023)); - try t.expectEqual(@as(?usize, 4), p.partialSlot(l, 4, 1024)); - try t.expectEqual(@as(?usize, 3), p.partialSlot(l, 7, 2047)); + try t.expectEqual(@as(u32, 33), p.slotsFor(l, 1048576)); + try t.expectEqual(@as(?usize, 31), p.partialSlot(l, 31, 1023)); + try t.expectEqual(@as(?usize, null), p.partialSlot(l, 32, 1023)); + try t.expectEqual(@as(?usize, 32), p.partialSlot(l, 32, 1024)); + try t.expectEqual(@as(?usize, 31), p.partialSlot(l, 63, 2047)); try t.expectEqual(@as(usize, 1023), @as(usize, 8191) % 1024); try t.expectEqual(@as(usize, 0), @as(usize, 8192) % 8192); } @@ -51,19 +51,22 @@ test "inkling2 metal tau starts strictly above its 8192 floor" { test "inkling2 metal decode and prompt dispatch geometry" { const sl = p.Layer.sliding(1024, 8); const sr = p.Rows{ .rows = 8, .last_pos = 4095, .streams = 2 }; - const sd = try p.attend(sr, sl, 5, 8 * 24 * 5); + const sd = try p.attend(sr, sl, 33, 8 * 24 * 33); try t.expectEqual(p.Path.decode_gqa, sd.path); - try t.expectEqual([3]u32{ 64, 5, 1 }, sd.grid); + try t.expectEqual([3]u32{ 64, 33, 1 }, sd.grid); try t.expectEqual([3]u32{ 192, 1, 1 }, sd.merge_grid); try t.expectEqual(@as(u32, 32), sd.threads); - const general = try p.attend(.{ .rows = 4, .heads = 16, .kv_heads = 8, .last_pos = 4095 }, sl, 5, 0); + const general = try p.attend(.{ .rows = 4, .heads = 16, .kv_heads = 8, .last_pos = 4095 }, sl, 33, 0); try t.expectEqual(p.Path.decode, general.path); - try t.expectEqual([3]u32{ 64, 5, 1 }, general.grid); + try t.expectEqual([3]u32{ 64, 33, 1 }, general.grid); // Single-row sliding/short decode keeps 24 scalar TGs to avoid under-occupying wide GPUs. - const lone_sl = try p.attend(.{ .rows = 1, .last_pos = 500 }, sl, 5, 0); + const lone_sl = try p.attend(.{ .rows = 1, .last_pos = 100 }, sl, 33, 0); try t.expectEqual(p.Path.decode, lone_sl.path); - try t.expectEqual([3]u32{ 24, 5, 1 }, lone_sl.grid); + try t.expectEqual([3]u32{ 24, 33, 1 }, lone_sl.grid); const gl = p.Layer.global(1048576); + try t.expectEqual(@as(u32, 16384), gl.chunk); + try t.expectEqual(@as(u32, 1024), p.Layer.global(65536).chunk); + try t.expectEqual(@as(u32, 4096), p.Layer.global(262144).chunk); const one = p.Rows{ .rows = 1, .last_pos = 1048575 }; const gd = try p.attend(one, gl, 64, 24 * 64 * p.subs - 1); try t.expectEqual(p.Path.prompt, gd.path); @@ -78,25 +81,25 @@ test "inkling2 metal decode and prompt dispatch geometry" { try t.expectEqual(p.Path.prompt, prompt.path); try t.expectEqual([3]u32{ 4, 8, 2 }, prompt.grid); // ceil(130 * 3 / 128) const sl256 = p.Layer.sliding(1024, 256); - const s1 = try p.attend(.{ .rows = 1, .last_pos = 1024 }, sl, 5, 0); - try t.expectEqual(p.Path.decode, s1.path); - const sp2 = try p.attend(.{ .rows = 2, .last_pos = 1024 }, sl, 5, 0); + const s1 = try p.attend(.{ .rows = 1, .last_pos = 1024 }, sl, 33, 0); + try t.expectEqual(p.Path.decode_gqa, s1.path); + const sp2 = try p.attend(.{ .rows = 2, .last_pos = 1024 }, sl, 33, 0); try t.expectEqual(p.Path.sliding_prompt, sp2.path); - try t.expectEqual([3]u32{ 1, 8, 5 }, sp2.grid); + try t.expectEqual([3]u32{ 1, 8, 33 }, sp2.grid); try t.expectEqual(@as(u32, 0), sp2.c0); try t.expectEqual(@as(u32, 256), sp2.threads); - const sp8 = try p.attend(.{ .rows = 8, .last_pos = 1024 }, sl, 5, 0); + const sp8 = try p.attend(.{ .rows = 8, .last_pos = 1024 }, sl, 33, 0); try t.expectEqual(p.Path.sliding_prompt, sp8.path); - try t.expectEqual([3]u32{ 4, 8, 5 }, sp8.grid); + try t.expectEqual([3]u32{ 4, 8, 33 }, sp8.grid); try t.expectEqual(@as(u32, 0), sp8.c0); try t.expectEqual(@as(u32, 256), sp8.threads); - const sp256 = try p.attend(.{ .rows = 256, .last_pos = 2255 }, sl256, 5, 0); + const sp256 = try p.attend(.{ .rows = 256, .last_pos = 2255 }, sl256, 33, 0); try t.expectEqual(p.Path.sliding_prompt, sp256.path); - try t.expectEqual([3]u32{ 128, 8, 6 }, sp256.grid); - try t.expectEqual(@as(u32, 3), sp256.c0); - const sp_short = try p.attend(.{ .rows = 64, .last_pos = 500 }, p.Layer.sliding(1024, 64), 5, 0); + try t.expectEqual([3]u32{ 128, 8, 41 }, sp256.grid); + try t.expectEqual(@as(u32, 30), sp256.c0); + const sp_short = try p.attend(.{ .rows = 64, .last_pos = 500 }, p.Layer.sliding(1024, 64), 33, 0); try t.expectEqual(p.Path.sliding_prompt, sp_short.path); - try t.expectEqual([3]u32{ 32, 8, 2 }, sp_short.grid); + try t.expectEqual([3]u32{ 32, 8, 16 }, sp_short.grid); try t.expectEqual(@as(u32, 0), sp_short.c0); } @@ -107,15 +110,15 @@ test "inkling2 metal GQA 3:1 guard, activeChunks, and batched segment planning" const sl = p.Layer.sliding(1024, 1); try t.expectEqual(@as(u32, 1), p.activeChunks(sl, 0)); - try t.expectEqual(@as(u32, 1), p.activeChunks(sl, 255)); - try t.expectEqual(@as(u32, 2), p.activeChunks(sl, 256)); - try t.expectEqual(@as(u32, 4), p.activeChunks(sl, 1023)); - try t.expectEqual(@as(u32, 5), p.activeChunks(sl, 1024)); - try t.expectEqual(@as(u32, 5), p.activeChunks(sl, 99999)); + try t.expectEqual(@as(u32, 8), p.activeChunks(sl, 255)); + try t.expectEqual(@as(u32, 9), p.activeChunks(sl, 256)); + try t.expectEqual(@as(u32, 32), p.activeChunks(sl, 1023)); + try t.expectEqual(@as(u32, 33), p.activeChunks(sl, 1024)); + try t.expectEqual(@as(u32, 33), p.activeChunks(sl, 99999)); const gl = p.Layer.global(65536); - try t.expectEqual(@as(u32, 1), p.activeChunks(gl, 16383)); - try t.expectEqual(@as(u32, 2), p.activeChunks(gl, 16384)); + try t.expectEqual(@as(u32, 16), p.activeChunks(gl, 16383)); + try t.expectEqual(@as(u32, 17), p.activeChunks(gl, 16384)); const sl_segs = [_]p.BatchedSegSpec{ .{ .rows = 1, .last_pos = 40, .layer = .{ .window = 1024, .ring = 1280, .chunk = 256, .tau = false }, .is_tree = false }, @@ -156,7 +159,7 @@ test "inkling2 metal GQA 3:1 guard, activeChunks, and batched segment planning" try t.expect(p.planBatched(&gl_segs, 24, 8, 64, 0) == null); const gl_b = p.planBatched(&gl_segs, 24, 8, 64, 64 * 24 * 64 * p.subs).?; try t.expectEqual(@as(u32, 3), gl_b.total_rows); - try t.expectEqual(@as(u32, 2), gl_b.max_chunks); + try t.expectEqual(@as(u32, 18), gl_b.max_chunks); try t.expect(gl_b.tau); - try t.expectEqual([3]u32{ 24, 2, 1 }, gl_b.grid); + try t.expectEqual([3]u32{ 24, 18, 1 }, gl_b.grid); } From 75ff7a95a0b40163346e2099d3467eac9981dd88 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:59:08 -0500 Subject: [PATCH 02/13] lean: the global chunk comment fits 120 columns --- zig/src/families/inkling2/metal/attention_plan.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index a259cd009d5..9d0c611fad3 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -60,7 +60,7 @@ pub const Layer = struct { pub const Prep = struct { qk_clip: f32 = 22.627416997969522, rel_clip: f32 = 8, floor: f32 = 8192, alpha: f32 = 0.1, eps: f32 = 1e-6 }; pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1 }; -/// The fewest keys a launch slot that fits `capacity` in 64 slots; any whole number of 1,024-key folds gives the same bits. +/// The fewest keys a slot that fit `capacity` in 64 slots; any whole number of 1,024-key folds gives the same bits. pub fn globalChunk(capacity: u32) u32 { var chunk: u32 = global_sub; while (@as(u64, chunk) * 64 < capacity and chunk < global_chunk) chunk *= 2; From 0892f6692e35200b0de70b691ecbed38cbd1ce6f Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:42:18 -0500 Subject: [PATCH 03/13] inkling2 metal: the forward on a concurrent encoder in five command buffers, independent launches side by side --- zig/src/families/inkling2/metal/attention.zig | 74 +++-- zig/src/families/inkling2/metal/forward.zig | 269 ++++-------------- .../inkling2/metal/forward_attention.zig | 221 ++++++++++++++ .../families/inkling2/metal/forward_conv.zig | 1 + .../inkling2/metal/forward_dispatch.zig | 18 ++ .../inkling2/metal/forward_experts.zig | 91 ++++++ zig/src/families/inkling2/metal/glue.zig | 1 + zig/src/families/inkling2/metal/loop.zig | 2 + .../inkling2/metal/tfq3_pipelines.zig | 3 + 9 files changed, 441 insertions(+), 239 deletions(-) create mode 100644 zig/src/families/inkling2/metal/forward_attention.zig create mode 100644 zig/src/families/inkling2/metal/forward_dispatch.zig create mode 100644 zig/src/families/inkling2/metal/forward_experts.zig diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig index 4f5d6ee3e50..cdfc90d01a0 100644 --- a/zig/src/families/inkling2/metal/attention.zig +++ b/zig/src/families/inkling2/metal/attention.zig @@ -133,7 +133,7 @@ pub fn prepTree(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: p prepLaunch(k.prep_tree, e, r, l, c, meta, raw, scales, q, rel, kv); } -fn attendImpl(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref, cached: ?Ref) !void { +fn partialsImpl(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, cached: ?Ref) !planning.Launch { const launch = try planning.attend(r, l, stride, slots); const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); switch (launch.path) { @@ -163,12 +163,18 @@ fn attendImpl(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer }, } e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); + return launch; +} +pub fn partials(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref) !planning.Launch { + return partialsImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, null); +} + +fn attendImpl(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref, cached: ?Ref) !void { + const launch = try partialsImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, cached); e.barrier(); - e.setPipeline(k.merge); - bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); - e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = launch.subs }, 6); - e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); + mergeRaw(k, e, r, l, launch.partials_rh, launch.subs, meta, part_o, part_ml, sink, gate, out); } + pub fn attend(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { return attendImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, sink, gate, out, null); } @@ -188,7 +194,7 @@ pub fn attendCached(k: *const Kernels, e: anytype, r: planning.Rows, l: planning } /// The table is opt-out at sixteen active global chunks, and never serves prompt, tree or batched paths. -pub fn attendReusable(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref, min_context: u32, segments: usize, tree: bool, decode: bool, tab: Ref) !void { +pub fn partialsReusable(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, min_context: u32, segments: usize, tree: bool, decode: bool, tab: Ref) !planning.Launch { const decode_slots = @as(usize, r.rows) * r.heads * stride * planning.subs; const launch = try planning.attend(r, l, stride, if (decode) decode_slots else slots); const kind: relbias.Kind = switch (launch.path) { @@ -206,10 +212,17 @@ pub fn attendReusable(k: *const Kernels, e: anytype, r: planning.Rows, l: planni tree, kind, )) { - return attendImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, sink, gate, out, null); + return partialsImpl(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, null); } try projectRelTable(k, e, r, meta.pos, rel, proj, tab); - return attendImpl(k, e, r, l, stride, decode_slots, meta, q, kv, rel, proj, part_o, part_ml, sink, gate, out, tab); + e.barrier(); + return partialsImpl(k, e, r, l, stride, decode_slots, meta, q, kv, rel, proj, part_o, part_ml, tab); +} + +pub fn attendReusable(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref, min_context: u32, segments: usize, tree: bool, decode: bool, tab: Ref) !void { + const launch = try partialsReusable(k, e, r, l, stride, slots, meta, q, kv, rel, proj, part_o, part_ml, min_context, segments, tree, decode, tab); + e.barrier(); + mergeRaw(k, e, r, l, launch.partials_rh, launch.subs, meta, part_o, part_ml, sink, gate, out); } fn fillBatchedSegs(e: mtl.ComputeEncoder, caches: []const BatchedCache, usage: usize, out: *[planning.max_batched_segments]planning.BatchedSeg) ![]const planning.BatchedSeg { @@ -259,34 +272,51 @@ pub fn attendBatched(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning. e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); } -pub fn attendTree(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, start: u32, meta: RowMeta, tree_paths: Ref, tail_o: Ref, tail_ml: Ref, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { - const launch = try planning.attendTree(r, l, stride, start); +pub fn treePrefix(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning.TreeLaunch, r: planning.Rows, l: planning.Layer, meta: RowMeta, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, tail_o: Ref, tail_ml: Ref) bool { + if (!launch.global or launch.p_tile == 0) return false; + const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); + const prompt_segs = meta.prompt_segs orelse meta.segs; + const args = planning.PromptTreeArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale, .p_tile = launch.p_tile, .c_off = launch.c_off, .max_pos = r.last_pos }; + e.setPipeline(k.prompt_tree_prefix); + bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml, meta.pos, tail_o, tail_ml }, 0); + e.setValue(args, 11); + e.dispatchGroups(mtl.Size.of(launch.prefix_grid[0], launch.prefix_grid[1], launch.prefix_grid[2]), mtl.Size.of(launch.threads, 1, 1)); + return true; +} + +pub fn treePartials(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning.TreeLaunch, r: planning.Rows, l: planning.Layer, meta: RowMeta, tree_paths: Ref, tail_o: Ref, tail_ml: Ref, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref) void { const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); if (launch.global) { const prompt_segs = meta.prompt_segs orelse meta.segs; const args = planning.PromptTreeArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale, .p_tile = launch.p_tile, .c_off = launch.c_off, .max_pos = r.last_pos }; - if (launch.p_tile > 0) { - e.setPipeline(k.prompt_tree_prefix); - bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml, meta.pos, tail_o, tail_ml }, 0); - e.setValue(args, 11); - e.dispatchGroups(mtl.Size.of(launch.prefix_grid[0], launch.prefix_grid[1], launch.prefix_grid[2]), mtl.Size.of(launch.threads, 1, 1)); - e.barrier(); - } e.setPipeline(k.prompt_tree_tail); bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml, meta.pos, tree_paths, tail_o, tail_ml }, 0); e.setValue(args, 12); - e.dispatchGroups(mtl.Size.of(launch.tail_grid[0], launch.tail_grid[1], launch.tail_grid[2]), mtl.Size.of(launch.threads, 1, 1)); } else { e.setPipeline(k.decode_tree); bind(e, &.{ q, kv.k, kv.v, rel, proj, meta.segs, part_o, part_ml, meta.pos, meta.seg_of, tree_paths }, 0); e.setValue(planning.AttnArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 11); - e.dispatchGroups(mtl.Size.of(launch.tail_grid[0], launch.tail_grid[1], launch.tail_grid[2]), mtl.Size.of(launch.threads, 1, 1)); } - e.barrier(); + e.dispatchGroups(mtl.Size.of(launch.tail_grid[0], launch.tail_grid[1], launch.tail_grid[2]), mtl.Size.of(launch.threads, 1, 1)); +} + +pub fn mergeRaw(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Layer, partials_rh: u32, subs: u32, meta: RowMeta, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) void { e.setPipeline(k.merge); bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); - e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = 1 }, 6); - e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); + e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = partials_rh, .subs = subs }, 6); + e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); +} + +pub fn merge(k: *const Kernels, e: mtl.ComputeEncoder, launch: planning.Launch, r: planning.Rows, l: planning.Layer, meta: RowMeta, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) void { + mergeRaw(k, e, r, l, launch.partials_rh, launch.subs, meta, part_o, part_ml, sink, gate, out); +} + +pub fn attendTree(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, start: u32, meta: RowMeta, tree_paths: Ref, tail_o: Ref, tail_ml: Ref, q: Ref, kv: Cache, rel: Ref, proj: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + const launch = try planning.attendTree(r, l, stride, start); + if (treePrefix(k, e, launch, r, l, meta, q, kv, rel, proj, part_o, part_ml, tail_o, tail_ml)) e.barrier(); + treePartials(k, e, launch, r, l, meta, tree_paths, tail_o, tail_ml, q, kv, rel, proj, part_o, part_ml); + e.barrier(); + mergeRaw(k, e, r, l, launch.partials_rh, 1, meta, part_o, part_ml, sink, gate, out); } test { diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index b10bd5219a9..e1fd9c154ed 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -7,10 +7,13 @@ const ap = @import("attention_plan.zig"); const attention = @import("attention.zig"); const glue = @import("glue.zig"); const metal_reset = @import("reset.zig"); -const experts = @import("experts.zig"); +const forward_experts = @import("forward_experts.zig"); +const forward_attention = @import("forward_attention.zig"); +const forward_dispatch = @import("forward_dispatch.zig"); +const runtime = forward_dispatch.runtime; +const copyBf16 = forward_dispatch.copyBf16; const loop = @import("loop.zig"); const dense_mma = @import("dense.zig"); -const tree = @import("tree.zig"); const conv = @import("forward_conv.zig"); const state = @import("state.zig"); const sample = @import("sample.zig"); @@ -22,6 +25,9 @@ pub const Draw = sample.Draw; pub const DrawMode = sample.DrawMode; pub const drawMode = sample.drawMode; pub const Segment = struct { cache: *state.Cache, rows: usize, parents: ?[]const i32 = null }; +const fusedConv = forward_attention.fusedConv; +const postConv = forward_attention.postConv; +const attendSegments = forward_attention.attendSegments; const SegMeta = struct { is_tree: bool = false, max_depth: u32 = 0 }; /// The BF16 rows [off, off + rows * hidden * 2) of `buf` replace the normed embeddings of chunk rows [row, row + rows). pub const ImageRows = struct { row: u32, rows: u32, buf: mtl.Buffer, off: usize = 0 }; @@ -48,7 +54,6 @@ pub fn finalPlan(rows: usize, all: bool, taps: bool) FinalPlan { }; } -const RArgs = extern struct { count: u32, boundary: u32 = 0 }; const NormArgs = extern struct { rows: u32, width: u32, heads: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 }; pub const DenseArgs = extern struct { rows: u32, n: u32, k: u32, ldy: u32 }; @@ -64,9 +69,6 @@ fn row(buf: mtl.Buffer, i: usize, row_bytes: usize) Ref { fn a(x_: Ref) attention.Ref { return .{ .buf = x_.buf, .off = x_.off }; } -fn x(x_: Ref) experts.Ref { - return .{ .buf = x_.buf, .off = x_.off }; -} fn l(x_: Ref) loop.Ref { return .{ .buf = x_.buf, .off = x_.off }; } @@ -90,16 +92,6 @@ fn gates(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, h: Ref, msg: loop.gatesSplit(&m.loop, e, l(h), l(msg), stride, l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(out), l(at(s.gate_norm, 0)), l(at(s.gate_zeta, 0)), @intCast(rows)); } -fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { - e.setPipeline(m.runtime[@backingInt(op)]); - for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); - e.setValue(RArgs{ .count = @intCast(count), .boundary = @intCast(boundary) }, refs.len); - e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(256, 1, 1)); -} - -fn copyBf16(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { - runtime(m, e, .copy_bf16, &.{ from, to }, count, 0); -} fn captureTap(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, rows: usize, channel: usize) void { std.debug.assert(channel < state.feature_taps); runtime(m, e, .capture_tap, &.{ from, to }, rows * state.hidden, channel); @@ -174,9 +166,11 @@ fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, rows: copyBf16(m, e, at(s.blocks, (i * state.block_slots + 2) * state.hidden * 2), row(s.bank0, i, state.hidden * 2), state.hidden); } copyBf16(m, e, at(s.p, 0), at(s.bank1, 0), rows * state.hidden); + e.barrier(); loop.crossPassMessageAttention(&m.loop, e, l(at(s.bank0, 0)), l(at(s.bank1, 0)), l(r(m.weights.cross_queries)), l(r(m.weights.cross_kv_queries)), l(at(s.messages, 0)), @intCast(rows)); // The prelude p is restored, but every visit's KV and convolution state remains live. copyBf16(m, e, at(s.prelude, 0), at(s.p, 0), rows * state.hidden); + e.barrier(); } fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize, pre_fused: bool, pre_fused_norm: bool) !void { @@ -190,6 +184,7 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra if (!pre_fused) { metal_reset.cachedAttention(m, e, s, v, rows); } + e.barrier(); if (v.hasMessages()) { const controllers = w.controllers.?; const core = v.layer - 6; @@ -209,6 +204,7 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra loop.gatesEach(&m.loop, e, &roles, @intCast(rows), state.message_entries * state.hidden); } } + e.barrier(); const gated = v.hasMessages(); // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. if (!gated and lp.kind == .local) { @@ -220,203 +216,6 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra } } -fn fusedConv(segments: []const Segment, meta: []const SegMeta) bool { - for (meta) |m| if (m.is_tree) return false; - return segments.len > 1 or segments[0].rows <= state.window_rows; -} - -fn postConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment, meta: []const SegMeta, slot: usize, cs: usize, raw: Ref, weight: ck.Tensor, out: Ref) void { - if (fusedConv(segments, meta)) return conv.postConv(m, e, s, segments, slot, cs, raw, weight, out); - var base: usize = 0; - for (segments, meta) |seg, sm| { - staticPostConv(m, e, s, seg.cache, slot, cs, raw, weight, out, base, seg.rows, sm.is_tree); - base += seg.rows; - } -} - -fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref { - const channels = state.convWidth(conv_state); - const taps = cache.staged(slot, conv_state, 0); - copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); - copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); - return taps; -} - -fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void { - const channels = state.convWidth(conv_state); - const taps = stageConvInput(m, e, cache, slot, conv_state, raw, base, rows); - if (is_tree) { - tree.convStatic(&m.tree, e, taps, r(weight), at(s.conv_src, base * 4 * 4), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); - } else { - glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); - } -} - -fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, seg_meta: []const SegMeta, meta_override: ?attention.RowMeta, decode: bool) !void { - const fused = fusedConv(segments, seg_meta); - if (fused) conv.fusedAttention(m, e, s, v, segments); - const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; - const proj_ref = a(r(m.weights.layers[v.layer].attn.rel_projection)); - const scale_refs = [2]attention.Ref{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }; - var specs: [state.max_segments]ap.BatchedSegSpec = undefined; - for (segments, seg_meta, 0..) |seg, sm, si| { - const layer0 = seg.cache.attentionLayer(&m.weight_plan, v.cache_slot, seg.rows); - const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(seg.cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; - const last_pos: u32 = @intCast(seg.cache.len + (if (sm.is_tree) sm.max_depth else seg.rows - 1)); - specs[si] = .{ .rows = @intCast(seg.rows), .last_pos = last_pos, .layer = layer, .is_tree = sm.is_tree }; - } - if (ap.planBatched(specs[0..segments.len], 24, 8, state.max_attention_stride, 0)) |batch| { - var caches: [state.max_segments]attention.BatchedCache = undefined; - var base: usize = 0; - for (segments, seg_meta, 0..) |seg, sm, si| { - if (!fused) convInputsForAttention(m, e, s, seg.cache, v, base, seg.rows, sm.is_tree); - caches[si] = .{ - .k = a(seg.cache.keys(v.cache_slot)), - .v = a(seg.cache.values(v.cache_slot)), - .row0 = @intCast(base), - .n = @intCast(seg.rows), - .p0 = @intCast(seg.cache.len), - .ring = specs[si].layer.ring, - }; - base += seg.rows; - } - const rr = ap.Rows{ .rows = batch.total_rows, .heads = 24, .kv_heads = 8, .last_pos = 0, .streams = @intCast(segments.len) }; - const raw_refs = [4]attention.Ref{ a(at(s.q_raw, 0)), a(at(s.k_conv, 0)), a(at(s.v_conv, 0)), a(at(s.rel_raw, 0)) }; - try attention.prepBatched(&m.attention, e, rr, batch.tau, prep, a(at(s.pos, 0)), a(at(s.seg_of, 0)), caches[0..segments.len], raw_refs, scale_refs, a(at(s.q_prep, 0)), a(at(s.rel_prep, 0))); - e.barrier(); - try attention.attendBatched(&m.attention, e, batch, 24, 8, a(at(s.pos, 0)), a(at(s.seg_of, 0)), caches[0..segments.len], a(at(s.q_prep, 0)), a(at(s.rel_prep, 0)), proj_ref, a(at(s.part_o, 0)), a(at(s.part_ml, 0)), a(at(s.sink, 0)), a(at(s.gate, 0)), a(at(s.att, 0))); - return; - } - var base: usize = 0; - for (segments, seg_meta, 0..) |seg, sm, si| { - const rows = seg.rows; - const cache = seg.cache; - const start = cache.len; - const layer = specs[si].layer; - const last_pos = specs[si].last_pos; - const rr = ap.Rows{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = last_pos, .streams = 1 }; - const meta = meta_override orelse attention.RowMeta{ - .pos = a(at(s.pos, base * 4)), - .seg_of = a(at(s.seg_of, base * 4)), - .segs = a(at(s.segs, 0)), - .prompt_segs = a(at(s.segs, si * @sizeOf(ap.Seg))), - }; - const kv = attention.Cache{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; - if (!fused) convInputsForAttention(m, e, s, cache, v, base, rows, sm.is_tree); - const rel_ref = a(at(s.rel_prep, base * state.rel_width * 2)); - const q_ref = a(at(s.q_prep, base * state.query_width * 2)); - const po_ref = a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)); - const pml_ref = a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)); - const sink_ref = a(at(s.sink, base * 24 * 2)); - const gate_ref = a(at(s.gate, base * state.query_width * 2)); - const att_ref = a(at(s.att, base * state.query_width * 2)); - const raw_refs = [4]attention.Ref{ a(at(s.q_raw, base * state.query_width * 2)), a(at(s.k_conv, base * state.kv_width * 2)), a(at(s.v_conv, base * state.kv_width * 2)), a(at(s.rel_raw, base * state.rel_width * 2)) }; - if (sm.is_tree) { - attention.prepTree(&m.attention, e, rr, layer, prep, meta, raw_refs, scale_refs, q_ref, rel_ref, kv); - try attention.attendTree(&m.attention, e, rr, layer, state.max_attention_stride, @intCast(start), meta, a(at(s.tree_paths, base * state.window_rows * 4)), a(at(s.tree_tail_o, base * 2 * 24 * ap.head_dim * 4)), a(at(s.tree_tail_ml, base * 24 * 16)), q_ref, kv, rel_ref, proj_ref, po_ref, pml_ref, sink_ref, gate_ref, att_ref); - } else { - const stride = ap.slotsFor(layer, @as(usize, last_pos) + 1); - if (stride > state.max_attention_stride) return error.Inkling2Partials; - attention.prep(&m.attention, e, rr, layer, prep, meta, raw_refs, scale_refs, q_ref, rel_ref, kv); - try attention.attendReusable(&m.attention, e, rr, layer, stride, 0, meta, q_ref, kv, rel_ref, proj_ref, po_ref, pml_ref, sink_ref, gate_ref, att_ref, m.relbias_min, segments.len, false, decode, a(at(s.rel_bias, 0))); - } - base += rows; - } -} - -fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void { - const lp = m.weight_plan.at(v.layer); - const w = &m.weights.layers[v.layer]; - const k_taps = stageConvInput(m, e, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows); - const v_taps = stageConvInput(m, e, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows); - const k_out = at(s.k_conv, base * state.kv_width * 2); - const v_out = at(s.v_conv, base * state.kv_width * 2); - const k_in = at(s.k_norm, base * state.hidden * 2); - const v_norm = if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); - const v_in = at(v_norm.buf, v_norm.off + base * state.hidden * 2); - if (is_tree) { - const src = at(s.conv_src, base * 4 * 4); - switch (w.attn.k_conv) { - .static => |kw| tree.convStatic(&m.tree, e, k_taps, r(kw), src, k_out, @intCast(rows), state.kv_width), - .dynamic => |kd| tree.convDynamic(&m.tree, e, k_taps, k_in, r(kd.static_w), r(kd.projection), src, k_out, @intCast(rows), state.kv_width), - } - switch (w.attn.v_conv) { - .static => |vw| tree.convStatic(&m.tree, e, v_taps, r(vw), src, v_out, @intCast(rows), state.kv_width), - .dynamic => |vd| tree.convDynamic(&m.tree, e, v_taps, v_in, r(vd.static_w), r(vd.projection), src, v_out, @intCast(rows), state.kv_width), - } - return; - } - switch (w.attn.k_conv) { - .static => |kw| switch (w.attn.v_conv) { - .static => |vw| glue.convStaticKv(&m.glue, e, k_taps, r(kw), k_out, v_taps, r(vw), v_out, @intCast(rows), state.kv_width), - .dynamic => |vd| { - glue.convStatic(&m.glue, e, k_taps, r(kw), k_out, @intCast(rows), state.kv_width); - glue.convDynamic(&m.glue, e, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width); - }, - }, - .dynamic => |kd| switch (w.attn.v_conv) { - .dynamic => |vd| glue.convDynamicKv(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width), - .static => |vw| { - glue.convDynamic(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, @intCast(rows), state.kv_width); - glue.convStatic(&m.glue, e, v_taps, r(vw), v_out, @intCast(rows), state.kv_width); - }, - }, - } -} - -fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { - const w = &m.weights.layers[layer]; - const lp = m.weight_plan.at(@intCast(layer)).precision; - const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = if (lp == .mxfp8) .mxfp8 else .nvfp4 }; - if (lp == .tfq5) { - try m.dispatchTfq5Moe(e, w.tfq5 orelse return error.Tfq5NotLoaded, s.mlp_normed, s.route_ids, s.gu, s.down, rows); - return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); - } - if (lp == .tfq3) { - const pipes = if (m.tfq3_pipes) |*p| p else return error.Tfq3NotLoaded; - try pipes.dispatch(e, w.tfq3 orelse return error.Tfq3NotLoaded, at(s.mlp_normed, 0), at(s.route_ids, 0), at(s.gu, 0), at(s.down, 0), rows); - return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); - } - const precision: experts.Format = if (lp == .nvfp4) .nvfp4 else if (lp == .mxfp8) .mxfp8 else return error.UnsupportedInkling2ExpertFormat; - const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; - if (m.experts.mma != null and rows >= experts.mma_rows) { - // A row's sums are the same on either path, so a chunk or window takes the one that fits its width. - const nv = precision == .nvfp4; - const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; - const down_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) } else null; - try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); - try experts.mma(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call); - try experts.mma(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call); - } else if (rows >= 2) { - var row0: usize = 0; - while (row0 < rows) { - const take: usize = @min(rows - row0, experts.max_grouped_rows); - const chunk_gu = experts.Call{ .rows = @intCast(take), .k = state.hidden, .n = state.intermediate, .format = precision }; - const chunk_down = experts.Call{ .rows = @intCast(take), .k = state.intermediate, .n = state.hidden, .format = precision }; - const x_in = x(row(s.mlp_normed, row0, state.hidden * 2)); - const ids_in = x(row(s.route_ids, row0, state.experts_per_token * 4)); - const gu_out = x(row(s.gu, row0, state.experts_per_token * state.intermediate * 2)); - const down_out = x(row(s.down, row0, state.experts_per_token * state.hidden * 2)); - try experts.groupBuckets(&m.experts, e, ids_in, x(at(s.expert_group, 0)), chunk_gu); - if (precision == .nvfp4) { - try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.expert_group, 0)), gu_out, chunk_gu); - try experts.nvfp4DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.expert_group, 0)), down_out, chunk_down); - } else { - try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.expert_group, 0)), gu_out, chunk_gu); - try experts.mxfp8DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.expert_group, 0)), down_out, chunk_down); - } - row0 += take; - } - } else { - try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), if (precision == .nvfp4) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); - switch (precision) { - .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), - .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), - } - } - try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); -} - fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, prev_fused: bool, prev_fused_norm: bool, next_v: ?*const layer_plan.Visit, final_rows: usize, segments: []const Segment, seg_meta: []const SegMeta, rows: usize, taps: ?state.Ref, meta_override: ?attention.RowMeta, decode: bool) !void { const lp = m.weight_plan.at(v.layer); const gated = v.hasMessages(); @@ -432,7 +231,9 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la if (v.pass > 1 and v.layer == 6) bankAndReset(m, e, s, rows); const w = &m.weights.layers[v.layer]; if (v.layer != 0 and !prev_fused) widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + e.barrier(); try prepareAttentionInputs(m, e, s, v, rows, prev_fused, prev_fused_norm); + e.barrier(); const knorm = if (gated or lp.kind == .global) at(s.k_norm, 0) else at(s.q_norm, 0); const vnorm = if (gated or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); project(m, e, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); @@ -441,22 +242,29 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la project(m, e, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); project(m, e, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); project(m, e, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); + e.barrier(); try attendSegments(m, e, s, v, segments, seg_meta, meta_override, decode); + e.barrier(); project(m, e, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + e.barrier(); postConv(m, e, s, segments, seg_meta, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0)); const boundary: u32 = if (lp.boundary) lp.blocks_in + 1 else 0; if (gated) { glue.attnPartialAr(&m.glue, e, at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.block_inv_rms, 0), at(s.partial, 0), r(m.weights.mlp_queries[v.layer]), at(s.mlp_ar, 0), @intCast(rows), lp.mlp_sources, boundary); const c = w.controllers.?[3]; const core = v.layer - 6; + e.barrier(); try gates(m, e, s, at(s.mlp_ar, 0), messageRow(s, core, 3, 0), c, at(s.mlp_gated, 0), rows); + e.barrier(); norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); } else glue.attnPartialArNorm(&m.glue, e, at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.block_inv_rms, 0), at(s.partial, 0), r(m.weights.mlp_queries[v.layer]), r(w.mlp_norm), at(s.mlp_normed, 0), @intCast(rows), lp.mlp_sources, boundary); + e.barrier(); if (loop.plan.splitRows(rows)) glue.routerSplit(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_scores, 0), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)) else glue.router(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); - try routedExperts(m, e, s, v.layer, rows); + e.barrier(); + try forward_experts.routed(m, e, s, v.layer, rows); postConv(m, e, s, segments, seg_meta, v.cache_slot, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0)); if (next_v) |nv| { if (canPreFuseNorm(&m.weight_plan, nv)) { @@ -468,7 +276,10 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la } else { runtime(m, e, .mlp_partial, &.{ at(s.partial, 0), at(s.mlp_conv, 0), at(s.p, 0) }, rows * state.hidden, 0); } - if (v.cache_slot == 5) copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); + if (v.cache_slot == 5) { + e.barrier(); + copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); + } } else if (final_rows == rows) { glue.mlpPartialArNorm(&m.glue, e, at(s.partial, 0), at(s.mlp_conv, 0), at(s.blocks, 0), at(s.block_inv_rms, 0), r(m.weights.output_query), r(m.weights.norm), at(s.p, 0), at(s.partial, 0), at(s.mlp_normed, 0), @intCast(rows), m.weight_plan.final_sources); } else { @@ -476,6 +287,7 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la runtime(m, e, .mlp_partial, &.{ at(s.partial, 0), at(s.mlp_conv, 0), at(s.p, 0) }, last * state.hidden, 0); glue.mlpPartialArNorm(&m.glue, e, row(s.partial, last, state.hidden * 4), row(s.mlp_conv, last, state.hidden * 2), at(s.blocks, last * state.block_slots * state.hidden * 2), at(s.block_inv_rms, last * state.block_slots * 4), r(m.weights.output_query), r(m.weights.norm), row(s.p, last, state.hidden * 2), row(s.partial, last, state.hidden * 4), at(s.mlp_normed, 0), 1, m.weight_plan.final_sources); } + e.barrier(); } fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment, meta: []const SegMeta) void { @@ -552,7 +364,7 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, if (use_fused_conv) conv.prepareConvTables(m, s, segments); const pool = mtl.objc.Pool.push(); defer pool.pop(); - const cb = m.queue.commandBuffer(); + var cb = m.queue.commandBuffer(); var need_backup = false; for (segments) |seg| if (seg.cache.pending != null and !seg.cache.conv_backed_up) { need_backup = true; @@ -562,20 +374,37 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, for (segments) |seg| if (seg.cache.pending != null and !seg.cache.conv_backed_up) seg.cache.backupBlit(blit); blit.end(); } - const e = cb.compute(.serial); + const parallel = rows > state.batch_rows; + var e = cb.compute(if (parallel) .concurrent else .serial); + var parts: [cuts.len]mtl.CommandBuffer = undefined; + var n_parts: usize = 0; + defer for (parts[0..n_parts]) |part| part.release(); + errdefer if (n_parts > 0) parts[n_parts - 1].wait(); if (use_fused_conv) conv.declareConvResources(e, s, segments); glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); + e.barrier(); for (options.images) |im| copyBf16(m, e, at(im.buf, im.off), at(s.p, im.row * state.hidden * 2), im.rows * state.hidden); + e.barrier(); const visits = m.weight_plan.visits[0..m.weight_plan.n_visits]; for (visits, 0..) |*v, vi| { const prev_fused = vi > 0 and canPreFuse(v); const prev_fused_norm = vi > 0 and canPreFuseNorm(&m.weight_plan, v); const next_v: ?*const layer_plan.Visit = if (vi + 1 < visits.len) &visits[vi + 1] else null; try visit(m, e, s, v, prev_fused, prev_fused_norm, next_v, final.work_rows, segments, seg_meta[0..segments.len], rows, options.taps, options.meta, options.decode); + if (parallel and options.flight == null and n_parts < cuts.len and vi + 1 == cuts[n_parts]) { + e.end(); + cb.commit(); + parts[n_parts] = cb.retain(); + n_parts += 1; + cb = m.queue.commandBuffer(); + e = cb.compute(.concurrent); + if (use_fused_conv) conv.declareConvResources(e, s, segments); + } } if (options.taps) |to| captureTap(m, e, at(s.mlp_normed, 0), to, final.capture_rows, 3); const logits = if (options.all) at(s.logits_all, 0) else at(segments[0].cache.logits, 0); glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + e.barrier(); sample.encodeForwardDraw(m, e, s, logits, options.draw, options.draws, m.config.text.unpadded_vocab); commitFullHistories(m, e, s, segments, seg_meta[0..segments.len]); e.end(); @@ -588,8 +417,14 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, return; } cb.wait(); + for (parts[0..n_parts]) |part| if (part.failure()) |msg| { + std.log.err("inkling2_loop forward: {s}", .{msg}); + return error.GpuFailed; + }; if (cb.failure()) |msg| { std.log.err("inkling2_loop forward: {s}", .{msg}); return error.GpuFailed; } } + +const cuts = [_]usize{ 2, 12, 24, 36 }; diff --git a/zig/src/families/inkling2/metal/forward_attention.zig b/zig/src/families/inkling2/metal/forward_attention.zig new file mode 100644 index 00000000000..698348b0442 --- /dev/null +++ b/zig/src/families/inkling2/metal/forward_attention.zig @@ -0,0 +1,221 @@ +//! Current attention and convolution routes, staged for independent launches between producer barriers. +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const layer_plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const tree = @import("tree.zig"); +const conv = @import("forward_conv.zig"); +const state = @import("state.zig"); +const Model = @import("model.zig").Model; +const Ref = state.Ref; +const copyBf16 = @import("forward_dispatch.zig").copyBf16; +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn a(x: Ref) attention.Ref { + return .{ .buf = x.buf, .off = x.off }; +} + +pub fn fusedConv(segments: anytype, meta: anytype) bool { + for (meta) |m| if (m.is_tree) return false; + return segments.len > 1 or segments[0].rows <= state.window_rows; +} + +pub fn postConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: anytype, meta: anytype, slot: usize, cs: usize, raw: Ref, weight: ck.Tensor, out: Ref) void { + if (fusedConv(segments, meta)) return conv.postConv(m, e, s, segments, slot, cs, raw, weight, out); + var base: usize = 0; + for (segments, meta) |seg, sm| { + staticPostConv(m, e, s, seg.cache, slot, cs, raw, weight, out, base, seg.rows, sm.is_tree); + base += seg.rows; + } + e.barrier(); +} + +fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref { + const channels = state.convWidth(conv_state); + const taps = cache.staged(slot, conv_state, 0); + copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); + copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); + return taps; +} + +fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void { + const channels = state.convWidth(conv_state); + const taps = stageConvInput(m, e, cache, slot, conv_state, raw, base, rows); + e.barrier(); + if (is_tree) { + tree.convStatic(&m.tree, e, taps, r(weight), at(s.conv_src, base * 4 * 4), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); + } else { + glue.convStatic(&m.glue, e, taps, r(weight), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); + } +} + +pub fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, meta_override: ?attention.RowMeta, decode: bool) !void { + const fused = fusedConv(segments, seg_meta); + if (fused) { + conv.fusedAttention(m, e, s, v, segments); + e.barrier(); + } + const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; + const proj_ref = a(r(m.weights.layers[v.layer].attn.rel_projection)); + const scale_refs = [2]attention.Ref{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }; + var specs: [state.max_segments]ap.BatchedSegSpec = undefined; + for (segments, seg_meta, 0..) |seg, sm, si| { + const layer0 = seg.cache.attentionLayer(&m.weight_plan, v.cache_slot, seg.rows); + const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(seg.cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; + const last_pos: u32 = @intCast(seg.cache.len + (if (sm.is_tree) sm.max_depth else seg.rows - 1)); + specs[si] = .{ .rows = @intCast(seg.rows), .last_pos = last_pos, .layer = layer, .is_tree = sm.is_tree }; + } + if (ap.planBatched(specs[0..segments.len], 24, 8, state.max_attention_stride, 0)) |batch| { + var caches: [state.max_segments]attention.BatchedCache = undefined; + var base: usize = 0; + for (segments, seg_meta, 0..) |seg, sm, si| { + if (!fused) convInputsForAttention(m, e, s, seg.cache, v, base, seg.rows, sm.is_tree); + caches[si] = .{ + .k = a(seg.cache.keys(v.cache_slot)), + .v = a(seg.cache.values(v.cache_slot)), + .row0 = @intCast(base), + .n = @intCast(seg.rows), + .p0 = @intCast(seg.cache.len), + .ring = specs[si].layer.ring, + }; + base += seg.rows; + } + e.barrier(); + const rr = ap.Rows{ .rows = batch.total_rows, .heads = 24, .kv_heads = 8, .last_pos = 0, .streams = @intCast(segments.len) }; + const raw_refs = [4]attention.Ref{ a(at(s.q_raw, 0)), a(at(s.k_conv, 0)), a(at(s.v_conv, 0)), a(at(s.rel_raw, 0)) }; + try attention.prepBatched(&m.attention, e, rr, batch.tau, prep, a(at(s.pos, 0)), a(at(s.seg_of, 0)), caches[0..segments.len], raw_refs, scale_refs, a(at(s.q_prep, 0)), a(at(s.rel_prep, 0))); + e.barrier(); + try attention.attendBatched(&m.attention, e, batch, 24, 8, a(at(s.pos, 0)), a(at(s.seg_of, 0)), caches[0..segments.len], a(at(s.q_prep, 0)), a(at(s.rel_prep, 0)), proj_ref, a(at(s.part_o, 0)), a(at(s.part_ml, 0)), a(at(s.sink, 0)), a(at(s.gate, 0)), a(at(s.att, 0))); + return; + } + if (!fused) { + var base: usize = 0; + for (segments, seg_meta) |seg, sm| { + convInputsForAttention(m, e, s, seg.cache, v, base, seg.rows, sm.is_tree); + base += seg.rows; + } + e.barrier(); + } + try attendEach(m, e, s, v, segments, seg_meta, specs[0..segments.len], prep, proj_ref, scale_refs, meta_override, decode); +} + +fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + const k_taps = stageConvInput(m, e, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows); + const v_taps = stageConvInput(m, e, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows); + e.barrier(); + const k_out = at(s.k_conv, base * state.kv_width * 2); + const v_out = at(s.v_conv, base * state.kv_width * 2); + const k_in = at(s.k_norm, base * state.hidden * 2); + const v_norm = if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + const v_in = at(v_norm.buf, v_norm.off + base * state.hidden * 2); + if (is_tree) { + const src = at(s.conv_src, base * 4 * 4); + switch (w.attn.k_conv) { + .static => |kw| tree.convStatic(&m.tree, e, k_taps, r(kw), src, k_out, @intCast(rows), state.kv_width), + .dynamic => |kd| tree.convDynamic(&m.tree, e, k_taps, k_in, r(kd.static_w), r(kd.projection), src, k_out, @intCast(rows), state.kv_width), + } + switch (w.attn.v_conv) { + .static => |vw| tree.convStatic(&m.tree, e, v_taps, r(vw), src, v_out, @intCast(rows), state.kv_width), + .dynamic => |vd| tree.convDynamic(&m.tree, e, v_taps, v_in, r(vd.static_w), r(vd.projection), src, v_out, @intCast(rows), state.kv_width), + } + return; + } + switch (w.attn.k_conv) { + .static => |kw| switch (w.attn.v_conv) { + .static => |vw| glue.convStaticKv(&m.glue, e, k_taps, r(kw), k_out, v_taps, r(vw), v_out, @intCast(rows), state.kv_width), + .dynamic => |vd| { + glue.convStatic(&m.glue, e, k_taps, r(kw), k_out, @intCast(rows), state.kv_width); + glue.convDynamic(&m.glue, e, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width); + }, + }, + .dynamic => |kd| switch (w.attn.v_conv) { + .dynamic => |vd| glue.convDynamicKv(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, v_taps, v_in, r(vd.static_w), r(vd.projection), v_out, @intCast(rows), state.kv_width), + .static => |vw| { + glue.convDynamic(&m.glue, e, k_taps, k_in, r(kd.static_w), r(kd.projection), k_out, @intCast(rows), state.kv_width); + glue.convStatic(&m.glue, e, v_taps, r(vw), v_out, @intCast(rows), state.kv_width); + }, + }, + } +} + +fn attendEach(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, specs: []const ap.BatchedSegSpec, prep_cfg: ap.Prep, proj_ref: attention.Ref, scale_refs: [2]attention.Ref, meta_override: ?attention.RowMeta, decode: bool) !void { + var launches: [state.max_segments]ap.Launch = undefined; + var tree_launches: [state.max_segments]ap.TreeLaunch = undefined; + var layers: [state.max_segments]ap.Layer = undefined; + var rrs: [state.max_segments]ap.Rows = undefined; + var strides: [state.max_segments]usize = undefined; + var metas: [state.max_segments]attention.RowMeta = undefined; + var kvs: [state.max_segments]attention.Cache = undefined; + var bases: [state.max_segments]usize = undefined; + var starts: [state.max_segments]u32 = undefined; + var base: usize = 0; + for (segments, 0..) |seg, si| { + const rows = seg.rows; + const cache = seg.cache; + const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, rows); + bases[si] = base; + starts[si] = @intCast(cache.len); + layers[si] = .{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; + rrs[si] = .{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = specs[si].last_pos, .streams = 1 }; + metas[si] = meta_override orelse attention.RowMeta{ + .pos = a(at(s.pos, base * 4)), + .seg_of = a(at(s.seg_of, base * 4)), + .segs = a(at(s.segs, 0)), + .prompt_segs = a(at(s.segs, si * @sizeOf(ap.Seg))), + }; + kvs[si] = .{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }; + base += rows; + } + for (seg_meta, 0..) |sm, si| { + const b = bases[si]; + const raw_refs = [4]attention.Ref{ a(at(s.q_raw, b * state.query_width * 2)), a(at(s.k_conv, b * state.kv_width * 2)), a(at(s.v_conv, b * state.kv_width * 2)), a(at(s.rel_raw, b * state.rel_width * 2)) }; + const q_ref = a(at(s.q_prep, b * state.query_width * 2)); + const rel_ref = a(at(s.rel_prep, b * state.rel_width * 2)); + if (sm.is_tree) { + attention.prepTree(&m.attention, e, rrs[si], layers[si], prep_cfg, metas[si], raw_refs, scale_refs, q_ref, rel_ref, kvs[si]); + } else { + strides[si] = ap.slotsFor(layers[si], @as(usize, specs[si].last_pos) + 1); + if (strides[si] > state.max_attention_stride) return error.Inkling2Partials; + attention.prep(&m.attention, e, rrs[si], layers[si], prep_cfg, metas[si], raw_refs, scale_refs, q_ref, rel_ref, kvs[si]); + } + } + e.barrier(); + var ran_prefix = false; + for (seg_meta, 0..) |sm, si| { + if (!sm.is_tree) continue; + const b = bases[si]; + tree_launches[si] = try ap.attendTree(rrs[si], layers[si], state.max_attention_stride, starts[si]); + if (attention.treePrefix(&m.attention, e, tree_launches[si], rrs[si], layers[si], metas[si], a(at(s.q_prep, b * state.query_width * 2)), kvs[si], a(at(s.rel_prep, b * state.rel_width * 2)), proj_ref, a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)), a(at(s.tree_tail_o, b * 2 * 24 * ap.head_dim * 4)), a(at(s.tree_tail_ml, b * 24 * 16)))) { + ran_prefix = true; + } + } + if (ran_prefix) e.barrier(); + for (seg_meta, 0..) |sm, si| { + const b = bases[si]; + const q_ref = a(at(s.q_prep, b * state.query_width * 2)); + const rel_ref = a(at(s.rel_prep, b * state.rel_width * 2)); + const po_ref = a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)); + const pml_ref = a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)); + if (sm.is_tree) { + attention.treePartials(&m.attention, e, tree_launches[si], rrs[si], layers[si], metas[si], a(at(s.tree_paths, b * state.window_rows * 4)), a(at(s.tree_tail_o, b * 2 * 24 * ap.head_dim * 4)), a(at(s.tree_tail_ml, b * 24 * 16)), q_ref, kvs[si], rel_ref, proj_ref, po_ref, pml_ref); + } else { + launches[si] = try attention.partialsReusable(&m.attention, e, rrs[si], layers[si], @intCast(strides[si]), 0, metas[si], q_ref, kvs[si], rel_ref, proj_ref, po_ref, pml_ref, m.relbias_min, segments.len, false, decode, a(at(s.rel_bias, 0))); + } + } + e.barrier(); + for (seg_meta, 0..) |sm, si| { + const b = bases[si]; + const partials_rh = if (sm.is_tree) tree_launches[si].partials_rh else launches[si].partials_rh; + const subs = if (sm.is_tree) @as(u32, 1) else launches[si].subs; + attention.mergeRaw(&m.attention, e, rrs[si], layers[si], partials_rh, subs, metas[si], a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)), a(at(s.sink, b * 24 * 2)), a(at(s.gate, b * state.query_width * 2)), a(at(s.att, b * state.query_width * 2))); + } + e.barrier(); +} diff --git a/zig/src/families/inkling2/metal/forward_conv.zig b/zig/src/families/inkling2/metal/forward_conv.zig index 4653def1356..6e5e2b7d649 100644 --- a/zig/src/families/inkling2/metal/forward_conv.zig +++ b/zig/src/families/inkling2/metal/forward_conv.zig @@ -153,6 +153,7 @@ pub fn fusedAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, stageConvStatic(m, e, segs_ref, r(w.attn.k_conv.static), r(w.attn.v_conv.static), segments.len, state.kv_width, 2); } else { stageConvSegs(m, e, segs_ref, segments.len, state.kv_width, 2); + e.barrier(); if (w.attn.k_conv == .dynamic and w.attn.v_conv == .dynamic) { var total: usize = 0; for (segments) |seg| total += seg.rows; diff --git a/zig/src/families/inkling2/metal/forward_dispatch.zig b/zig/src/families/inkling2/metal/forward_dispatch.zig new file mode 100644 index 00000000000..9e0c00083da --- /dev/null +++ b/zig/src/families/inkling2/metal/forward_dispatch.zig @@ -0,0 +1,18 @@ +//! Existing runtime and BF16-copy encoders shared by the forward's extracted scheduling helpers. +const mtl = @import("metal"); +const state = @import("state.zig"); +const model_file = @import("model.zig"); +const Model = model_file.Model; +const Ref = state.Ref; +const RArgs = extern struct { count: u32, boundary: u32 = 0 }; + +pub fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { + e.setPipeline(m.runtime[@backingInt(op)]); + for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); + e.setValue(RArgs{ .count = @intCast(count), .boundary = @intCast(boundary) }, refs.len); + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(256, 1, 1)); +} + +pub fn copyBf16(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .copy_bf16, &.{ from, to }, count, 0); +} diff --git a/zig/src/families/inkling2/metal/forward_experts.zig b/zig/src/families/inkling2/metal/forward_experts.zig new file mode 100644 index 00000000000..489e4d64a56 --- /dev/null +++ b/zig/src/families/inkling2/metal/forward_experts.zig @@ -0,0 +1,91 @@ +//! Mini's routed experts for one visit: the experts' launches in turn, a barrier after each step a later launch reads. +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const experts = @import("experts.zig"); +const state = @import("state.zig"); +const Model = @import("model.zig").Model; + +const Ref = state.Ref; + +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn row(buf: mtl.Buffer, i: usize, row_bytes: usize) Ref { + return at(buf, i * row_bytes); +} +fn x(x_: Ref) experts.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} + +/// Ends with a barrier: the combine's output is written. +pub fn routed(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { + const w = &m.weights.layers[layer]; + const lp = m.weight_plan.at(@intCast(layer)).precision; + const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = if (lp == .mxfp8) .mxfp8 else .nvfp4 }; + if (lp == .tfq5) { + try m.dispatchTfq5Moe(e, w.tfq5 orelse return error.Tfq5NotLoaded, s.mlp_normed, s.route_ids, s.gu, s.down, rows); + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + e.barrier(); + return; + } + if (lp == .tfq3) { + const pipes = if (m.tfq3_pipes) |*p| p else return error.Tfq3NotLoaded; + try pipes.dispatch(e, w.tfq3 orelse return error.Tfq3NotLoaded, at(s.mlp_normed, 0), at(s.route_ids, 0), at(s.gu, 0), at(s.down, 0), rows); + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + e.barrier(); + return; + } + const precision: experts.Format = if (lp == .nvfp4) .nvfp4 else if (lp == .mxfp8) .mxfp8 else return error.UnsupportedInkling2ExpertFormat; + const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; + if (m.experts.mma != null and rows >= experts.mma_rows) { + // A row's sums are the same on either path, so a chunk or window takes the one that fits its width. + const nv = precision == .nvfp4; + const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; + const down_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) } else null; + try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); + e.barrier(); + try experts.mma(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.mma(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call); + } else if (rows >= 2) { + var row0: usize = 0; + while (row0 < rows) { + const take: usize = @min(rows - row0, experts.max_grouped_rows); + const chunk_gu = experts.Call{ .rows = @intCast(take), .k = state.hidden, .n = state.intermediate, .format = precision }; + const chunk_down = experts.Call{ .rows = @intCast(take), .k = state.intermediate, .n = state.hidden, .format = precision }; + const x_in = x(row(s.mlp_normed, row0, state.hidden * 2)); + const ids_in = x(row(s.route_ids, row0, state.experts_per_token * 4)); + const gu_out = x(row(s.gu, row0, state.experts_per_token * state.intermediate * 2)); + const down_out = x(row(s.down, row0, state.experts_per_token * state.hidden * 2)); + // The chunks share the bucket table: each chunk's steps run in turn. + if (row0 > 0) e.barrier(); + try experts.groupBuckets(&m.experts, e, ids_in, x(at(s.expert_group, 0)), chunk_gu); + e.barrier(); + if (precision == .nvfp4) { + try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.expert_group, 0)), gu_out, chunk_gu); + e.barrier(); + try experts.nvfp4DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.expert_group, 0)), down_out, chunk_down); + } else { + try experts.guGrouped(&m.experts, e, x_in, x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.expert_group, 0)), gu_out, chunk_gu); + e.barrier(); + try experts.mxfp8DownGrouped(&m.experts, e, gu_out, x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.expert_group, 0)), down_out, chunk_down); + } + row0 += take; + } + } else { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), if (precision == .nvfp4) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + e.barrier(); + switch (precision) { + .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + } + } + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + e.barrier(); +} diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig index 81233d7caea..4a366024eaf 100644 --- a/zig/src/families/inkling2/metal/glue.zig +++ b/zig/src/families/inkling2/metal/glue.zig @@ -291,6 +291,7 @@ pub fn routerSplit(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: R inline for (.{ x, weight, scores }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(RouteArgs{ .rows = rows }, 3); e.dispatchGroups(mtl.Size.of(experts / 32, rows, 1), unit); + e.barrier(); e.setPipeline(p.route_select); inline for (.{ scores, bias, ids, weights }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(RouteArgs{ .rows = rows }, 4); diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig index 64df1f503c1..533b04ce590 100644 --- a/zig/src/families/inkling2/metal/loop.zig +++ b/zig/src/families/inkling2/metal/loop.zig @@ -103,10 +103,12 @@ pub fn gatesSplit(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, m_ bind(e, &.{ h, m, normalized }); e.setValue(args, 3); e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.down); bind(e, &.{ normalized, down, zeta }); e.setValue(args, 3); e.dispatchGroups(mtl.Size.of(rank / 32, rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); e.setPipeline(p.apply); bind(e, &.{ h, m, zeta, forget, gain, out }); e.setValue(args, 6); diff --git a/zig/src/families/inkling2/metal/tfq3_pipelines.zig b/zig/src/families/inkling2/metal/tfq3_pipelines.zig index 525728b93cb..88646888f3b 100644 --- a/zig/src/families/inkling2/metal/tfq3_pipelines.zig +++ b/zig/src/families/inkling2/metal/tfq3_pipelines.zig @@ -110,6 +110,7 @@ pub const Pipelines = struct { e.setBuffer(p.xrot, 0, 1); e.setValue(a, 2); e.dispatchGroups(mtl.Size.of(layer.hidden / 128, rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); if (layer.has_tfq4) { const t4 = layer.tables4 orelse return error.MissingTfq4Tables; @@ -125,6 +126,7 @@ pub const Pipelines = struct { e.setBuffer(act_rot_gu.buf, act_rot_gu.off, 7); e.setValue(a, 8); e.dispatchGroups(mtl.Size.of(layer.inter / 128, slots, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.moe4_down); e.setBuffer(layer.weights, 0, 0); @@ -151,6 +153,7 @@ pub const Pipelines = struct { e.setBuffer(act_rot_gu.buf, act_rot_gu.off, 6); e.setValue(a, 7); e.dispatchGroups(mtl.Size.of(layer.inter / 128, slots, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); e.setPipeline(p.moe_down); e.setBuffer(layer.weights, 0, 0); From 2b6512acd88c85c42dafdc163a3aff93cb91c9fa Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:53:14 -0500 Subject: [PATCH 04/13] inkling2 metal: routed experts on the tensor units at every width, so a row's sums never depend on its chunk --- zig/inkling2_source_owners_host.zig | 5 +- .../metal/inkling2/experts_sources.zig | 2 + .../metal/inkling2/experts_units.metal | 137 ++++++++ zig/kernels/metal/inkling2/units.metal | 43 +++ zig/kernels/metal/inkling2_facade.zig | 1 + zig/kernels/metal/inkling2_sources.zig | 1 + zig/runtime_sources/completion.zig | 1 + .../contract/inkling2_units_metal_records.zig | 20 ++ zig/src/core/contract/registry_joins.zig | 2 + zig/src/families/inkling2/metal/experts.zig | 52 +++ .../inkling2/metal/forward_experts.zig | 11 +- zig/tests/contract/metal_family_limits.zig | 6 + .../contract/metal_inkling2_controls_host.zig | 1 + zig/tests/contract/metal_inkling2_main.zig | 4 + zig/tests/contract/metal_inkling2_units.zig | 319 ++++++++++++++++++ .../metal_inkling2_units_controls.zig | 65 ++++ zig/tests/contract/metal_limits.zig | 1 + zig/tests/contract/metal_mapping_test.zig | 12 + 18 files changed, 680 insertions(+), 3 deletions(-) create mode 100644 zig/kernels/metal/inkling2/experts_units.metal create mode 100644 zig/kernels/metal/inkling2/units.metal create mode 100644 zig/src/core/contract/inkling2_units_metal_records.zig create mode 100644 zig/tests/contract/metal_inkling2_units.zig create mode 100644 zig/tests/contract/metal_inkling2_units_controls.zig diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index 815e434218f..5edfaf4bea8 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -1,4 +1,4 @@ -//! Independent byte identity receipt against the supplied main's assembled libraries. +//! Assembled runtime libraries match their reviewed source pins. const std = @import("std"); const ink = @import("inkling2_metal"); const ks = @import("kernel_sources"); @@ -35,12 +35,13 @@ test "every assembled glue kernel uses one scalar or vector width for positional } } } -test "every current generated Inkling and LFM2 library is byte-identical to supplied main" { +test "every current generated Inkling and LFM2 library matches its reviewed source pins" { try equal(ink.attention, 28563, "0969f2367a5955f0215ee82017fe536b85d5b9a5f763942383a4f90d1cda6f60"); try equal(ink.prompt_attention, 36507, "2e690463846a822b5c087139eaa3dfbc9a980caa7753e36cb3562afc88a17abd"); try equal(ink.prompt_attention_pre_m5, 36531, "28b71a25e1aab7174cf121f3ae05f84afb165970443a91f6978c06628630935b"); try equal(ink.glue, 41376, "d314051ebd95a9684bdc83aa639224d1659d970fea54b4d9197fc1733db61ca3"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); + try equal(ink.experts_units, 64267, "7154264b45db57a5ae9ae71384aa9f5a212d56802a36affd656846a3cf27ef6b"); try equal(ink.experts_mma, 54957, "dd04bd9b6cd695404966f9b182831a35a987fb7db81aaf44ee6c440d231bca86"); try equal(ink.dense_mma, 5389, "6d0b015dd66035efbd110ae4d8dd690ca677ed9c500a83837aee7269161b334a"); try equal(ink.dense_tiled, 4324, "cdddebd86d265d9a79fd93b80894266750ca267e7ffeb76c481e6e73ab03c3ee"); diff --git a/zig/kernels/metal/inkling2/experts_sources.zig b/zig/kernels/metal/inkling2/experts_sources.zig index 006d1b0f0f0..d2d36d1f964 100644 --- a/zig/kernels/metal/inkling2/experts_sources.zig +++ b/zig/kernels/metal/inkling2/experts_sources.zig @@ -3,3 +3,5 @@ const guard = @import("../threadgroup_source.zig"); pub const experts = guard.normalize(@embedFile("experts.metal") ++ "\n" ++ @embedFile("experts_grouped.metal")); /// The same products on simdgroup matrices, for GPUs without tensor units: after the decode helpers above. pub const experts_mma = guard.normalize(experts ++ @embedFile("experts_mma.metal")); +/// Tensor-unit products use the current packed-weight decoders and the same grouped table layout. +pub const experts_units = guard.normalize(@embedFile("../nax.h") ++ experts ++ @embedFile("units.metal") ++ @embedFile("experts_units.metal")); diff --git a/zig/kernels/metal/inkling2/experts_units.metal b/zig/kernels/metal/inkling2/experts_units.metal new file mode 100644 index 00000000000..58be6a3eafe --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_units.metal @@ -0,0 +1,137 @@ +struct Ink2UnitsArgs { uint k, n, topk, cap; }; +// Inkling 2 Mini's routed experts on the tensor units, after nax.h, experts.metal and units.metal. + +// The columns of a gate-up row and of a down row: constants, since a loop of constant length runs faster here. +#define INK2_GU_K 2304u +#define INK2_DOWN_K 1152u + +// Columns c .. c + 3 of two rows of X (zeros for a row past the expert's pairs) as a left fragment's eight values. +inline tfp::frag ink2_units_x(device const bfloat* x0, device const bfloat* x1, bool live0, bool live1, uint c) { + const bfloat z1 = bfloat(0.0f); + const bfloat4 z = bfloat4(z1, z1, z1, z1); + return tfp::frag(live0 ? *(device const bfloat4*)(x0 + c) : z, live1 ? *(device const bfloat4*)(x1 + c) : z); +} + +// Columns 16b + hx .. + 3 of a packed NVFP4 row as BF16 weights, each as ink2_nv_block decodes it. +inline bfloat4 ink2_nv_quad(device const uchar* w, device const uchar* scales, float phi, uint b, uint hx) { + bfloat4 v; + for (uint j = 0; j < 4u; ++j) { + const uint c = 16u * b + hx + j; + v[j] = bfloat(ink2_nv_weight(w[c / 2u], c, scales[b], phi)); + } + return v; +} + +// Columns 16b + hx .. + 3 of an MXFP8 row as BF16 weights, each as ink2_mx_block decodes it. +inline bfloat4 ink2_mx_quad(device const uchar* w, device const uchar* scales, uint b, uint hx) { + const uint scale = uint(scales[b / 2u]); + bfloat4 v; + for (uint j = 0; j < 4u; ++j) v[j] = ink2_mx_bf(uint(w[16u * b + hx + j]), scale); + return v; +} + +// Threadgroup (x, e): weight rows 32x .. 32x + 31 of expert e by its pairs, 16 a band; FP8 is MXFP8, else NVFP4. +template +inline void ink2_units(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2UnitsArgs& a, uint2 tg, uint sg, uint lane, threadgroup float* part) { + // GU: X is by row and the 2n interleaved gate and up rows give Y[pair][n]; else X is by pair. 32 divides the rows. + const uint K = GU ? INK2_GU_K : INK2_DOWN_K, rows_w = GU ? 2u * a.n : a.n, steps = K / 128u; + const uint expert = tg.y, w0 = 32u * tg.x; + const uint count = counts[expert]; + if (count == 0u) return; + const uint wb = FP8 ? K : K / 2u, sb = FP8 ? K / 32u : K / 16u; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + device const uchar* w = W + ulong(expert) * rows_w * wb + ulong(w0 + hy) * wb; + device const uchar* s = S + ulong(expert) * rows_w * sb + ulong(w0 + hy) * sb; + for (uint band = 0u; band < count; band += 16u) { + const uint m0 = band + hy, m1 = band + hy + 8u; + const bool live0 = m0 < count, live1 = m1 < count; + const uint p0 = members[expert * a.cap + min(m0, count - 1u)], p1 = members[expert * a.cap + min(m1, count - 1u)]; + device const bfloat* x0 = X + ulong(GU ? p0 / a.topk : p0) * K + hx; + device const bfloat* x1 = X + ulong(GU ? p1 / a.topk : p1) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + // Simdgroup s sums the columns of eighth s from zero, 16 an op; the eight partial sums are then added in order. + for (uint b = sg * steps; b < (sg + 1u) * steps; ++b) { + const tfp::frag fa = ink2_units_x(x0, x1, live0, live1, 16u * b); + tfp::frag b0, b1; + if (FP8) { + b0 = tfp::frag(ink2_mx_quad(w, s, b, hx), ink2_mx_quad(w + 8u * wb, s + 8u * sb, b, hx)); + b1 = tfp::frag(ink2_mx_quad(w + 16u * wb, s + 16u * sb, b, hx), ink2_mx_quad(w + 24u * wb, s + 24u * sb, b, hx)); + } else { + b0 = tfp::frag(ink2_nv_quad(w, s, phi, b, hx), ink2_nv_quad(w + 8u * wb, s + 8u * sb, phi, b, hx)); + b1 = tfp::frag(ink2_nv_quad(w + 16u * wb, s + 16u * sb, phi, b, hx), ink2_nv_quad(w + 24u * wb, s + 24u * sb, phi, b, hx)); + } + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0u) { + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is pair row hy + 8 (e >> 2), weight row w0 + hx + (e & 3); hi is 16 weight rows on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong pair = q == 0u ? p0 : p1; + for (uint side = 0u; side < 2u; ++side) { + const uint col = w0 + 16u * side + hx; + const float4 v = side == 0u ? float4(lo[4u * q], lo[4u * q + 1u], lo[4u * q + 2u], lo[4u * q + 3u]) + : float4(hi[4u * q], hi[4u * q + 1u], hi[4u * q + 2u], hi[4u * q + 3u]); + if (GU) { + Y[pair * a.n + col / 2u] = ink2_act(v[0], v[1]); + Y[pair * a.n + col / 2u + 1u] = ink2_act(v[2], v[3]); + } else { + for (uint j = 0u; j < 4u; ++j) Y[pair * a.n + col + j] = bfloat(v[j]); + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2UnitsArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2UnitsArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2UnitsArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2UnitsArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} diff --git a/zig/kernels/metal/inkling2/units.metal b/zig/kernels/metal/inkling2/units.metal new file mode 100644 index 00000000000..7075e8e9e6f --- /dev/null +++ b/zig/kernels/metal/inkling2/units.metal @@ -0,0 +1,43 @@ +// The tensor-unit op Inkling 2 Mini's expert products are built on, after nax.h: FP32 sums of BF16 products. +using namespace metal; + +// (lo | hi) += a (b0 | b1)^T, b's blocks as stored, [output][column]: nax.h's 16x32x16 op without relaxed precision. +inline void ink2_mma(thread tfp::frag& lo, thread tfp::frag& hi, thread const tfp::frag& a, + thread const tfp::frag& b0, thread const tfp::frag& b1) { + using namespace mpp::tensor_ops; + constexpr auto shape = matmul2d_descriptor(16, 32, 16, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + auto left = op.template get_left_input_cooperative_tensor(); + auto right = op.template get_right_input_cooperative_tensor(); + auto acc = op.template get_destination_cooperative_tensor, + metal::remove_addrspace_t, float>(); + TF_UNROLL + for (short e = 0; e < 8; e++) { + left[e] = a[e]; + right[e] = b0[e]; + right[8 + e] = b1[e]; + acc[e] = lo[e]; + acc[8 + e] = hi[e]; + } + op.run(left, right, acc); + TF_UNROLL + for (short e = 0; e < 8; e++) { + lo[e] = acc[e]; + hi[e] = acc[8 + e]; + } +} + +// A simdgroup's partial sums into the threadgroup's block, and the eight simdgroups' partials added in order. +inline void ink2_part_put(threadgroup float* part, thread const tfp::frag& lo, thread const tfp::frag& hi, uint sg, uint lane) { + for (uint e = 0u; e < 8u; ++e) { + part[(sg * 16u + e) * 32u + lane] = lo[e]; + part[(sg * 16u + 8u + e) * 32u + lane] = hi[e]; + } +} +inline void ink2_part_sum(threadgroup float* part, thread tfp::frag& lo, thread tfp::frag& hi, uint lane) { + for (uint e = 0u; e < 8u; ++e) + for (uint o = 1u; o < 8u; ++o) { + lo[e] += part[(o * 16u + e) * 32u + lane]; + hi[e] += part[(o * 16u + 8u + e) * 32u + lane]; + } +} diff --git a/zig/kernels/metal/inkling2_facade.zig b/zig/kernels/metal/inkling2_facade.zig index fcabed5813e..0818665efc3 100644 --- a/zig/kernels/metal/inkling2_facade.zig +++ b/zig/kernels/metal/inkling2_facade.zig @@ -7,6 +7,7 @@ pub const prompt_attention_pre_m5 = owner.prompt_attention_pre_m5; pub const glue = owner.glue; pub const experts = owner.experts; pub const experts_mma = owner.experts_mma; +pub const experts_units = owner.experts_units; pub const dense_mma = owner.dense_mma; pub const dense_tiled = owner.dense_tiled; pub const loop = owner.loop; diff --git a/zig/kernels/metal/inkling2_sources.zig b/zig/kernels/metal/inkling2_sources.zig index 95d199a3420..200a2f0da96 100644 --- a/zig/kernels/metal/inkling2_sources.zig +++ b/zig/kernels/metal/inkling2_sources.zig @@ -8,6 +8,7 @@ pub const experts = @import("inkling2/experts_sources.zig").experts; pub const experts_mma = @import("inkling2/experts_sources.zig").experts_mma; pub const dense_mma = @import("inkling2/dense_sources.zig").dense_mma; pub const dense_tiled = @import("inkling2/dense_sources.zig").dense_tiled; +pub const experts_units = @import("inkling2/experts_sources.zig").experts_units; pub const loop = @import("inkling2/loop_sources.zig").loop; pub const loop_mma = @import("inkling2/loop_sources.zig").loop_mma; pub const runtime = @import("inkling2/runtime_sources.zig").runtime; diff --git a/zig/runtime_sources/completion.zig b/zig/runtime_sources/completion.zig index 70d2c4c76d6..4af3e3088fc 100644 --- a/zig/runtime_sources/completion.zig +++ b/zig/runtime_sources/completion.zig @@ -173,5 +173,6 @@ fn inkling2(s: *Set) !void { try s.raw("inkling2", "tfq3", ks.inkling2_tfq3); try s.fragments("inkling2", "vision", src.vision); try s.add("inkling2", "inkling2_dflash2", src.inkling2_dflash2, precise()); + if (s.units) try s.raw("inkling2", "experts_units", src.experts_units); try s.raw("inkling2", if (s.units) "inkling2_dspark" else "inkling2_dspark_pre_m5", if (s.units) src.inkling2_dspark else src.inkling2_dspark_pre_m5); } diff --git a/zig/src/core/contract/inkling2_units_metal_records.zig b/zig/src/core/contract/inkling2_units_metal_records.zig new file mode 100644 index 00000000000..553d9d33b79 --- /dev/null +++ b/zig/src/core/contract/inkling2_units_metal_records.zig @@ -0,0 +1,20 @@ +//! Inkling 2 Mini's tensor-unit expert launches: tensor-op kernels, so no M1/M2 compile and 256 reserved threads. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 units tf_ink2_nvfp4_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, +}; + +test "Inkling2 units launches reserve their threads and carry no M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(!record.offline); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 units ")); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index a64e5ecafec..1f273aae54c 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -137,6 +137,7 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("inkling2_experts_metal_records.zig").records ++ @import("inkling2_mma_metal_records.zig").records ++ @import("inkling2_dense_metal_records.zig").records ++ + @import("inkling2_units_metal_records.zig").records ++ @import("inkling2_loop_metal_records.zig").records ++ @import("inkling2_runtime_metal_records.zig").records ++ @import("inkling2_tree_metal_records.zig").records ++ @@ -196,6 +197,7 @@ test { _ = @import("inkling2_experts_metal_records.zig"); _ = @import("inkling2_mma_metal_records.zig"); _ = @import("inkling2_dense_metal_records.zig"); + _ = @import("inkling2_units_metal_records.zig"); _ = @import("inkling2_loop_metal_records.zig"); _ = @import("inkling2_runtime_metal_records.zig"); _ = @import("inkling2_tree_metal_records.zig"); diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 44670af7628..d83ded8a17e 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -51,7 +51,13 @@ const MmaGroupArgs = extern struct { pairs: u32, experts: u32, cap: u32 }; const MmaArgs = extern struct { k: u32, n: u32, topk: u32, cap: u32 }; pub const Globals = struct { amax: Ref, denominator: Ref }; +/// The columns the units kernels read a row: experts_units.metal's INK2_GU_K and INK2_DOWN_K. +const units_gu_k = 2304; +const units_down_k = 1152; +const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units" }; + pub const Pipelines = struct { + units: ?[4]mtl.Pipeline = null, entries: [function_names.len]mtl.Pipeline, /// Each expert's count, then its route pairs: launches in one encoder run in order, so they share it. groups: ?mtl.Buffer = null, @@ -62,6 +68,7 @@ pub const Pipelines = struct { var out = try loadSource(device, src.experts); errdefer out.deinit(); try out.loadMma(device, src.experts_mma); + if (device.tensorUnits()) try out.loadUnits(device, src.experts_units); return out; } @@ -90,6 +97,22 @@ pub const Pipelines = struct { p.group_wide = wide; } + /// The tensor-unit kernels from `text`; the contract's controls pass an edited one. The GPU must have the units. + pub fn loadUnits(p: *Pipelines, device: mtl.Device, text: []const u8) !void { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: [4]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for (units_names, &pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + if (pipe.maxThreads() < 256) return error.ExpertThreads; + } + if (p.units) |old| for (old) |pipe| pipe.deinit(); + p.units = pipes; + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); @@ -111,6 +134,7 @@ pub const Pipelines = struct { } pub fn deinit(p: *Pipelines) void { + if (p.units) |pipes| for (pipes) |pipe| pipe.deinit(); if (p.mma) |pipes| for (pipes) |pipe| pipe.deinit(); if (p.groups) |buf| buf.deinit(); if (p.group_wide) |pipe| pipe.deinit(); @@ -273,6 +297,34 @@ pub fn mma(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Re e.dispatchGroups(mtl.Size.of(weight_rows / mma_tile_rows, c.experts, 1), mtl.Size.of(256, 1, 1)); } +/// gu, or the down products (`down`), after group on the tensor units: an op is 16 of an expert's pairs by 32 rows. +pub fn units(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + try plan.check(c); + const pipes = p.units orelse return error.NoTensorUnits; + if (c.rows > mma_cap or c.experts > plan.expert_count) return error.BadExpertShape; + const table = p.groups orelse return error.NoSimdgroupMatrices; + const counts = Ref{ .buf = table }; + const members = Ref{ .buf = table, .off = plan.expert_count * @sizeOf(u32) }; + const value = MmaArgs{ .k = c.k, .n = c.n, .topk = c.topk, .cap = mma_cap }; + // Gate and up rows interleave, so gu has two weight rows an output; the kernels fix the columns of each product. + const weight_rows = if (down) c.n else 2 * c.n; + if (c.k != @as(u32, if (down) units_down_k else units_gu_k) or weight_rows % 32 != 0) return error.BadExpertShape; + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ x, w, scales, g.amax, g.denominator, counts, members, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(value, 8); + e.setPipeline(pipes[@intFromBool(down)]); + }, + .mxfp8 => { + for ([_]Ref{ x, w, scales, counts, members, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(value, 6); + e.setPipeline(pipes[2 + @as(usize, @intFromBool(down))]); + }, + } + e.dispatchGroups(mtl.Size.of((weight_rows + 31) / 32, c.experts, 1), mtl.Size.of(256, 1, 1)); +} + /// Bucket route pairs by expert ID into <= 8-pair work items on GPU without host readback. pub fn groupBuckets(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, out: Ref, c: Call) !void { try plan.checkGrouped(c); diff --git a/zig/src/families/inkling2/metal/forward_experts.zig b/zig/src/families/inkling2/metal/forward_experts.zig index 489e4d64a56..569ff06e90a 100644 --- a/zig/src/families/inkling2/metal/forward_experts.zig +++ b/zig/src/families/inkling2/metal/forward_experts.zig @@ -42,7 +42,16 @@ pub fn routed(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: } const precision: experts.Format = if (lp == .nvfp4) .nvfp4 else if (lp == .mxfp8) .mxfp8 else return error.UnsupportedInkling2ExpertFormat; const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; - if (m.experts.mma != null and rows >= experts.mma_rows) { + if (m.experts.units != null) { + const nv = precision == .nvfp4; + const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; + const down_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) } else null; + try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); + e.barrier(); + try experts.units(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), gu_globals, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.units(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), down_globals, x(at(s.down, 0)), down_call); + } else if (m.experts.mma != null and rows >= experts.mma_rows) { // A row's sums are the same on either path, so a chunk or window takes the one that fits its width. const nv = precision == .nvfp4; const gu_globals: ?experts.Globals = if (nv) .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) } else null; diff --git a/zig/tests/contract/metal_family_limits.zig b/zig/tests/contract/metal_family_limits.zig index 0f582ab7e2c..472ef4af081 100644 --- a/zig/tests/contract/metal_family_limits.zig +++ b/zig/tests/contract/metal_family_limits.zig @@ -16,6 +16,10 @@ pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, const raw = @import("inkling2_metal").vision; return .{ .decl = d, .function = fun, .here = try tf.frags.source(device, a, raw), .pre_m5 = try preM5(a, "", raw) }; } + if (std.mem.startsWith(u8, d.name, "metal inkling2 units ")) { + if (!assemble) return @as(Launch, undefined); + return .{ .decl = d, .function = fun, .here = @import("inkling2_metal").experts_units, .pre_m5 = "" }; + } if (std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) { if (!assemble) return @as(Launch, undefined); const m = @import("inkling2_metal"); @@ -36,6 +40,8 @@ pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, @import("inkling2_metal").small_ops else if (std.mem.startsWith(u8, d.name, "metal inkling2 loop ")) @import("inkling2_metal").loop + else if (std.mem.startsWith(u8, d.name, "metal inkling2 units ")) + @import("inkling2_metal").experts_units else if (std.mem.startsWith(u8, d.name, "metal inkling2 experts ")) @import("inkling2_metal").experts else if (std.mem.startsWith(u8, d.name, "metal inkling2 mma tf_ink2_dense")) diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig index a68010a5077..29de18a576c 100644 --- a/zig/tests/contract/metal_inkling2_controls_host.zig +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -12,6 +12,7 @@ test { _ = @import("metal_inkling2_dense_mma_controls.zig"); _ = @import("metal_inkling2_dense_tiled_controls.zig"); _ = @import("metal_inkling2_gates_mma_controls.zig"); + _ = @import("metal_inkling2_units_controls.zig"); _ = @import("metal_inkling2_loop_controls.zig"); _ = @import("metal_inkling2_runtime_controls.zig"); _ = @import("metal_inkling2_dspark_controls.zig"); diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index b27a2a39add..a9876018c72 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -13,6 +13,7 @@ pub const Suites = struct { dense_mma: @import("metal_inkling2_dense_mma.zig").Suite, dense_tiled: @import("metal_inkling2_dense_tiled.zig").Suite, gates_mma: @import("metal_inkling2_gates_mma.zig").Suite, + units: @import("metal_inkling2_units.zig").Suite, loop: @import("metal_inkling2_loop.zig").Suite, runtime: @import("metal_inkling2_runtime.zig").Suite, dspark: @import("metal_inkling2_dspark.zig").Suite, @@ -35,6 +36,7 @@ pub const Suites = struct { .dense_mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dense_tiled = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .gates_mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, @@ -55,6 +57,7 @@ pub const Suites = struct { try s.dense_mma.collect(only); try s.dense_tiled.collect(only); try s.gates_mma.collect(only); + try s.units.collect(only); try s.loop.collect(only); try s.runtime.collect(only); try s.dspark.collect(only); @@ -76,6 +79,7 @@ pub const Suites = struct { s.dense_mma.deinit(); s.dense_tiled.deinit(); s.gates_mma.deinit(); + s.units.deinit(); s.loop.deinit(); s.runtime.deinit(); s.dspark.deinit(); diff --git a/zig/tests/contract/metal_inkling2_units.zig b/zig/tests/contract/metal_inkling2_units.zig new file mode 100644 index 00000000000..6651f25ebe2 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_units.zig @@ -0,0 +1,319 @@ +//! Inkling 2 Mini's routed experts on the tensor units: the same FP64 decode, dot and activation as the M3 entries. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down }; + +/// The columns the kernels fix for each product, and the experts `group` lists. +const gu_k = 2304; +const down_k = 1152; +const experts = 128; +const topk = 2; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu_units", + .nv_down => "tf_ink2_nvfp4_down_units", + .mx_gu => "tf_ink2_mxfp8_gu_units", + .mx_down => "tf_ink2_mxfp8_down_units", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_phi, + .nv_down => .nv_down_phi, + .mx_gu => .mx_gu_scale, + .mx_down => .mx_down_scale, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu; +} +/// An op is 16 columns: the shared bound on its roundings a step, then the eight partial sums and the epilogue. +fn depth(s: c.Shape) usize { + return s.k / 16 * contract.attention_range.mma_step + 8 + 3; +} + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 units tf_ink2_nvfp4_gu_units", + .nv_down => "metal inkling2 units tf_ink2_nvfp4_down_units", + .mx_gu => "metal inkling2 units tf_ink2_mxfp8_gu_units", + .mx_down => "metal inkling2 units tf_ink2_mxfp8_down_units", + }; + return .{ + .name = base, + .accum = .f32, + .depth = depth, + .ops = if (isGu(k)) 12 else 3, + .mids = if (isGu(k)) 3 else 0, + .out = .bf16, + // An expert's pairs go 16 a band: one expert takes every row here, so 20 rows cross a band. + .tiles = .{ .{ .size = 16 }, .{}, .{} }, + .served = if (isGu(k)) + &.{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 20, .n = 16, .k = gu_k } } + else + &.{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 20, .n = 32, .k = down_k } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and explicit BF16 nodes" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; +const Dot = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + kind: Kind, + ctl: controls.Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u8 = &.{}, + scales: []u8 = &.{}, + amax: []f32 = &.{}, + denominator: []f32 = &.{}, + ids: []i32 = &.{}, + refs: [7]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadMma(device, src.experts_mma); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .kind = kind, .ctl = if (control) mutation(kind) else .none }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.a.free(p.scales); + p.a.free(p.amax); + p.a.free(p.denominator); + p.a.free(p.ids); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = &vt, .control = p.ctl.gate() }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(p.shape.k), .n = @intCast(p.shape.n), .experts = experts, .topk = topk, .format = if (isNv(p.kind)) .nvfp4 else .mxfp8 }; + } + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = p.kind; + if (shape.rows == 0 or shape.rows > 40) return false; + if (isGu(k) and (shape.k != gu_k or shape.n == 0 or shape.n > 32 or shape.n % 16 != 0)) return false; + if (!isGu(k) and (shape.k != down_k or shape.n == 0 or shape.n > 64 or shape.n % 32 != 0)) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, if (isGu(k)) shape.rows * shape.k else routes * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + p.ids = try p.a.alloc(i32, routes); + // Expert 2 takes a pair of every row and experts 0 and 1 share the other, so one expert's pairs pass 16. + for (p.ids, 0..) |*id, i| id.* = @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = experts * (if (isGu(k)) 2 * shape.n else shape.n); + p.w = try p.a.alloc(u8, matrices * (if (nv) shape.k / 2 else shape.k)); + p.scales = try p.a.alloc(u8, matrices * (shape.k / @as(usize, if (nv) 16 else 32))); + for (p.w) |*v| v.* = rng.int(u8); + // Weights small enough that the gate and up sums stay in the activation's live range. + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(112 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (nv) { + p.amax = try p.a.alloc(f32, experts); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i % 4)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75 * 64; + } + if (fill == .stress) { + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + @memset(p.scales, if (nv) 0x38 else 127); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + const out = try p.rig.output(p.count() * 2); + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(p.w); + p.refs[2] = try p.rig.input(p.scales); + if (nv) { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[4] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[5] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[6] = out; + } else { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[4] = out; + } + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const nv = isNv(p.kind); + const ids = hr(p.refs[if (nv) 5 else 3]); + const out = hr(p.refs[if (nv) 6 else 4]); + try host.group(&p.pipes, e, ids, p.call()); + e.barrier(); + try host.units(&p.pipes, e, !isGu(p.kind), hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), if (nv) .{ .amax = hr(p.refs[3]), .denominator = hr(p.refs[4]) } else null, out, p.call()); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * topk * p.shape.n; + } + + fn e2(code: u8) f64 { + const v = ([_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[code & 7]; + return if (code & 8 != 0) -v else v; + } + fn e4(code: u8) f64 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const v = if (exponent == 0) @as(f64, @floatFromInt(mantissa)) / 512 else std.math.ldexp(@as(f64, 8 + @as(u16, mantissa)), @as(i32, exponent) - 10); + return if (code & 0x80 != 0) -v else v; + } + fn weight(p: *const Probe, expert: usize, row: usize, col: usize) f64 { + const k = p.shape.k; + const rows_per_expert: usize = if (isGu(p.kind)) 2 * p.shape.n else p.shape.n; + const matrix_row = expert * rows_per_expert + row; + if (!isNv(p.kind)) { + const value = p.w[matrix_row * k + col]; + const scale = p.scales[matrix_row * (k / 32) + col / 32]; + return bf(std.math.ldexp(e4(value), @as(i32, scale) - 127)); + } + const codes = p.w[matrix_row * (k / 2) + col / 2]; + const code = if (col % 2 == 0) codes & 15 else codes >> 4; + const scale = p.scales[matrix_row * (k / 16) + col / 16]; + const factor = bf(p.amax[expert]) / bf(p.denominator[0]); + return bf(@as(f32, @floatCast(e2(code) * e4(scale) * factor))); + } + + fn dot(p: *const Probe, expert: usize, row: usize, x: []const u16, sim: ?Sim) Dot { + var terms: [gu_k]f64 = undefined; + var magnitude: f64 = 0; + for (0..p.shape.k) |col| { + const term = p.weight(expert, row, col) * @as(f64, c.fromBf16(x[col])); + terms[col] = term; + magnitude += @abs(term); + } + return .{ .value = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..p.shape.k]) else blk: { + var sum: f64 = 0; + for (terms[0..p.shape.k]) |term| sum += term; + break :blk sum; + }, .magnitude = magnitude }; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const pair = at / p.shape.n; + const n = at % p.shape.n; + const token = pair / topk; + const expert: usize = @intCast(p.ids[pair]); + const x = if (isGu(p.kind)) p.x[token * p.shape.k ..][0..p.shape.k] else p.x[pair * p.shape.k ..][0..p.shape.k]; + if (!isGu(p.kind)) { + const d = p.dot(expert, n, x, sim); + return .{ .value = bf(d.value), .magnitude = d.magnitude }; + } + const gd = p.dot(expert, 2 * n, x, sim); + const ud = p.dot(expert, 2 * n + 1, x, sim); + const gate = bf(gd.value); + const up = bf(ud.value); + const left = 4 * std.math.tanh(gate / 4) * (1 / (1 + @exp(-gate))); + return .{ .value = bf(left * (25 * std.math.tanh(up / 25))), .magnitude = gd.magnitude + ud.magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [8]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entries exist only where the GPU has tensor units; elsewhere the M3 kernels serve every width. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const label = if (control) mutation(kind).name() else spec(kind, false).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; + +test "contract labels resolve to the four units entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_units, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_units_controls.zig b/zig/tests/contract/metal_inkling2_units_controls.zig new file mode 100644 index 00000000000..ddf0d42aa9c --- /dev/null +++ b/zig/tests/contract/metal_inkling2_units_controls.zig @@ -0,0 +1,65 @@ +//! Count-checked mutations of the tensor-unit expert kernels: every entry has a genuine arithmetic control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + nv_gu_phi, + nv_down_phi, + mx_gu_scale, + mx_down_scale, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_phi => "control: metal inkling2 units tf_ink2_nvfp4_gu_units phi", + .nv_down_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units phi", + .mx_gu_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units scale", + .mx_down_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units scale", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .nv_gu_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + // Both MXFP8 entries decode through one helper; a control compiles only its selected entry. + .mx_gu_scale, .mx_down_scale => .{ .from = "const uint scale = uint(scales[b / 2u]);", .to = "const uint scale = uint(scales[b / 2u]) + 1u;" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts_units); + const change = m.edit(); + if (std.mem.count(u8, src.experts_units, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.experts_units, change.from, change.to); +} + +test "every units control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 units ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts_units, plain); +} + +test "units source exports all four entries after the decode helpers" { + inline for ([_][]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units" }) |name| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, name ++ "(")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_units, "never quantize an activation") != null); +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 72109734454..e2888079854 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -31,6 +31,7 @@ pub fn requireMapped(d: limits.MetalLaunch) !void { } /// Only launches the loader can build on this device enter the limits compiler; declarations are checked first. pub fn supported(device: mtl.Device, d: limits.MetalLaunch) bool { + if (std.mem.startsWith(u8, d.name, "metal inkling2 units ")) return device.tensorUnits(); if (std.mem.eql(u8, d.name, "metal inkling2 vision ik2_gemm_bf16_nt_rows")) return !device.tensorUnits(); if (std.mem.startsWith(u8, d.name, "q27 cache ")) return device.tensorUnits(); if (std.mem.startsWith(u8, d.name, "qwen27 prompt ")) { diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index 8116812b872..9948f9b8af8 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -91,3 +91,15 @@ test "Metal launch map: Inkling2 MMA launches resolve and support all Metal GPUs } try std.testing.expectEqual(@as(usize, 8), count); } + +test "Metal launch map: every expert tensor-unit launch is M5-only and resolves" { + var count: usize = 0; + for (registry.all_metal) |launch| { + if (!std.mem.startsWith(u8, launch.name, "metal inkling2 units ")) continue; + try launches.requireMapped(launch); + try std.testing.expect(!launches.supported(.{ .units = false }, launch)); + try std.testing.expect(launches.supported(.{ .units = true }, launch)); + count += 1; + } + try std.testing.expectEqual(@as(usize, 4), count); +} From 6ce4f719d5376e184fd184c039437a16faffbce1 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:24:41 -0500 Subject: [PATCH 05/13] inkling2 metal: the depth mix reads four values a thread, and each simdgroup folds the partial sums itself --- zig/inkling2_source_owners_host.zig | 4 +- zig/kernels/metal/inkling2/glue.metal | 68 ++++++++++++------- .../contract/inkling2_glue_metal_records.zig | 2 +- zig/src/families/inkling2/metal/glue.zig | 4 +- .../contract/metal_inkling2_glue_controls.zig | 2 +- 5 files changed, 49 insertions(+), 31 deletions(-) diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index 5edfaf4bea8..d2a2fd8a414 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -39,7 +39,7 @@ test "every current generated Inkling and LFM2 library matches its reviewed sour try equal(ink.attention, 28563, "0969f2367a5955f0215ee82017fe536b85d5b9a5f763942383a4f90d1cda6f60"); try equal(ink.prompt_attention, 36507, "2e690463846a822b5c087139eaa3dfbc9a980caa7753e36cb3562afc88a17abd"); try equal(ink.prompt_attention_pre_m5, 36531, "28b71a25e1aab7174cf121f3ae05f84afb165970443a91f6978c06628630935b"); - try equal(ink.glue, 41376, "d314051ebd95a9684bdc83aa639224d1659d970fea54b4d9197fc1733db61ca3"); + try equal(ink.glue, 42623, "0f4564349cd972c641812ab3d1fc71da085b88a045f28c794ecd35ff9718def7"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); try equal(ink.experts_units, 64267, "7154264b45db57a5ae9ae71384aa9f5a212d56802a36affd656846a3cf27ef6b"); try equal(ink.experts_mma, 54957, "dd04bd9b6cd695404966f9b182831a35a987fb7db81aaf44ee6c440d231bca86"); @@ -54,7 +54,7 @@ test "every current generated Inkling and LFM2 library matches its reviewed sour try equal(ink.vision, 40124, "f3bccee002e5b0d7572dc25316538b384e397a4f5dba3f4ac99839e434d848c6"); try equal(ink.inkling2_dflash2, 22370, "74a5e9a2324b5875a754e931243203bf19b426758fe6a2a524c62f6809f96dbd"); try equal(ink.sample, 10443, "747835e5a84d76d7d838958e2677aa5af62e4ebf2e612520bfc759e967d44c81"); - try equal(ks.inkling2_glue, 26731, "93ef5c160698f9d4faa17efe377c6c4370ea7b52ec1fda8ed7c4f6edfb0c9627"); + try equal(ks.inkling2_glue, 27978, "584e06e726d4fc7a74212a04c2cdd3b589b5425871498479ce9597b5d167f65b"); try equal(ks.inkling2_sample, 10443, "747835e5a84d76d7d838958e2677aa5af62e4ebf2e612520bfc759e967d44c81"); try equal(ks.lfm2_prompt_masked.source, 16617, "5b5edd3224410f5bebb192cb2781692e21a17baad26be73b8e842f2bee92b0f0"); try equal(ks.inkling2_runtime, 7891, "9f3cff7027ad7b6b5229956688ae2f4b5e00af30e0bd1761a94f0c4c81fa7b01"); diff --git a/zig/kernels/metal/inkling2/glue.metal b/zig/kernels/metal/inkling2/glue.metal index 462180a49ed..72fbd1e15b1 100644 --- a/zig/kernels/metal/inkling2/glue.metal +++ b/zig/kernels/metal/inkling2/glue.metal @@ -1,11 +1,9 @@ #include #pragma METAL fp contract(off) using namespace metal; - // Inkling 2 Mini glue. Every reduction is FP32; bfloat stores round nearest-even. constant float INKLING_EPS = 1e-6f; constant float INKLING_AR_SCALE = 0x1.555556p-6f; // binary32(1 / 48) - inline float ink_sigmoid(float x) { const float e = precise::exp(-fabs(x)); return x < 0.0f ? precise::divide(e, 1.0f + e) : precise::divide(1.0f, 1.0f + e); @@ -17,7 +15,6 @@ inline float ink_value(const device bfloat* blocks, const device float* partial, uint source, uint sources, uint d) { return source + 1 == sources ? partial[d] : float(blocks[size_t(source) * 2304 + d]); } - // Two BF16 pairs of w and x multiplied and added to sum in column order. inline float ink_pair(float sum, uint w, uint x) { sum += as_type(w << 16u) * as_type(x << 16u); @@ -151,37 +148,58 @@ inline void ink_ar_finish_regs( out[d] = acc; } } -[[max_total_threads_per_threadgroup(256)]] +// Four consecutive values of a source: a completed block's BF16, or the running partial's FP32 for the last source. +inline float4 ink_values(const device bfloat* blocks, const device float* partial, uint source, uint sources, uint d) { + if (source + 1 == sources) return *(const device float4*)(partial + d); + return float4(*(const device bfloat4*)(blocks + size_t(source) * 2304 + d)); +} + +// Threadgroup (q, row): row's sources mixed by query q into out[q * rows + row], four values a thread. +[[max_total_threads_per_threadgroup(576)]] kernel void tf_inkling2_ar( - const device bfloat* blocks_base [[buffer(0)]], const device float* partial_base [[buffer(1)]], - const device float* queries [[buffer(2)]], device float* out_base [[buffer(3)]], + const device bfloat* all_blocks [[buffer(0)]], const device float* all_partial [[buffer(1)]], + const device float* queries [[buffer(2)]], device float* all_out [[buffer(3)]], constant InkARArgs& a [[buffer(4)]], uint t [[thread_index_in_threadgroup]], - uint2 at [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { - const uint q = at.x, row = at.y; + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const uint q = tg.x, row = tg.y, d = 4u * t; if (q >= a.queries || row >= a.rows || a.sources == 0 || a.sources > 5) return; - // Row `row`'s blocks, partial sums and output start that row's stride past the first row's. - const device bfloat* blocks = blocks_base + size_t(row) * a.blocks_stride; - const device float* partial = partial_base + size_t(row) * a.partial_stride; - device float* out = out_base + size_t(row) * a.out_stride; - threadgroup float red[2 * 5 * 8], means[5], weights[5]; - for (uint s = 0; s < a.sources; ++s) { - float ss = 0.0f; - for (uint d = t; d < 2304; d += 256) { - const float x = ink_value(blocks, partial, s, a.sources, d); - ss += x * x; - } - const float reduced = simd_sum(ss); - if (lane == 0) red[s * 8 + t / 32] = reduced; + const device bfloat* blocks = all_blocks + size_t(row) * a.blocks_stride; + const device float* partial = all_partial + size_t(row) * a.partial_stride; + device float* out = all_out + size_t(row) * a.out_stride + size_t(q) * 2304; + // Each of the 18 simdgroups folds the partial sums itself, so no thread waits on another's result. + threadgroup float red[5 * 18], dots[5 * 18]; + float4 x[5]; + for (uint s = 0; s < 5; ++s) { + x[s] = s < a.sources ? ink_values(blocks, partial, s, a.sources, d) : float4(0.0f); + const float4 sq = x[s] * x[s]; + const float reduced = simd_sum((sq.x + sq.y) + (sq.z + sq.w)); + if (lane == 0) red[s * 18 + sg] = reduced; } threadgroup_barrier(mem_flags::mem_threadgroup); - if (t == 0) for (uint s = 0; s < a.sources; ++s) { - float ss = 0.0f; - for (uint j = 0; j < 8; ++j) ss += red[s * 8 + j]; + const float4 query = *(const device float4*)(queries + size_t(q) * 2304 + d); + float means[5]; + for (uint s = 0; s < 5; ++s) { + const float ss = simd_sum(lane < 18u ? red[s * 18 + lane] : 0.0f); means[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_EPS); + const float4 z = query * (x[s] * means[s]); + const float reduced = simd_sum((z.x + z.y) + (z.z + z.w)); + if (lane == 0) dots[s * 18 + sg] = reduced; } threadgroup_barrier(mem_flags::mem_threadgroup); - ink_ar_finish(blocks, partial, queries, out, a.sources, q, 2304, t, lane, red + 40, means, weights); + float ar_weights[5], peak = -INFINITY; + for (uint s = 0; s < 5; ++s) { + const float dot = simd_sum(lane < 18u ? dots[s * 18 + lane] : 0.0f); + ar_weights[s] = dot * INKLING_AR_SCALE; + if (s < a.sources) peak = max(peak, ar_weights[s]); + } + float den = 0.0f; + for (uint s = 0; s < a.sources; ++s) { ar_weights[s] = precise::exp(ar_weights[s] - peak); den += ar_weights[s]; } + float4 acc = float4(0.0f); + for (uint s = 0; s < a.sources; ++s) acc += precise::divide(ar_weights[s], den) * (x[s] * means[s]); + *(device float4*)(out + d) = acc; } + [[max_total_threads_per_threadgroup(256)]] kernel void tf_inkling2_block_inv_rms( const device bfloat* blocks [[buffer(0)]], device float* inv_rms [[buffer(1)]], diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig index 4f15972d54a..5c71c4a3b55 100644 --- a/zig/src/core/contract/inkling2_glue_metal_records.zig +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -2,7 +2,7 @@ const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ .{ .name = "metal inkling2 glue embed_norm tf_inkling2_embed_norm", .threads = 256, .tg_memory = 48, .reserved = 256 }, - .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 256, .tg_memory = 368, .reserved = 256 }, + .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 576, .tg_memory = 720, .reserved = 576 }, .{ .name = "metal inkling2 glue cached_ar tf_inkling2_cached_ar", .threads = 256, .tg_memory = 240, .reserved = 256 }, .{ .name = "metal inkling2 glue block_inv_rms tf_inkling2_block_inv_rms", .threads = 256, .tg_memory = 32, .reserved = 256 }, .{ .name = "metal inkling2 glue attn_partial_ar tf_inkling2_attn_partial_ar", .threads = 256, .tg_memory = 272, .reserved = 256 }, diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig index 4a366024eaf..5fcf3acd5bc 100644 --- a/zig/src/families/inkling2/metal/glue.zig +++ b/zig/src/families/inkling2/metal/glue.zig @@ -76,7 +76,7 @@ pub const Pipelines = struct { "tf_inkling2_attn_partial_ar_norm", "tf_inkling2_mlp_partial_ar_norm", "tf_ink2_argmax", - }, [_]usize{ 256, 256, 256, 256, 256, 256, 32, 256, 32, 256, 256, 32, 32, 32, 32, 32, 32, 128, 128, 128, 256, 256, 256, 256, 256, 1024 }, &pipes) |name, req_threads, *pipe| { + }, [_]usize{ 256, 576, 256, 256, 256, 256, 32, 256, 32, 256, 256, 32, 32, 32, 32, 32, 32, 128, 128, 128, 256, 256, 256, 256, 256, 1024 }, &pipes) |name, req_threads, *pipe| { pipe.* = try mtl.Pipeline.init(device, lib, name, false); made += 1; if (pipe.maxThreads() < req_threads) return error.GlueThreads; @@ -137,7 +137,7 @@ pub fn ar(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, e.setPipeline(p.ar); inline for (.{ blocks, partial, queries, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(ARArgs{ .sources = sources_, .queries = queries_, .rows = batch.rows, .blocks_stride = batch.blocks_stride, .partial_stride = batch.partial_stride, .out_stride = batch.out_stride }, 4); - e.dispatchGroups(mtl.Size.of(queries_, batch.rows, 1), mtl.Size.of(256, 1, 1)); + e.dispatchGroups(mtl.Size.of(queries_, batch.rows, 1), mtl.Size.of(576, 1, 1)); } const BlockInvRmsArgs = extern struct { rows: u32, slot: u32 }; diff --git a/zig/tests/contract/metal_inkling2_glue_controls.zig b/zig/tests/contract/metal_inkling2_glue_controls.zig index 329115c4649..3f05b4054cf 100644 --- a/zig/tests/contract/metal_inkling2_glue_controls.zig +++ b/zig/tests/contract/metal_inkling2_glue_controls.zig @@ -34,7 +34,7 @@ const Edit = struct { from: []const u8, to: []const u8 }; fn edit(kind: p.Kind) Edit { return switch (kind) { .embed_norm => .{ .from = "float(weight[d]) * (float(x[d]) * inverse)", .to = "float(weight[0]) * (float(x[d]) * inverse)" }, - .ar => .{ .from = "weights[s] = dot * INKLING_AR_SCALE;", .to = "weights[s] = dot;" }, + .ar => .{ .from = "ar_weights[s] = dot * INKLING_AR_SCALE;", .to = "ar_weights[s] = dot;" }, .cached_ar => .{ .from = "if (t + 1 < a.sources) means[t] = block_inv_rms[t];", .to = "if (t + 1 < a.sources) means[t] = block_inv_rms[(t + 1) & 3];" }, .block_inv_rms => .{ .from = "if (t == 0) inv_rms[size_t(row) * 4 + a.slot] = inv;", .to = "if (t == 0) inv_rms[size_t(row) * 4 + a.slot] = inv * 2.0f;" }, .attn_partial_ar => .{ .from = "means[a.sources - 1] = part_inv;", .to = "means[a.sources - 1] = part_inv * 2.0f;" }, From ba86e129a5237b01fd013d314a73821432a1a8c7 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:25:18 -0500 Subject: [PATCH 06/13] inkling2 metal: the prompt pass a chunk a call, so other streams decode between a prompt's chunks --- zig/src/families/inkling2/metal/backend.zig | 102 +++------------ zig/src/families/inkling2/metal/prefill.zig | 131 ++++++++++++++++++++ zig/src/families/inkling2/metal/state.zig | 2 + zig/src/native/inkling2_serving_test.zig | 34 +++++ 4 files changed, 183 insertions(+), 86 deletions(-) create mode 100644 zig/src/families/inkling2/metal/prefill.zig diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index 0f5eb1efb11..d23bc5c8fe9 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -11,6 +11,7 @@ const img = @import("images.zig"); const drafter_snap = @import("drafter_snap.zig"); const policy = @import("gpu_tokens_policy.zig"); const draws = @import("draw.zig"); +const prefill = @import("prefill.zig"); const flight = @import("flight.zig"); const sample = @import("sample.zig"); const be = lanes.backend; @@ -107,9 +108,13 @@ pub const Metal = struct { try self.ring.drain(); try validateTaps(&self.model.config, taps); if (!self.prepared) return error.UnpreparedInkling2Taps; - const tp = (try self.cacheOf(stream)).tap; + const cache = try self.cacheOf(stream); + var tp = cache.tap; + const off = st.featureOffset(tp, start, count, self.tap_gen) catch |err| blk: { + tp = cache.fill_tap; + break :blk st.featureOffset(tp, start, count, self.tap_gen) catch return err; + }; const buf = tp.buf orelse return error.Inkling2TapsNotHeld; - const off = try st.featureOffset(tp, start, count, self.tap_gen); return .{ .buffer = @intFromPtr(buf.id), .offset = off, .rows = count, .row_bytes = @intCast(st.feature_row_bytes), .space = .device, .dtype = .bf16 }; } @@ -122,18 +127,18 @@ pub const Metal = struct { return prefillFn(ptr, stream); } - fn nextTapGeneration(self: *Metal) u64 { + pub fn nextTapGeneration(self: *Metal) u64 { self.tap_gen +%= 1; return self.tap_gen; } - fn nextVerifyGeneration(self: *Metal) u64 { + pub fn nextVerifyGeneration(self: *Metal) u64 { self.verify_gen +%= 1; return self.verify_gen; } pub fn backend(self: *Metal) be.Backend { - return .{ .keep_full_lone = true, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + return .{ .keep_full_lone = true, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .reports_fill = true, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; } fn cast(ptr: *anyopaque) *Metal { @@ -158,90 +163,15 @@ pub const Metal = struct { } fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows) !void { - const base = cache.len; - var at: usize = 0; - while (at < ids.len) { - var end = @min(ids.len, at + st.prompt_rows); - if (stream) |sm| { - if (sm.isCancelled()) return error.Cancelled; - for (sm.chunks) |x| if (x > base + at and x < base + end) { - end = x - base; - }; - for (sm.reuse.marks) |x| if (x > base + at and x < base + end) { - end = x - base; - }; - } - const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; - if (s == &self.scratch) _ = self.nextVerifyGeneration(); - const capture = self.prepared and stream != null; - if (capture) _ = self.nextTapGeneration(); - const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; - const rows_of: []const fwd.ImageRows = if (pictures) |p| p.chunk(base + at, base + end) else &.{}; - try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = taps, .images = rows_of }); - if (capture) { - const rows = end - at; - if (self.sink) |k| try k.take(k.ptr, stream.?, .{ - .buffer = @intFromPtr(s.taps.?.id), - .offset = 0, - .rows = @intCast(rows), - .row_bytes = @intCast(st.feature_row_bytes), - .space = .device, - .dtype = .bf16, - }, @intCast(cache.len)); - if (base + end == stream.?.prompt().len) { - if (cache.last_tap == null) { - cache.last_tap = try self.model.device.buffer(st.feature_row_bytes, mtl.ResourceOptions.shared); - if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); - } - const bytes = s.taps.?.slice(u8, rows * st.feature_row_bytes); - @memcpy(cache.last_tap.?.slice(u8, st.feature_row_bytes), bytes[(rows - 1) * st.feature_row_bytes ..][0..st.feature_row_bytes]); - cache.tap = .{ .buf = cache.last_tap, .start = @intCast(cache.len + rows - 1), .rows = 1 }; - } - } - cache.len += end - at; - if (stream) |sm| lanes.prefill_widths.completed(self.gpa, sm, end - at); - at = end; - if (stream) |sm| if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); - } + return prefill.feed(self, cache, ids, stream, pictures); } fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { - const self = cast(ptr); - try self.ring.drain(); - const ids = stream.prompt(); - if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidInklingPrompt; - const min_cap = ids.len + stream.max_new; - const padded = @min(@as(usize, 1048576), min_cap + st.window_rows); - const cap = if (self.held + st.cacheBytes(padded) <= self.options.budget) padded else min_cap; - const need = st.cacheBytes(cap); - if (self.held + need > self.options.budget) { - std.log.warn("inkling2_loop: a stream needs {d:.1} GiB of state; {d:.1} of {d:.1} GiB are held", .{ gib(need), gib(self.held), gib(self.options.budget) }); - return error.InklingStateFull; - } - self.held += need; - errdefer self.held -= need; - if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); - const cache = try self.createCache(cap); - errdefer self.gpa.destroy(cache); - errdefer cache.deinit(); - try self.caches.put(self.gpa, stream, cache); - errdefer _ = self.caches.remove(stream); - stream.cached = 0; - if (stream.reuse.saved) |saved| { - const snap: *const SavedSnap = @ptrCast(@alignCast(saved)); - if (snap.target.at < ids.len) { - if (self.restoreSnap(cache, stream, snap)) { - stream.cached = @intCast(snap.target.at); - } else |_| { - cache.len = 0; - if (self.drafter) |d| d.resetLane(stream); - stream.reuse_failed = true; - } - } else stream.reuse_failed = true; - } - var pictures = try img.Rows.init(self.gpa, self.options.images, stream, cache.len); - defer pictures.deinit(); - try self.feed(cache, ids[cache.len..], stream, &pictures); + return prefill.whole(cast(ptr), stream); + } + + fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, max_rows: u32) !bool { + return prefill.step(cast(ptr), stream, max_rows); } pub fn restoreSnap(self: *Metal, cache: *st.Cache, stream: *lanes.Stream, snap: *const SavedSnap) !void { diff --git a/zig/src/families/inkling2/metal/prefill.zig b/zig/src/families/inkling2/metal/prefill.zig new file mode 100644 index 00000000000..371965567bc --- /dev/null +++ b/zig/src/families/inkling2/metal/prefill.zig @@ -0,0 +1,131 @@ +//! Prompt filling with main's image and snapshot handling, and text chunks that yield between calls. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const fwd = @import("forward.zig"); +const img = @import("images.zig"); +const SavedSnap = @import("drafter_snap.zig").Saved; + +pub fn feed(self: anytype, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows) !void { + var at: usize = 0; + while (at < ids.len) at += try feedChunk(self, cache, ids[at..], stream, pictures); +} + +pub fn feedChunk(self: anytype, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows) !usize { + const base = cache.len; + var end: usize = @min(ids.len, st.prompt_rows); + if (stream) |sm| { + if (sm.isCancelled()) return error.Cancelled; + for (sm.chunks) |x| if (x > base and x < base + end) { + end = x - base; + }; + for (sm.reuse.marks) |x| if (x > base and x < base + end) { + end = x - base; + }; + } + const s = if (end > st.batch_rows) &self.prompt else &self.scratch; + if (s == &self.scratch) _ = self.nextVerifyGeneration(); + const capture = self.prepared and stream != null; + if (capture) _ = self.nextTapGeneration(); + const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; + const rows_of: []const fwd.ImageRows = if (pictures) |p| p.chunk(base, base + end) else &.{}; + try fwd.run(self.model, s, cache, ids[0..end], .{ .taps = taps, .images = rows_of }); + if (capture) { + const rows = end; + if (self.sink) |k| try k.take(k.ptr, stream.?, .{ + .buffer = @intFromPtr(s.taps.?.id), + .offset = 0, + .rows = @intCast(rows), + .row_bytes = @intCast(st.feature_row_bytes), + .space = .device, + .dtype = .bf16, + }, @intCast(cache.len)) else { + cache.fill_tap = .{ .buf = s.taps, .start = @intCast(base), .rows = end, .gen = self.tap_gen }; + } + if (base + end == stream.?.prompt().len) { + if (cache.last_tap == null) { + cache.last_tap = try self.model.device.buffer(st.feature_row_bytes, mtl.ResourceOptions.shared); + if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); + } + const bytes = s.taps.?.slice(u8, rows * st.feature_row_bytes); + @memcpy(cache.last_tap.?.slice(u8, st.feature_row_bytes), bytes[(rows - 1) * st.feature_row_bytes ..][0..st.feature_row_bytes]); + cache.tap = .{ .buf = cache.last_tap, .start = @intCast(cache.len + rows - 1), .rows = 1 }; + } + } + cache.len += end; + if (stream) |sm| { + lanes.prefill_widths.completed(self.gpa, sm, end); + sm.fill_at.store(@intCast(cache.len), .monotonic); + if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); + } + return end; +} + +pub fn opening(self: anytype, stream: *lanes.Stream) !*st.Cache { + try self.ring.drain(); + const ids = stream.prompt(); + if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidInklingPrompt; + const min_cap = ids.len + stream.max_new; + const padded = @min(@as(usize, 1048576), min_cap + st.window_rows); + const cap = if (self.held + st.cacheBytes(padded) <= self.options.budget) padded else min_cap; + const need = st.cacheBytes(cap); + if (self.held + need > self.options.budget) { + std.log.warn("inkling2_loop: a stream needs {d:.1} GiB of state; {d:.1} of {d:.1} GiB are held", .{ gib(need), gib(self.held), gib(self.options.budget) }); + return error.InklingStateFull; + } + self.held += need; + errdefer self.held -= need; + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); + const cache = try self.createCache(cap); + errdefer self.gpa.destroy(cache); + errdefer cache.deinit(); + try self.caches.put(self.gpa, stream, cache); + errdefer _ = self.caches.remove(stream); + stream.cached = 0; + if (stream.reuse.saved) |saved| { + const snap: *const SavedSnap = @ptrCast(@alignCast(saved)); + if (snap.target.at < ids.len) { + if (self.restoreSnap(cache, stream, snap)) { + stream.cached = @intCast(snap.target.at); + } else |_| { + cache.len = 0; + if (self.drafter) |d| d.resetLane(stream); + stream.reuse_failed = true; + } + } else stream.reuse_failed = true; + } + return cache; +} + +pub fn drop(self: anytype, stream: *lanes.Stream) void { + const entry = self.caches.fetchRemove(stream) orelse return; + self.held -= st.cacheBytes(entry.value.capacity); + entry.value.deinit(); + self.gpa.destroy(entry.value); +} + +pub fn whole(self: anytype, stream: *lanes.Stream) !void { + const cache = try opening(self, stream); + errdefer drop(self, stream); + var pictures = try img.Rows.init(self.gpa, self.options.images, stream, cache.len); + defer pictures.deinit(); + try feed(self, cache, stream.prompt()[cache.len..], stream, &pictures); +} + +pub fn step(self: anytype, stream: *lanes.Stream, _: u32) !bool { + if (stream.images.len > 0) { + try whole(self, stream); + return true; + } + try self.ring.drain(); + const cache = self.caches.get(stream) orelse try opening(self, stream); + errdefer drop(self, stream); + const ids = stream.prompt(); + _ = try feedChunk(self, cache, ids[cache.len..], stream, null); + return cache.len == ids.len; +} + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1024.0 * 1024 * 1024); +} diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 3b5a67f3c85..3c1c425ef77 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -109,6 +109,8 @@ pub const Cache = struct { backup: mtl.Buffer, logits: mtl.Buffer, tap: Tap = .{}, + /// A stepped prompt chunk's rows, good until the next forward. + fill_tap: Tap = .{}, last_tap: ?mtl.Buffer = null, key_at: [visit_slots]usize, value_at: [visit_slots]usize, diff --git a/zig/src/native/inkling2_serving_test.zig b/zig/src/native/inkling2_serving_test.zig index 6cd4ced5cf3..ff692ca6a7e 100644 --- a/zig/src/native/inkling2_serving_test.zig +++ b/zig/src/native/inkling2_serving_test.zig @@ -375,3 +375,37 @@ test "Mini Metal verify tree matches serial target bit-for-bit across all branch } } } + +test "Mini Metal fills a prompt a chunk a call to the whole pass's first row and features" { + const dir = try checkpoint(); + const ids = prompt(64, 5); + const cuts = [_]u32{ 20, 41 }; + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 2, .budget = 2 * st.cacheBytes(context) }); + defer target.deinit(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + var whole = try lanes.Stream.init(gpa, .{ .id = "whole", .prompt = &ids, .max_new = made, .drafts = false, .logprobs = 3, .chunks = &cuts }); + defer whole.deinit(gpa); + try b.prefill(&whole); + defer b.release(&whole); + try std.testing.expectEqual(@as(u32, ids.len), whole.fill_at.load(.monotonic)); + var stepped = try lanes.Stream.init(gpa, .{ .id = "stepped", .prompt = &ids, .max_new = made, .drafts = false, .logprobs = 3, .chunks = &cuts }); + defer stepped.deinit(gpa); + defer b.release(&stepped); + var from: u32 = 0; + for ([_]u32{ 20, 41, ids.len }) |end| { + try std.testing.expectEqual(end == ids.len, try b.vtable.prefill_step.?(b.ptr, &stepped, 0)); + try std.testing.expectEqual(end, stepped.fill_at.load(.monotonic)); + // A chunk's rows are held until the next forward, and an earlier chunk's are not. + try std.testing.expectEqual(end - from, (try b.features(&stepped, &taps, from, end - from)).rows); + if (from > 0) try std.testing.expectError(error.Inkling2TapsNotHeld, b.features(&stepped, &taps, 0, from)); + from = end; + } + try std.testing.expectEqualSlices(u8, &(try featureRow(b, &whole, ids.len - 1)), &(try featureRow(b, &stepped, ids.len - 1))); + const whole_first = try b.read(try b.first(&whole, ids.len)); + const whole_row = try b.firstRow(&whole); + try std.testing.expectEqual(whole_first, try b.read(try b.first(&stepped, ids.len))); + try expectFirstRow(whole_row, try b.firstRow(&stepped)); +} From cb094c50923774308b73b4e43f8914554ad7a6c3 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:54:38 -0500 Subject: [PATCH 07/13] inkling2 metal: logits on the tensor units, one pass of the vocabulary for up to 16 rows --- zig/inkling2_source_owners_host.zig | 2 +- .../metal/inkling2/experts_units.metal | 44 +++++ .../contract/inkling2_units_metal_records.zig | 3 +- zig/src/families/inkling2/metal/experts.zig | 16 +- zig/src/families/inkling2/metal/forward.zig | 11 +- .../contract/metal_inkling2_logits_units.zig | 179 ++++++++++++++++++ zig/tests/contract/metal_inkling2_main.zig | 4 + .../metal_inkling2_units_controls.zig | 5 +- zig/tests/contract/metal_mapping_test.zig | 2 +- 9 files changed, 258 insertions(+), 8 deletions(-) create mode 100644 zig/tests/contract/metal_inkling2_logits_units.zig diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index d2a2fd8a414..10784d001ba 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -41,7 +41,7 @@ test "every current generated Inkling and LFM2 library matches its reviewed sour try equal(ink.prompt_attention_pre_m5, 36531, "28b71a25e1aab7174cf121f3ae05f84afb165970443a91f6978c06628630935b"); try equal(ink.glue, 42623, "0f4564349cd972c641812ab3d1fc71da085b88a045f28c794ecd35ff9718def7"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); - try equal(ink.experts_units, 64267, "7154264b45db57a5ae9ae71384aa9f5a212d56802a36affd656846a3cf27ef6b"); + try equal(ink.experts_units, 66778, "31f7f43d6d8662465ddfedbbb0678a0b6260a277d92208ed6a16f5d26148ae6d"); try equal(ink.experts_mma, 54957, "dd04bd9b6cd695404966f9b182831a35a987fb7db81aaf44ee6c440d231bca86"); try equal(ink.dense_mma, 5389, "6d0b015dd66035efbd110ae4d8dd690ca677ed9c500a83837aee7269161b334a"); try equal(ink.dense_tiled, 4324, "cdddebd86d265d9a79fd93b80894266750ca267e7ffeb76c481e6e73ab03c3ee"); diff --git a/zig/kernels/metal/inkling2/experts_units.metal b/zig/kernels/metal/inkling2/experts_units.metal index 58be6a3eafe..f2c3e384448 100644 --- a/zig/kernels/metal/inkling2/experts_units.metal +++ b/zig/kernels/metal/inkling2/experts_units.metal @@ -135,3 +135,47 @@ inline void ink2_units(device const bfloat* X, device const uchar* W, device con threadgroup float part[4096]; ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); } + +struct Ink2LogitArgs { uint rows, vocab; }; + +// Threadgroup (x, y): vocabulary rows 32x .. + 31 by rows 16y .. + 15 of h, summed as the expert products are. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_logits_units( + device const bfloat* X [[buffer(0)]], device const bfloat* W [[buffer(1)]], + device float* Y [[buffer(2)]], constant Ink2LogitArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + const uint n0 = 32u * tg.x, r0 = 16u * tg.y, K = INK2_GU_K; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + const bool live0 = r0 + hy < a.rows, live1 = r0 + hy + 8u < a.rows; + device const bfloat* x0 = X + ulong(r0 + hy) * K + hx; + // A vocabulary row past the end reads the last one: its sums are not stored. + const uint last = a.vocab - 1u; + device const bfloat* w0 = W + ulong(min(n0 + hy, last)) * K + hx; + device const bfloat* w1 = W + ulong(min(n0 + hy + 8u, last)) * K + hx; + device const bfloat* w2 = W + ulong(min(n0 + hy + 16u, last)) * K + hx; + device const bfloat* w3 = W + ulong(min(n0 + hy + 24u, last)) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * (K / 128u); b < (sg + 1u) * (K / 128u); ++b) { + const tfp::frag fa = ink2_units_x(x0, x0 + 8u * K, live0, live1, 16u * b); + const tfp::frag b0 = tfp::frag(*(device const bfloat4*)(w0 + 16u * b), *(device const bfloat4*)(w1 + 16u * b)); + const tfp::frag b1 = tfp::frag(*(device const bfloat4*)(w2 + 16u * b), *(device const bfloat4*)(w3 + 16u * b)); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is row r0 + hy + 8 (e >> 2), vocabulary row n0 + hx + (e & 3); hi is 16 vocabulary rows on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong row = r0 + hy + 8u * q; + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint v = n0 + 16u * side + hx + j; + const float dot = side == 0u ? lo[4u * q + j] : hi[4u * q + j]; + if (v < a.vocab) Y[row * a.vocab + v] = 30.0f * precise::tanh(precise::divide(float(bfloat(dot)), 30.0f)); + } + } +} diff --git a/zig/src/core/contract/inkling2_units_metal_records.zig b/zig/src/core/contract/inkling2_units_metal_records.zig index 553d9d33b79..2b4d85f8dea 100644 --- a/zig/src/core/contract/inkling2_units_metal_records.zig +++ b/zig/src/core/contract/inkling2_units_metal_records.zig @@ -1,4 +1,4 @@ -//! Inkling 2 Mini's tensor-unit expert launches: tensor-op kernels, so no M1/M2 compile and 256 reserved threads. +//! Inkling 2 Mini's tensor-unit launches: tensor-op kernels, so no M1/M2 compile and 256 reserved threads. const std = @import("std"); const M = @import("limits.zig").MetalLaunch; @@ -7,6 +7,7 @@ pub const records = [_]M{ .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_logits_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, }; test "Inkling2 units launches reserve their threads and carry no M1/M2 compile receipts" { diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index d83ded8a17e..281b682fb15 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -54,10 +54,10 @@ pub const Globals = struct { amax: Ref, denominator: Ref }; /// The columns the units kernels read a row: experts_units.metal's INK2_GU_K and INK2_DOWN_K. const units_gu_k = 2304; const units_down_k = 1152; -const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units" }; +const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units" }; pub const Pipelines = struct { - units: ?[4]mtl.Pipeline = null, + units: ?[units_names.len]mtl.Pipeline = null, entries: [function_names.len]mtl.Pipeline, /// Each expert's count, then its route pairs: launches in one encoder run in order, so they share it. groups: ?mtl.Buffer = null, @@ -101,7 +101,7 @@ pub const Pipelines = struct { pub fn loadUnits(p: *Pipelines, device: mtl.Device, text: []const u8) !void { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); - var pipes: [4]mtl.Pipeline = undefined; + var pipes: [units_names.len]mtl.Pipeline = undefined; var made: usize = 0; errdefer for (pipes[0..made]) |pipe| pipe.deinit(); for (units_names, &pipes) |name, *pipe| { @@ -373,3 +373,13 @@ pub fn guGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, sca .mxfp8 => return mxfp8GuGrouped(p, e, x, w, scales, group_buf, out, c), } } + +const LogitArgs = extern struct { rows: u32, vocab: u32 }; +/// Rows of h against the vocabulary on the tensor units: fp32 out[row][v], bf16-rounded and capped as the glue's. +pub fn logitsUnits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, out: Ref, rows: u32, vocab: u32) !void { + const pipes = p.units orelse return error.NoTensorUnits; + for ([_]Ref{ h, unembed, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); + e.setPipeline(pipes[4]); + e.dispatchGroups(mtl.Size.of((vocab + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); +} diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index e1fd9c154ed..40c73ca9ebf 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -6,6 +6,7 @@ const layer_plan = @import("../plan.zig"); const ap = @import("attention_plan.zig"); const attention = @import("attention.zig"); const glue = @import("glue.zig"); +const experts = @import("experts.zig"); const metal_reset = @import("reset.zig"); const forward_experts = @import("forward_experts.zig"); const forward_attention = @import("forward_attention.zig"); @@ -403,7 +404,11 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, } if (options.taps) |to| captureTap(m, e, at(s.mlp_normed, 0), to, final.capture_rows, 3); const logits = if (options.all) at(s.logits_all, 0) else at(segments[0].cache.logits, 0); - glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + if (m.experts.units != null) { + try experts.logitsUnits(&m.experts, e, x(at(s.mlp_normed, final.logits_row * state.hidden * 2)), x(r(m.weights.unembed)), x(logits), @intCast(final.logits_rows), m.config.text.unpadded_vocab); + } else { + glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + } e.barrier(); sample.encodeForwardDraw(m, e, s, logits, options.draw, options.draws, m.config.text.unpadded_vocab); commitFullHistories(m, e, s, segments, seg_meta[0..segments.len]); @@ -428,3 +433,7 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, } const cuts = [_]usize{ 2, 12, 24, 36 }; + +fn x(ref: Ref) experts.Ref { + return .{ .buf = ref.buf, .off = ref.off }; +} diff --git a/zig/tests/contract/metal_inkling2_logits_units.zig b/zig/tests/contract/metal_inkling2_logits_units.zig new file mode 100644 index 00000000000..d88e13f7441 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_logits_units.zig @@ -0,0 +1,179 @@ +//! Inkling 2 Mini's logits on the tensor units: the glue entry's FP64 dot, BF16 round and cap of 30. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +const hidden = 2304; +pub const name = "metal inkling2 units tf_ink2_logits_units"; + +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.logits_cap.name() else name, + .accum = .f32, + .depth = depth, + .ops = 8, + .mids = 1, + .out = .f32, + // Rows go 16 a band and vocabulary rows 32 a tile; 90 vocabulary rows leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 64, .k = hidden }, .{ .rows = 8, .n = 90, .k = hidden }, .{ .rows = 20, .n = 32, .k = hidden } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms, an explicit BF16 node and a tanh" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .logits_cap else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) controls.Mutation.logits_cap.gate() else null }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 40 or shape.n == 0 or shape.n > 128 or shape.k != hidden) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * hidden); + p.w = try p.a.alloc(u16, shape.n * hidden); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + if (fill == .stress) { + // Whole numbers times a power of two: every product and partial sum is exact, and the cap stays live. + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + for (p.w, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(@as(i32, @intCast(i % 7)) - 3)) * 0x1p-20); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 4); + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + try host.logitsUnits(&p.pipes, pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.n)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const row = at / p.shape.n; + const v = at % p.shape.n; + var terms: [hidden]f64 = undefined; + var magnitude: f64 = 0; + for (&terms, 0..) |*term, d| { + term.* = @as(f64, c.fromBf16(p.w[v * hidden + d])) * @as(f64, c.fromBf16(p.x[row * hidden + d])); + magnitude += @abs(term.*); + } + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, &terms) else blk: { + var total: f64 = 0; + for (terms) |term| total += term; + break :blk total; + }; + return .{ .value = 30 * std.math.tanh(bf(sum) / 30), .magnitude = magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists only where the GPU has tensor units; elsewhere the glue's kernel serves every width. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + const label = spec(control).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; + +test "the logits entry resolves to its symbol in the units source" { + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, "tf_ink2_logits_units(")); +} diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index a9876018c72..95329067d49 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -14,6 +14,7 @@ pub const Suites = struct { dense_tiled: @import("metal_inkling2_dense_tiled.zig").Suite, gates_mma: @import("metal_inkling2_gates_mma.zig").Suite, units: @import("metal_inkling2_units.zig").Suite, + logits_units: @import("metal_inkling2_logits_units.zig").Suite, loop: @import("metal_inkling2_loop.zig").Suite, runtime: @import("metal_inkling2_runtime.zig").Suite, dspark: @import("metal_inkling2_dspark.zig").Suite, @@ -37,6 +38,7 @@ pub const Suites = struct { .dense_tiled = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .gates_mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .logits_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, @@ -58,6 +60,7 @@ pub const Suites = struct { try s.dense_tiled.collect(only); try s.gates_mma.collect(only); try s.units.collect(only); + try s.logits_units.collect(only); try s.loop.collect(only); try s.runtime.collect(only); try s.dspark.collect(only); @@ -80,6 +83,7 @@ pub const Suites = struct { s.dense_tiled.deinit(); s.gates_mma.deinit(); s.units.deinit(); + s.logits_units.deinit(); s.loop.deinit(); s.runtime.deinit(); s.dspark.deinit(); diff --git a/zig/tests/contract/metal_inkling2_units_controls.zig b/zig/tests/contract/metal_inkling2_units_controls.zig index ddf0d42aa9c..b9a86ca2b74 100644 --- a/zig/tests/contract/metal_inkling2_units_controls.zig +++ b/zig/tests/contract/metal_inkling2_units_controls.zig @@ -1,4 +1,4 @@ -//! Count-checked mutations of the tensor-unit expert kernels: every entry has a genuine arithmetic control. +//! Count-checked mutations of the tensor-unit kernels: every entry has a genuine arithmetic control. const std = @import("std"); const src = @import("inkling2_metal"); const g = @import("contract").gates; @@ -9,6 +9,7 @@ pub const Mutation = enum { nv_down_phi, mx_gu_scale, mx_down_scale, + logits_cap, pub fn name(m: Mutation) []const u8 { return switch (m) { @@ -17,6 +18,7 @@ pub const Mutation = enum { .nv_down_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units phi", .mx_gu_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units scale", .mx_down_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units scale", + .logits_cap => "control: metal inkling2 units tf_ink2_logits_units cap", }; } @@ -32,6 +34,7 @@ pub const Mutation = enum { .nv_down_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, // Both MXFP8 entries decode through one helper; a control compiles only its selected entry. .mx_gu_scale, .mx_down_scale => .{ .from = "const uint scale = uint(scales[b / 2u]);", .to = "const uint scale = uint(scales[b / 2u]) + 1u;" }, + .logits_cap => .{ .from = "precise::divide(float(bfloat(dot)), 30.0f)", .to = "precise::divide(float(bfloat(dot)), 15.0f)" }, }; } }; diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index 9948f9b8af8..90fe907107f 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -101,5 +101,5 @@ test "Metal launch map: every expert tensor-unit launch is M5-only and resolves" try std.testing.expect(launches.supported(.{ .units = true }, launch)); count += 1; } - try std.testing.expectEqual(@as(usize, 4), count); + try std.testing.expectEqual(@as(usize, 5), count); } From b84b64e8e719ae4872996c3cba4f981f4f1756e6 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:23:39 -0500 Subject: [PATCH 08/13] inkling2 metal: a prompt's rows take their projections on the tensor units --- zig/inkling2_source_owners_host.zig | 2 +- .../metal/inkling2/experts_units.metal | 51 +++++ .../contract/inkling2_units_metal_records.zig | 1 + zig/src/families/inkling2/metal/experts.zig | 13 +- zig/src/families/inkling2/metal/forward.zig | 25 ++- zig/src/families/inkling2/metal/prefill.zig | 2 +- .../contract/metal_inkling2_dense_units.zig | 181 ++++++++++++++++++ zig/tests/contract/metal_inkling2_main.zig | 4 + .../metal_inkling2_units_controls.zig | 3 + zig/tests/contract/metal_mapping_test.zig | 2 +- 10 files changed, 270 insertions(+), 14 deletions(-) create mode 100644 zig/tests/contract/metal_inkling2_dense_units.zig diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index 10784d001ba..9a0afe6fe4d 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -41,7 +41,7 @@ test "every current generated Inkling and LFM2 library matches its reviewed sour try equal(ink.prompt_attention_pre_m5, 36531, "28b71a25e1aab7174cf121f3ae05f84afb165970443a91f6978c06628630935b"); try equal(ink.glue, 42623, "0f4564349cd972c641812ab3d1fc71da085b88a045f28c794ecd35ff9718def7"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); - try equal(ink.experts_units, 66778, "31f7f43d6d8662465ddfedbbb0678a0b6260a277d92208ed6a16f5d26148ae6d"); + try equal(ink.experts_units, 69553, "f60a6ef8610b08a30e878eb735105558034833550fc82115bf7e4460c7f073be"); try equal(ink.experts_mma, 54957, "dd04bd9b6cd695404966f9b182831a35a987fb7db81aaf44ee6c440d231bca86"); try equal(ink.dense_mma, 5389, "6d0b015dd66035efbd110ae4d8dd690ca677ed9c500a83837aee7269161b334a"); try equal(ink.dense_tiled, 4324, "cdddebd86d265d9a79fd93b80894266750ca267e7ffeb76c481e6e73ab03c3ee"); diff --git a/zig/kernels/metal/inkling2/experts_units.metal b/zig/kernels/metal/inkling2/experts_units.metal index f2c3e384448..851a9e05e37 100644 --- a/zig/kernels/metal/inkling2/experts_units.metal +++ b/zig/kernels/metal/inkling2/experts_units.metal @@ -179,3 +179,54 @@ struct Ink2LogitArgs { uint rows, vocab; }; } } } + +struct Ink2DenseArgs { uint rows, n, k; }; + +// Threadgroup (x, y): outputs 32x .. 32x + 31 of rows 16y .. 16y + 15, summed as the expert products are; KC is k. +template +inline void ink2_dense(device const bfloat* X, device const bfloat* W, device bfloat* Y, constant Ink2DenseArgs& a, + uint2 tg, uint sg, uint lane, threadgroup float* part) { + const uint n0 = 32u * tg.x, r0 = 16u * tg.y, K = KC; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + const bool live0 = r0 + hy < a.rows, live1 = r0 + hy + 8u < a.rows; + device const bfloat* x0 = X + ulong(r0 + hy) * K + hx; + // An output past the end reads the last one's weights: its sums are not stored. + const uint last = a.n - 1u; + device const bfloat* w0 = W + ulong(min(n0 + hy, last)) * K + hx; + device const bfloat* w1 = W + ulong(min(n0 + hy + 8u, last)) * K + hx; + device const bfloat* w2 = W + ulong(min(n0 + hy + 16u, last)) * K + hx; + device const bfloat* w3 = W + ulong(min(n0 + hy + 24u, last)) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * (K / 128u); b < (sg + 1u) * (K / 128u); ++b) { + const tfp::frag fa = ink2_units_x(x0, x0 + 8u * K, live0, live1, 16u * b); + const tfp::frag b0 = tfp::frag(*(device const bfloat4*)(w0 + 16u * b), *(device const bfloat4*)(w1 + 16u * b)); + const tfp::frag b1 = tfp::frag(*(device const bfloat4*)(w2 + 16u * b), *(device const bfloat4*)(w3 + 16u * b)); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is row r0 + hy + 8 (e >> 2), output n0 + hx + (e & 3); hi is 16 outputs on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong row = r0 + hy + 8u * q; + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint v = n0 + 16u * side + hx + j; + const float dot = side == 0u ? lo[4u * q + j] : hi[4u * q + j]; + if (v < a.n) Y[row * a.n + v] = bfloat(dot); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_dense_units( + device const bfloat* X [[buffer(0)]], device const bfloat* W [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DenseArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + if (a.k == 2304u) ink2_dense<2304u>(X, W, Y, a, tg, sg, lane, part); + else ink2_dense<3072u>(X, W, Y, a, tg, sg, lane, part); +} diff --git a/zig/src/core/contract/inkling2_units_metal_records.zig b/zig/src/core/contract/inkling2_units_metal_records.zig index 2b4d85f8dea..938c9bffdbf 100644 --- a/zig/src/core/contract/inkling2_units_metal_records.zig +++ b/zig/src/core/contract/inkling2_units_metal_records.zig @@ -8,6 +8,7 @@ pub const records = [_]M{ .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_logits_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_dense_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, }; test "Inkling2 units launches reserve their threads and carry no M1/M2 compile receipts" { diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 281b682fb15..2a57e4913de 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -54,7 +54,7 @@ pub const Globals = struct { amax: Ref, denominator: Ref }; /// The columns the units kernels read a row: experts_units.metal's INK2_GU_K and INK2_DOWN_K. const units_gu_k = 2304; const units_down_k = 1152; -const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units" }; +const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units", "tf_ink2_dense_units" }; pub const Pipelines = struct { units: ?[units_names.len]mtl.Pipeline = null, @@ -383,3 +383,14 @@ pub fn logitsUnits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: e.setPipeline(pipes[4]); e.dispatchGroups(mtl.Size.of((vocab + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); } + +const DenseArgs = extern struct { rows: u32, n: u32, k: u32 }; +/// A prompt's rows of x [rows][k] against a bf16 weight [n][k] on the tensor units; k is 2,304 or 3,072. +pub fn denseUnits(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, out: Ref, rows: u32, n: u32, k: u32) !void { + const pipes = p.units orelse return error.NoTensorUnits; + if ((k != 2304 and k != 3072) or rows == 0 or n == 0) return error.BadExpertShape; + for ([_]Ref{ x, w, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(DenseArgs{ .rows = rows, .n = n, .k = k }, 3); + e.setPipeline(pipes[5]); + e.dispatchGroups(mtl.Size.of((n + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); +} diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index 40c73ca9ebf..a2de26e9502 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -34,6 +34,7 @@ const SegMeta = struct { is_tree: bool = false, max_depth: u32 = 0 }; pub const ImageRows = struct { row: u32, rows: u32, buf: mtl.Buffer, off: usize = 0 }; pub const Options = struct { all: bool = false, + prompt: bool = false, decode: bool = false, ids: ?Ref = null, meta: ?attention.RowMeta = null, @@ -143,7 +144,11 @@ pub fn encodeDense(comptime Encoder: type, m: anytype, e: Encoder, weight: ck.Te } /// A visit's projection: `dense`, simdgroup matrices without tensor units, or register-tiled bf16 on tensor-unit GPUs. -fn project(m: *const Model, e: mtl.ComputeEncoder, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) void { +fn project(m: *const Model, e: mtl.ComputeEncoder, prompt: bool, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) !void { + const k = weight.shape[weight.rank - 1]; + if (prompt and m.experts.units != null and weight.dtype == .bf16 and (k == 2304 or k == 3072)) { + return experts.denseUnits(&m.experts, e, x(input), x(r(weight)), x(out), @intCast(rows), @intCast(weight.shape[weight.rank - 2]), @intCast(k)); + } const n: u32 = @intCast(weight.shape[weight.rank - 2]); const call = dense_mma.Call{ .rows = @intCast(rows), .n = n, .k = @intCast(weight.shape[weight.rank - 1]), .ldy = n }; if (m.dense_mma) |mma| { @@ -217,7 +222,7 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra } } -fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, prev_fused: bool, prev_fused_norm: bool, next_v: ?*const layer_plan.Visit, final_rows: usize, segments: []const Segment, seg_meta: []const SegMeta, rows: usize, taps: ?state.Ref, meta_override: ?attention.RowMeta, decode: bool) !void { +fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, prev_fused: bool, prev_fused_norm: bool, next_v: ?*const layer_plan.Visit, final_rows: usize, segments: []const Segment, seg_meta: []const SegMeta, rows: usize, taps: ?state.Ref, meta_override: ?attention.RowMeta, decode: bool, prompt: bool) !void { const lp = m.weight_plan.at(v.layer); const gated = v.hasMessages(); if (taps) |to| { @@ -237,16 +242,16 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la e.barrier(); const knorm = if (gated or lp.kind == .global) at(s.k_norm, 0) else at(s.q_norm, 0); const vnorm = if (gated or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); - project(m, e, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); - project(m, e, w.attn.wk, knorm, at(s.k_raw, 0), rows); - project(m, e, w.attn.wv, vnorm, at(s.v_raw, 0), rows); - project(m, e, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); - project(m, e, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); - project(m, e, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); + try project(m, e, prompt, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); + try project(m, e, prompt, w.attn.wk, knorm, at(s.k_raw, 0), rows); + try project(m, e, prompt, w.attn.wv, vnorm, at(s.v_raw, 0), rows); + try project(m, e, prompt, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); + try project(m, e, prompt, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); + try project(m, e, prompt, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); e.barrier(); try attendSegments(m, e, s, v, segments, seg_meta, meta_override, decode); e.barrier(); - project(m, e, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + try project(m, e, prompt, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); e.barrier(); postConv(m, e, s, segments, seg_meta, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0)); const boundary: u32 = if (lp.boundary) lp.blocks_in + 1 else 0; @@ -391,7 +396,7 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, const prev_fused = vi > 0 and canPreFuse(v); const prev_fused_norm = vi > 0 and canPreFuseNorm(&m.weight_plan, v); const next_v: ?*const layer_plan.Visit = if (vi + 1 < visits.len) &visits[vi + 1] else null; - try visit(m, e, s, v, prev_fused, prev_fused_norm, next_v, final.work_rows, segments, seg_meta[0..segments.len], rows, options.taps, options.meta, options.decode); + try visit(m, e, s, v, prev_fused, prev_fused_norm, next_v, final.work_rows, segments, seg_meta[0..segments.len], rows, options.taps, options.meta, options.decode, options.prompt); if (parallel and options.flight == null and n_parts < cuts.len and vi + 1 == cuts[n_parts]) { e.end(); cb.commit(); diff --git a/zig/src/families/inkling2/metal/prefill.zig b/zig/src/families/inkling2/metal/prefill.zig index 371965567bc..4bf91fc4bfe 100644 --- a/zig/src/families/inkling2/metal/prefill.zig +++ b/zig/src/families/inkling2/metal/prefill.zig @@ -30,7 +30,7 @@ pub fn feedChunk(self: anytype, cache: *st.Cache, ids: []const u32, stream: ?*la if (capture) _ = self.nextTapGeneration(); const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; const rows_of: []const fwd.ImageRows = if (pictures) |p| p.chunk(base, base + end) else &.{}; - try fwd.run(self.model, s, cache, ids[0..end], .{ .taps = taps, .images = rows_of }); + try fwd.run(self.model, s, cache, ids[0..end], .{ .taps = taps, .images = rows_of, .prompt = true }); if (capture) { const rows = end; if (self.sink) |k| try k.take(k.ptr, stream.?, .{ diff --git a/zig/tests/contract/metal_inkling2_dense_units.zig b/zig/tests/contract/metal_inkling2_dense_units.zig new file mode 100644 index 00000000000..2ebf6bc0ba3 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dense_units.zig @@ -0,0 +1,181 @@ +//! Inkling 2 Mini's prompt projections on the tensor units: an FP64 dot of BF16 values, stored as BF16. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +/// The columns the kernel takes: the hidden width, and the query width `wo` reads. +const widths = [_]usize{ 2304, 3072 }; +pub const name = "metal inkling2 units tf_ink2_dense_units"; + +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.dense_store.name() else name, + .accum = .f32, + .depth = depth, + .ops = 3, + .out = .bf16, + // Rows go 16 a band and outputs 32 a tile; 24 and 90 outputs leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 64, .k = 2304 }, .{ .rows = 8, .n = 24, .k = 2304 }, .{ .rows = 20, .n = 90, .k = 3072 } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and one BF16 store" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .dense_store else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) controls.Mutation.dense_store.gate() else null }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 40 or shape.n == 0 or shape.n > 128 or std.mem.indexOfScalar(usize, &widths, shape.k) == null) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * shape.k); + p.w = try p.a.alloc(u16, shape.n * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + if (fill == .stress) { + // Whole numbers times a power of two: every product and partial sum is exact. + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + for (p.w, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(@as(i32, @intCast(i % 7)) - 3)) * 0x1p-20); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 2); + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + try host.denseUnits(&p.pipes, pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.n), @intCast(p.shape.k)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const row = at / p.shape.n; + const v = at % p.shape.n; + const k = p.shape.k; + var store: [3072]f64 = undefined; + const terms = store[0..k]; + var magnitude: f64 = 0; + for (terms, 0..) |*term, d| { + term.* = @as(f64, c.fromBf16(p.w[v * k + d])) * @as(f64, c.fromBf16(p.x[row * k + d])); + magnitude += @abs(term.*); + } + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, terms) else blk: { + var total: f64 = 0; + for (terms) |term| total += term; + break :blk total; + }; + return .{ .value = bf(sum), .magnitude = magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists only where the GPU has tensor units; elsewhere a prompt's rows take the shared matvec. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + const label = spec(control).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; + +test "the dense entry resolves to its symbol in the units source" { + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, "tf_ink2_dense_units(")); +} diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index 95329067d49..332455c19e3 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -15,6 +15,7 @@ pub const Suites = struct { gates_mma: @import("metal_inkling2_gates_mma.zig").Suite, units: @import("metal_inkling2_units.zig").Suite, logits_units: @import("metal_inkling2_logits_units.zig").Suite, + dense_units: @import("metal_inkling2_dense_units.zig").Suite, loop: @import("metal_inkling2_loop.zig").Suite, runtime: @import("metal_inkling2_runtime.zig").Suite, dspark: @import("metal_inkling2_dspark.zig").Suite, @@ -39,6 +40,7 @@ pub const Suites = struct { .gates_mma = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .logits_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dense_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, @@ -61,6 +63,7 @@ pub const Suites = struct { try s.gates_mma.collect(only); try s.units.collect(only); try s.logits_units.collect(only); + try s.dense_units.collect(only); try s.loop.collect(only); try s.runtime.collect(only); try s.dspark.collect(only); @@ -84,6 +87,7 @@ pub const Suites = struct { s.gates_mma.deinit(); s.units.deinit(); s.logits_units.deinit(); + s.dense_units.deinit(); s.loop.deinit(); s.runtime.deinit(); s.dspark.deinit(); diff --git a/zig/tests/contract/metal_inkling2_units_controls.zig b/zig/tests/contract/metal_inkling2_units_controls.zig index b9a86ca2b74..abe7446f8f8 100644 --- a/zig/tests/contract/metal_inkling2_units_controls.zig +++ b/zig/tests/contract/metal_inkling2_units_controls.zig @@ -10,6 +10,7 @@ pub const Mutation = enum { mx_gu_scale, mx_down_scale, logits_cap, + dense_store, pub fn name(m: Mutation) []const u8 { return switch (m) { @@ -19,6 +20,7 @@ pub const Mutation = enum { .mx_gu_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units scale", .mx_down_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units scale", .logits_cap => "control: metal inkling2 units tf_ink2_logits_units cap", + .dense_store => "control: metal inkling2 units tf_ink2_dense_units store", }; } @@ -35,6 +37,7 @@ pub const Mutation = enum { // Both MXFP8 entries decode through one helper; a control compiles only its selected entry. .mx_gu_scale, .mx_down_scale => .{ .from = "const uint scale = uint(scales[b / 2u]);", .to = "const uint scale = uint(scales[b / 2u]) + 1u;" }, .logits_cap => .{ .from = "precise::divide(float(bfloat(dot)), 30.0f)", .to = "precise::divide(float(bfloat(dot)), 15.0f)" }, + .dense_store => .{ .from = "Y[row * a.n + v] = bfloat(dot);", .to = "Y[row * a.n + v] = bfloat(2.0f * dot);" }, }; } }; diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index 90fe907107f..3969c4930df 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -101,5 +101,5 @@ test "Metal launch map: every expert tensor-unit launch is M5-only and resolves" try std.testing.expect(launches.supported(.{ .units = true }, launch)); count += 1; } - try std.testing.expectEqual(@as(usize, 5), count); + try std.testing.expectEqual(@as(usize, 6), count); } From c375a6624afc1ad80d02733ff9250c9a34ceae59 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:35:43 -0500 Subject: [PATCH 09/13] inkling2 metal: a prompt's rows take the sliding layers' attention on the prompt kernel, a tile of keys a chunk --- zig/inkling2_source_owners_host.zig | 4 ++-- .../metal/inkling2/prompt_attention.metal | 20 ++++++++++++----- zig/src/families/inkling2/metal/attention.zig | 2 +- .../inkling2/metal/attention_plan.zig | 14 ++++++++---- .../inkling2/metal/attention_test.zig | 2 +- zig/src/families/inkling2/metal/forward.zig | 2 +- .../inkling2/metal/forward_attention.zig | 11 +++++----- .../contract/metal_inkling2_attention.zig | 22 ++++++++++++------- .../metal_inkling2_attention_controls.zig | 21 +++++++++++++++--- 9 files changed, 67 insertions(+), 31 deletions(-) diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index 9a0afe6fe4d..12ed28bbf1b 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -37,8 +37,8 @@ test "every assembled glue kernel uses one scalar or vector width for positional } test "every current generated Inkling and LFM2 library matches its reviewed source pins" { try equal(ink.attention, 28563, "0969f2367a5955f0215ee82017fe536b85d5b9a5f763942383a4f90d1cda6f60"); - try equal(ink.prompt_attention, 36507, "2e690463846a822b5c087139eaa3dfbc9a980caa7753e36cb3562afc88a17abd"); - try equal(ink.prompt_attention_pre_m5, 36531, "28b71a25e1aab7174cf121f3ae05f84afb165970443a91f6978c06628630935b"); + try equal(ink.prompt_attention, 37015, "41126214b24221c99eb3e12a4cae8f67647eb6ca7d56f6836375bb4089a2b997"); + try equal(ink.prompt_attention_pre_m5, 37039, "965ee2473d73b71fbcd51f0f514c657fd21df1e0e53a763c39c89c00642d1b47"); try equal(ink.glue, 42623, "0f4564349cd972c641812ab3d1fc71da085b88a045f28c794ecd35ff9718def7"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); try equal(ink.experts_units, 69553, "f60a6ef8610b08a30e878eb735105558034833550fc82115bf7e4460c7f073be"); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal index fad98b2ed32..8504edca39d 100644 --- a/zig/kernels/metal/inkling2/prompt_attention.metal +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -6,12 +6,16 @@ using namespace metal; constant constexpr uint D = 128, REL = 16, EXTENT = 1024, KEYS = 64, PAIRS = 128; constant constexpr float LOG2E = 1.4426950408889634f; struct InkPromptSeg { int row0, n, p0, pad; long off; }; -struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; }; +struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; uint window; }; inline size_t ink_prompt_rh(const thread InkPromptSeg& s, uint heads, uint group, uint kvh, uint pair) { return (size_t(s.row0) + pair / group) * heads + kvh * group + pair % group; } +inline uint ink_prompt_first(constant InkPromptArgs& a, uint pos) { + return a.window ? (pos + 1 > a.window ? pos + 1 - a.window : 0u) / a.chunk : a.c0; +} + inline void ink_fold(thread float& mm, thread float& ll, float m, float l, thread float& a, thread float& b) { const float mn = max(mm, m); a = precise::exp2(mm - mn); @@ -47,6 +51,8 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi const uint kvh = tg.y, c = a.c0 + tg.z, b_lo = c * a.chunk; const uint tile_hi = uint(s.p0) + min(m0 + PAIRS - 1, total - 1) / group; if (b_lo > tile_hi) return; + const uint first_pos = uint(s.p0) + m0 / group; + if (a.window && first_pos + 1 > a.window && b_lo + a.chunk <= first_pos + 1 - a.window) return; const uint k_hi = min(b_lo + a.chunk - 1, tile_hi), m = m0 + 16 * sg; const short2 home = tfp::frag_home(ushort(lane)); const uint row_a = m + uint(home.y), row_b = row_a + 8; @@ -100,7 +106,7 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi } for (uint f = 0; f < 4; ++f) for (uint ce = 0; ce < 4; ++ce) { const uint e = 4 * h + ce, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col; - const bool live = row_live && kp <= pos && kp >= sub_lo && kp <= sub_hi; + const bool live = row_live && kp <= pos && kp >= sub_lo && kp <= sub_hi && (a.window == 0u || kp + a.window > pos); const uint distance = live ? pos - kp : 0; float bias = 0.0f; if (live && distance < EXTENT) { @@ -149,16 +155,18 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) { const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e); if (row >= total) continue; - const uint pos = uint(s.p0) + row / group; - if (b_lo > pos) continue; + const uint pos = uint(s.p0) + row / group, first = ink_prompt_first(a, pos); + if (b_lo > pos || c < first) continue; const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); - part_o[(prow * a.chunks + c - a.c0) * D + 16 * d + col] = out[d][e]; + part_o[(prow * a.chunks + c - first) * D + 16 * d + col] = out[d][e]; } if (home.x == 0) for (uint h = 0; h < 2; ++h) { const uint row = m + uint(home.y) + 8 * h; if (row >= total || b_lo > uint(s.p0) + row / group) continue; const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); - part_ml[prow * a.chunks + c - a.c0] = float2(upper[h], whole[h]); + const uint first = ink_prompt_first(a, uint(s.p0) + row / group); + if (c < first) continue; + part_ml[prow * a.chunks + c - first] = float2(upper[h], whole[h]); } } diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig index cdfc90d01a0..902e469fc40 100644 --- a/zig/src/families/inkling2/metal/attention.zig +++ b/zig/src/families/inkling2/metal/attention.zig @@ -159,7 +159,7 @@ fn partialsImpl(k: *const Kernels, e: anytype, r: planning.Rows, l: planning.Lay const prompt_segs = meta.prompt_segs orelse meta.segs; e.setPipeline(k.prompt); bind(e, &.{ q, kv.k, kv.v, rel, proj, prompt_segs, part_o, part_ml }, 0); - e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 8); + e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = launch.c0, .chunks = launch.partials_rh, .scale = scale, .window = l.window }, 8); }, } e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index 9d0c611fad3..17dfc41e2b4 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -35,11 +35,11 @@ pub const PrepArgs = extern struct { }; pub const AttnArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, window: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; pub const MergeArgs = extern struct { heads: u32, window: u32, chunk: u32, c0: u32, chunks: u32, subs: u32 = 1 }; -pub const PromptArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; +pub const PromptArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32, window: u32 = 0 }; pub const PromptTreeArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32, p_tile: u32, c_off: u32, max_pos: u32 }; comptime { if (@sizeOf(Seg) != 24 or @sizeOf(BatchedSeg) != 32 or @sizeOf(PrepArgs) != 36 or @sizeOf(AttnArgs) != 32) @compileError("Inkling attention ABI drift"); - if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 28 or @sizeOf(PromptTreeArgs) != 40) @compileError("Inkling prompt ABI drift"); + if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 32 or @sizeOf(PromptTreeArgs) != 40) @compileError("Inkling prompt ABI drift"); } pub const Layer = struct { @@ -58,7 +58,7 @@ pub const Layer = struct { } }; pub const Prep = struct { qk_clip: f32 = 22.627416997969522, rel_clip: f32 = 8, floor: f32 = 8192, alpha: f32 = 0.1, eps: f32 = 1e-6 }; -pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1 }; +pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1, prompt: bool = false }; /// The fewest keys a slot that fit `capacity` in 64 slots; any whole number of 1,024-key folds gives the same bits. pub fn globalChunk(capacity: u32) u32 { @@ -81,7 +81,8 @@ pub fn split(r: Rows, stride: u32, slots: usize) bool { return r.rows <= split_rows and @as(usize, r.rows) * r.heads * stride * subs <= slots; } pub fn usePrompt(r: Rows, l: Layer, stride: u32, slots: usize) bool { - return l.window == 0 and r.streams == 1 and !split(r, stride, slots); + if (l.window > 0) return r.prompt and r.streams == 1; + return r.streams == 1 and !split(r, stride, slots); } pub fn useSlidingPrompt(r: Rows, l: Layer) bool { return l.window > 0 and r.streams == 1 and r.rows >= sliding_prompt_min_rows and r.kv_heads > 0 and r.heads == r.kv_heads * 3; @@ -126,6 +127,11 @@ pub fn attend(r: Rows, l: Layer, stride: u32, slots: usize) error{Inkling2Partia const merge_grid = [3]u32{ r.rows * r.heads, 1, 1 }; if (usePrompt(r, l, stride, slots)) { const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + if (l.window > 0) { + const first_pos = r.last_pos + 1 - r.rows; + const c0 = ((first_pos + 1) -| l.window) / l.chunk; + return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, r.last_pos / l.chunk - c0 + 1 }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride, .c0 = c0 }; + } return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, stride }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride }; } if (useSlidingPrompt(r, l)) return attendSlidingPrompt(r, l, stride); diff --git a/zig/src/families/inkling2/metal/attention_test.zig b/zig/src/families/inkling2/metal/attention_test.zig index 86d78760586..0af2557930a 100644 --- a/zig/src/families/inkling2/metal/attention_test.zig +++ b/zig/src/families/inkling2/metal/attention_test.zig @@ -21,7 +21,7 @@ test "inkling2 metal ABI matches the shaders" { try t.expectEqual(@as(usize, 8), @sizeOf(rb.Args)); try t.expectEqual(@as(u32, 245761), rb.default_min_context); try t.expectEqual(@as(usize, 24), @sizeOf(p.MergeArgs)); - try t.expectEqual(@as(usize, 28), @sizeOf(p.PromptArgs)); + try t.expectEqual(@as(usize, 32), @sizeOf(p.PromptArgs)); try t.expectEqual(@as(u32, 24), (p.Rows{ .rows = 1, .last_pos = 0 }).heads); try t.expectEqual(@as(u32, 8), (p.Rows{ .rows = 1, .last_pos = 0 }).kv_heads); try t.expectEqual(@as(f32, 8192), (p.Prep{}).floor); diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index a2de26e9502..badbb71f189 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -249,7 +249,7 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la try project(m, e, prompt, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); try project(m, e, prompt, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); e.barrier(); - try attendSegments(m, e, s, v, segments, seg_meta, meta_override, decode); + try attendSegments(m, e, s, v, segments, seg_meta, meta_override, decode, prompt); e.barrier(); try project(m, e, prompt, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); e.barrier(); diff --git a/zig/src/families/inkling2/metal/forward_attention.zig b/zig/src/families/inkling2/metal/forward_attention.zig index 698348b0442..c0afacd1fae 100644 --- a/zig/src/families/inkling2/metal/forward_attention.zig +++ b/zig/src/families/inkling2/metal/forward_attention.zig @@ -55,7 +55,7 @@ fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cac } } -pub fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, meta_override: ?attention.RowMeta, decode: bool) !void { +pub fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, meta_override: ?attention.RowMeta, decode: bool, prompt: bool) !void { const fused = fusedConv(segments, seg_meta); if (fused) { conv.fusedAttention(m, e, s, v, segments); @@ -102,7 +102,7 @@ pub fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, } e.barrier(); } - try attendEach(m, e, s, v, segments, seg_meta, specs[0..segments.len], prep, proj_ref, scale_refs, meta_override, decode); + try attendEach(m, e, s, v, segments, seg_meta, specs[0..segments.len], prep, proj_ref, scale_refs, meta_override, decode, prompt); } fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void { @@ -146,7 +146,7 @@ fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra } } -fn attendEach(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, specs: []const ap.BatchedSegSpec, prep_cfg: ap.Prep, proj_ref: attention.Ref, scale_refs: [2]attention.Ref, meta_override: ?attention.RowMeta, decode: bool) !void { +fn attendEach(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: anytype, seg_meta: anytype, specs: []const ap.BatchedSegSpec, prep_cfg: ap.Prep, proj_ref: attention.Ref, scale_refs: [2]attention.Ref, meta_override: ?attention.RowMeta, decode: bool, prompt: bool) !void { var launches: [state.max_segments]ap.Launch = undefined; var tree_launches: [state.max_segments]ap.TreeLaunch = undefined; var layers: [state.max_segments]ap.Layer = undefined; @@ -163,8 +163,9 @@ fn attendEach(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *con const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, rows); bases[si] = base; starts[si] = @intCast(cache.len); - layers[si] = .{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; - rrs[si] = .{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = specs[si].last_pos, .streams = 1 }; + const tiled = prompt and m.attention.units and layer0.window > 0 and !seg_meta[si].is_tree; + layers[si] = .{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = if (tiled) ap.tile_keys else layer0.chunk, .tau = layer0.tau }; + rrs[si] = .{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = specs[si].last_pos, .streams = 1, .prompt = tiled }; metas[si] = meta_override orelse attention.RowMeta{ .pos = a(at(s.pos, base * 4)), .seg_of = a(at(s.seg_of, base * 4)), diff --git a/zig/tests/contract/metal_inkling2_attention.zig b/zig/tests/contract/metal_inkling2_attention.zig index 2b9d8e4fa02..0ae6f545297 100644 --- a/zig/tests/contract/metal_inkling2_attention.zig +++ b/zig/tests/contract/metal_inkling2_attention.zig @@ -24,6 +24,7 @@ const sliding_prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1030 }, const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 17 }, .{ .rows = 1, .n = H * D, .k = 1025 } }; const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 }, .{ .rows = 3, .n = H * D, .k = 17 }, .{ .rows = 1, .n = H * D, .k = 1025 } }; const long_shapes = [_]c.Shape{.{ .rows = 5, .n = H * D, .k = 17450 }}; +const prompt_sliding_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 2049 }, .{ .rows = 64, .n = H * D, .k = 80 } }; fn depth(s: c.Shape) usize { return D + 4 * s.k + 64; } @@ -31,6 +32,10 @@ fn spec(w: Which) c.Spec { const x: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 64, .mids = 8, .out = .bf16, .served = &global_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .exact = true, .why = "P and outputs have required bf16 roundings" } }; var s = x; switch (w) { + .prompt_sliding_m5, .prompt_sliding_pre_m5 => { + s.name = if (w == .prompt_sliding_m5) "metal inkling2 prompt m5 sliding tf_ink2_attn_prompt" else "metal inkling2 prompt pre-m5 sliding tf_ink2_attn_prompt"; + s.served = &prompt_sliding_shapes; + }, .prep_sliding, .prep_global => { s.name = if (w == .prep_global) "metal inkling2 attention prep global tf_ink2_prep" else "metal inkling2 attention prep sliding tf_ink2_prep"; s.served = if (w == .prep_global) &prep_global_shapes else &prep_shapes; @@ -184,15 +189,16 @@ pub const Probe = struct { p.rig.reset(); p.shape = s; p.fill = fill; - const global = p.which == .prep_global or p.which == .decode_global or p.which == .decode_global_long or controls.isPrompt(p.which); - const sliding = p.which == .prep_sliding or p.which == .decode_sliding or p.which == .sliding_prompt; + const tiled = controls.isPromptSliding(p.which); + const global = p.which == .prep_global or p.which == .decode_global or p.which == .decode_global_long or (controls.isPrompt(p.which) and !tiled); + const sliding = p.which == .prep_sliding or p.which == .decode_sliding or p.which == .sliding_prompt or tiled; const ring: u32 = if (p.which == .sliding_prompt) plan.ringFor(1024, @intCast(s.rows)) else if (controls.isAttention(p.which)) @intCast(std.mem.alignForward(usize, @max(2048, s.k), 64)) else 2048; - p.layer = .{ .window = if (sliding) 1024 else 0, .ring = ring, .chunk = if (sliding) 256 else plan.global_chunk, .tau = global }; + p.layer = .{ .window = if (sliding) 1024 else 0, .ring = ring, .chunk = if (tiled) plan.tile_keys else if (sliding) 256 else plan.global_chunk, .tau = global }; const rows = s.rows; const rh = rows * H; const cache = KV * p.layer.ring * D; @@ -325,9 +331,9 @@ pub const Probe = struct { e.setBuffer(p.pml.buf, p.pml.off, 7); const sc: f32 = 1.0 / @sqrt(@as(f32, D)); if (controls.isPrompt(p.which)) { - e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 8); - const blocks = (rows * (H / KV) + plan.prompt_pairs - 1) / plan.prompt_pairs; - e.dispatchGroups(mtl.Size.of(blocks, KV, stride), mtl.Size.of(256, 1, 1)); + const launch = try plan.attend(.{ .rows = @intCast(rows), .last_pos = @intCast(p.shape.k - 1), .prompt = p.layer.window > 0 }, p.layer, stride, 0); + e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = launch.c0, .chunks = stride, .scale = sc, .window = p.layer.window }, 8); + e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(256, 1, 1)); } else if (p.which == .sliding_prompt) { const rr = plan.Rows{ .rows = rows, .heads = H, .kv_heads = KV, .last_pos = @intCast(p.shape.k - 1), .streams = 1 }; const launch = try plan.attendSlidingPrompt(rr, p.layer, stride); @@ -368,8 +374,8 @@ pub const Probe = struct { fn supported(device: mtl.Device, w: Which) bool { return switch (w) { - .prompt_m5, .prompt_m5_long => device.tensorUnits(), - .prompt_pre_m5, .prompt_pre_m5_long => !device.tensorUnits(), + .prompt_m5, .prompt_m5_long, .prompt_sliding_m5 => device.tensorUnits(), + .prompt_pre_m5, .prompt_pre_m5_long, .prompt_sliding_pre_m5 => !device.tensorUnits(), else => true, }; } diff --git a/zig/tests/contract/metal_inkling2_attention_controls.zig b/zig/tests/contract/metal_inkling2_attention_controls.zig index be744080417..cbaf20607cd 100644 --- a/zig/tests/contract/metal_inkling2_attention_controls.zig +++ b/zig/tests/contract/metal_inkling2_attention_controls.zig @@ -13,20 +13,25 @@ pub const Which = enum { prompt_m5_long, prompt_pre_m5, prompt_pre_m5_long, + prompt_sliding_m5, + prompt_sliding_pre_m5, }; pub fn function(w: Which) []const u8 { return switch (w) { .prep_sliding, .prep_global => "tf_ink2_prep", .decode_sliding, .decode_global, .decode_global_long => "tf_ink2_attn_scalar", .sliding_prompt => "tf_ink2_attn_sliding_prompt", - .prompt_m5, .prompt_m5_long, .prompt_pre_m5, .prompt_pre_m5_long => "tf_ink2_attn_prompt", + .prompt_m5, .prompt_m5_long, .prompt_pre_m5, .prompt_pre_m5_long, .prompt_sliding_m5, .prompt_sliding_pre_m5 => "tf_ink2_attn_prompt", }; } pub fn isPrompt(w: Which) bool { - return w == .prompt_m5 or w == .prompt_m5_long or w == .prompt_pre_m5 or w == .prompt_pre_m5_long; + return w == .prompt_m5 or w == .prompt_m5_long or w == .prompt_pre_m5 or w == .prompt_pre_m5_long or isPromptSliding(w); } pub fn isPreM5(w: Which) bool { - return w == .prompt_pre_m5 or w == .prompt_pre_m5_long; + return w == .prompt_pre_m5 or w == .prompt_pre_m5_long or w == .prompt_sliding_pre_m5; +} +pub fn isPromptSliding(w: Which) bool { + return w == .prompt_sliding_m5 or w == .prompt_sliding_pre_m5; } pub fn isSliding(w: Which) bool { return w == .prep_sliding or w == .decode_sliding or w == .sliding_prompt; @@ -54,9 +59,13 @@ pub const Mutation = enum { prompt_late_bias, prompt_pre_rel_late, prompt_pre_late_bias, + prompt_wide_window, + prompt_pre_wide_window, pub fn name(m: Mutation) []const u8 { return switch (m) { .none => "", + .prompt_wide_window => "control: metal inkling2 prompt m5 sliding window half as long tf_ink2_attn_prompt", + .prompt_pre_wide_window => "control: metal inkling2 prompt pre-m5 sliding window half as long tf_ink2_attn_prompt", .prep_swap_kv => "control: metal inkling2 attention prep sliding with gated K/V inputs exchanged tf_ink2_prep", .prep_tau_off => "control: metal inkling2 attention global prep without tau tf_ink2_prep", .decode_rel_late => "control: metal inkling2 attention sliding relative projection one column late tf_ink2_attn_scalar", @@ -78,6 +87,8 @@ pub const Mutation = enum { } pub fn which(m: Mutation) Which { return switch (m) { + .prompt_wide_window => .prompt_sliding_m5, + .prompt_pre_wide_window => .prompt_sliding_pre_m5, .none => unreachable, .prep_swap_kv => .prep_sliding, .prep_tau_off => .prep_global, @@ -91,6 +102,10 @@ pub const Mutation = enum { const Edit = struct { from: []const u8, to: []const u8 }; fn edit(m: Mutation) Edit { return switch (m) { + .prompt_wide_window, .prompt_pre_wide_window => .{ + .from = "(a.window == 0u || kp + a.window > pos);", + .to = "(a.window == 0u || kp + a.window / 2u > pos);", + }, .none => unreachable, .prep_swap_kv => .{ .from = "const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D;", From 993a69136529e9814faa12cc37797b09f08d43c1 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:26:18 -0500 Subject: [PATCH 10/13] inkling2 metal: a chunk wider than a window stages its convolution taps in the scratch, so a stream's cache stages a window only --- zig/src/families/inkling2/metal/forward.zig | 3 +-- .../inkling2/metal/forward_attention.zig | 16 ++++++++----- .../families/inkling2/metal/forward_conv.zig | 2 +- .../families/inkling2/metal/runtime_test.zig | 8 +++---- zig/src/families/inkling2/metal/state.zig | 24 +++++++++++++++---- .../families/inkling2/metal/tree_gpu_test.zig | 6 ++--- 6 files changed, 38 insertions(+), 21 deletions(-) diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index badbb71f189..a274b8902b8 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -297,10 +297,9 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la } fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment, meta: []const SegMeta) void { - _ = s; if (fusedConv(segments, meta)) { for (segments) |seg| if (seg.cache.pending != null) conv.commitHistories(m, e, seg.cache, seg.rows); - } else for (segments) |seg| for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| copyBf16(m, e, seg.cache.staged(slot, cs, seg.rows), seg.cache.history(slot, cs), 3 * state.convWidth(cs)); + } else for (segments) |seg| for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| copyBf16(m, e, forward_attention.staged(s, seg.cache, seg.rows, slot, cs, seg.rows), seg.cache.history(slot, cs), 3 * state.convWidth(cs)); } pub fn run(m: *const Model, s: *state.Scratch, cache: *state.Cache, ids: []const u32, options: Options) !void { diff --git a/zig/src/families/inkling2/metal/forward_attention.zig b/zig/src/families/inkling2/metal/forward_attention.zig index c0afacd1fae..e7947354560 100644 --- a/zig/src/families/inkling2/metal/forward_attention.zig +++ b/zig/src/families/inkling2/metal/forward_attention.zig @@ -36,17 +36,21 @@ pub fn postConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segme e.barrier(); } -fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref { +pub fn staged(s: *const state.Scratch, cache: *const state.Cache, rows: usize, slot: usize, cs: usize, rows_before: usize) Ref { + return if (rows > state.window_rows) s.staged(slot, cs, rows_before) else cache.staged(slot, cs, rows_before); +} + +fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, s: *const state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) Ref { const channels = state.convWidth(conv_state); - const taps = cache.staged(slot, conv_state, 0); + const taps = staged(s, cache, rows, slot, conv_state, 0); copyBf16(m, e, cache.history(slot, conv_state), taps, 3 * channels); - copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), cache.staged(slot, conv_state, 3), rows * channels); + copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), staged(s, cache, rows, slot, conv_state, 3), rows * channels); return taps; } fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize, is_tree: bool) void { const channels = state.convWidth(conv_state); - const taps = stageConvInput(m, e, cache, slot, conv_state, raw, base, rows); + const taps = stageConvInput(m, e, s, cache, slot, conv_state, raw, base, rows); e.barrier(); if (is_tree) { tree.convStatic(&m.tree, e, taps, r(weight), at(s.conv_src, base * 4 * 4), at(out.buf, out.off + base * channels * 2), @intCast(rows), @intCast(channels)); @@ -108,8 +112,8 @@ pub fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, fn convInputsForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, is_tree: bool) void { const lp = m.weight_plan.at(v.layer); const w = &m.weights.layers[v.layer]; - const k_taps = stageConvInput(m, e, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows); - const v_taps = stageConvInput(m, e, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows); + const k_taps = stageConvInput(m, e, s, cache, v.cache_slot, 0, at(s.k_raw, 0), base, rows); + const v_taps = stageConvInput(m, e, s, cache, v.cache_slot, 1, at(s.v_raw, 0), base, rows); e.barrier(); const k_out = at(s.k_conv, base * state.kv_width * 2); const v_out = at(s.v_conv, base * state.kv_width * 2); diff --git a/zig/src/families/inkling2/metal/forward_conv.zig b/zig/src/families/inkling2/metal/forward_conv.zig index 6e5e2b7d649..26a46a03f6f 100644 --- a/zig/src/families/inkling2/metal/forward_conv.zig +++ b/zig/src/families/inkling2/metal/forward_conv.zig @@ -176,7 +176,7 @@ pub fn commitHistories(m: *const Model, e: mtl.ComputeEncoder, cache: *const sta e.setPipeline(m.runtime[@backingInt(model_file.RuntimeOp.commit_histories)]); e.setBuffer(cache.taps, 0, 0); e.setBuffer(cache.conv, 0, 1); - e.setValue(CommitHistoriesArgs{ .offset = @intCast(offset), .slots = state.visit_slots, .tap_rows = 3 + state.max_rows }, 2); + e.setValue(CommitHistoriesArgs{ .offset = @intCast(offset), .slots = state.visit_slots, .tap_rows = state.stage_rows }, 2); e.dispatchThreads(mtl.Size.of(state.visit_slots * 3 * state.conv_row_values, 1, 1), mtl.Size.of(256, 1, 1)); } diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig index 470a0ee6e59..d050ae34026 100644 --- a/zig/src/families/inkling2/metal/runtime_test.zig +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -82,15 +82,15 @@ test "Every visit and convolution role has disjoint persistent and staged bytes" if (slot != 0 or cs != 0) try std.testing.expect(off >= previous_persistent); previous_persistent = off + len; for (0..4) |accepted| { - const source = state.convByteOffset(slot, cs, accepted, 3 + state.max_rows); + const source = state.convByteOffset(slot, cs, accepted, state.stage_rows); try std.testing.expect(source + len <= state.taps_bytes); } }; try std.testing.expectEqual(state.conv_bytes, previous_persistent); // Decode acceptance k preserves exactly old[k], old[k+1], old[k+2] through raw[k..k+3]. for (0..state.window_rows + 1) |accepted| { - const old = state.convByteOffset(47, 3, 0, 3 + state.max_rows); - const selected = state.convByteOffset(47, 3, accepted, 3 + state.max_rows); + const old = state.convByteOffset(47, 3, 0, state.stage_rows); + const selected = state.convByteOffset(47, 3, accepted, state.stage_rows); try std.testing.expectEqual(old + accepted * state.hidden * 2, selected); } } @@ -428,7 +428,7 @@ pub fn rollbackCases() !void { // Case 3: post-full-CB partial accept selects staged offset; full accept/rollback keep conv exact. try blitFill(queue, cache.taps, 0, state.taps_bytes, 0x44); - const sel_off = state.convByteOffset(0, 0, 1, 3 + state.max_rows); + const sel_off = state.convByteOffset(0, 0, 1, state.stage_rows); const sel_len = 3 * state.convWidth(0) * 2; try blitFill(queue, cache.taps, sel_off, sel_len, 0x55); try cache.beginStage(4); diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 3c1c425ef77..07e1b7b223a 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -51,7 +51,13 @@ pub const sliding_ring = ap.ringFor(1024, max_rows); pub const conv_widths = [conv_states]usize{ 1024, 1024, 2304, 2304 }; pub const conv_row_values = 1024 + 1024 + 2304 + 2304; pub const conv_bytes = visit_slots * 3 * conv_row_values * 2; -pub const taps_bytes = visit_slots * (3 + max_rows) * conv_row_values * 2; +/// A cache stages a round's taps: three old rows and a window. A wider chunk stages in its scratch. +pub const stage_rows = 3 + window_rows; +pub const taps_bytes = visit_slots * stage_rows * conv_row_values * 2; +/// A scratch's staged taps for a chunk of up to `rows`; none where a cache's own staging holds them. +pub fn stageBytes(rows: usize) usize { + return if (rows > window_rows) visit_slots * (3 + rows) * conv_row_values * 2 else 0; +} pub fn globalSlots(capacity: usize) usize { return std.mem.alignForward(usize, capacity, ap.tile_keys); @@ -209,7 +215,7 @@ pub const Cache = struct { } pub fn staged(c: *const Cache, slot: usize, state: usize, rows_before: usize) Ref { - return .{ .buf = c.taps, .off = convByteOffset(slot, state, rows_before, 3 + max_rows) }; + return .{ .buf = c.taps, .off = convByteOffset(slot, state, rows_before, stage_rows) }; } pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { @@ -268,7 +274,7 @@ pub const Cache = struct { e.copy(c.backup, 0, c.conv, 0, conv_bytes); for (0..visit_slots) |slot| for (0..conv_states) |state| { const bytes = 3 * convWidth(state) * 2; - e.copy(c.taps, convByteOffset(slot, state, accepted, 3 + max_rows), c.conv, convByteOffset(slot, state, 0, 3), bytes); + e.copy(c.taps, convByteOffset(slot, state, accepted, stage_rows), c.conv, convByteOffset(slot, state, 0, 3), bytes); }; e.end(); cb.commit(); @@ -322,7 +328,7 @@ pub const Cache = struct { @memcpy(kv_args.path[0..path.len], path); tree.keepKv(ops, e, .{ .buf = c.kv }, kv_args); } - tree.keepConv(ops, e, .{ .buf = c.taps }, .{ .buf = c.conv }, .{ .src = convHistorySrc(path), .tap_rows = 3 + max_rows }); + tree.keepConv(ops, e, .{ .buf = c.taps }, .{ .buf = c.conv }, .{ .src = convHistorySrc(path), .tap_rows = stage_rows }); e.end(); cb.commit(); cb.wait(); @@ -423,7 +429,7 @@ fn sizes(rows: usize) [fields.len]usize { pub fn scratchBytes(rows: usize) usize { var out: usize = 0; for (sizes(rows)) |n| out += n; - return out; + return out + stageBytes(rows); } pub const Scratch = struct { @@ -487,6 +493,8 @@ pub const Scratch = struct { rel_bias: mtl.Buffer, /// Opt-in DSpark features [row][tap][H], allocated by prepare_features. taps: ?mtl.Buffer = null, + /// The staged convolution taps of a chunk wider than a window: this scratch then holds one stream's rows. + stage: ?mtl.Buffer = null, rows: usize, pub fn init(device: mtl.Device, rows: usize) !Scratch { @@ -502,14 +510,20 @@ pub const Scratch = struct { } s.taps = null; s.rows = rows; + s.stage = if (stageBytes(rows) > 0) try device.buffer(stageBytes(rows), mtl.ResourceOptions.private) else null; return s; } pub fn deinit(s: *Scratch) void { inline for (fields) |f| @field(s, f).deinit(); if (s.taps) |b| b.deinit(); + if (s.stage) |b| b.deinit(); s.* = undefined; } + + pub fn staged(s: *const Scratch, slot: usize, state: usize, rows_before: usize) Ref { + return .{ .buf = s.stage.?, .off = convByteOffset(slot, state, rows_before, 3 + s.rows) }; + } }; pub const validateParents = tree.plan.validateParents; diff --git a/zig/src/families/inkling2/metal/tree_gpu_test.zig b/zig/src/families/inkling2/metal/tree_gpu_test.zig index 1a0f07a3159..c7480b5b84f 100644 --- a/zig/src/families/inkling2/metal/tree_gpu_test.zig +++ b/zig/src/families/inkling2/metal/tree_gpu_test.zig @@ -71,7 +71,7 @@ test "Cache beginTree and commitPath compact sliding-wrap KV and all 4 conv hist for (0..st.visit_slots) |slot| for (0..st.conv_states) |cs| { const w = st.convWidth(cs); const h_off = st.convByteOffset(slot, cs, 0, 3) / 2; - const t_off = st.convByteOffset(slot, cs, 0, 3 + st.max_rows) / 2; + const t_off = st.convByteOffset(slot, cs, 0, st.stage_rows) / 2; @memcpy(taps_u16[t_off..][0 .. 3 * w], conv_u16[h_off..][0 .. 3 * w]); }; try blitCopy(queue, taps_stage, 0, cache.taps, 0, st.taps_bytes); @@ -103,7 +103,7 @@ test "Cache beginTree and commitPath compact sliding-wrap KV and all 4 conv hist const w = st.convWidth(cs); for (0..3) |out_r| { const dst_off = st.convByteOffset(slot, cs, out_r, 3) / 2; - const src_off = st.convByteOffset(slot, cs, want_src[out_r], 3 + st.max_rows) / 2; + const src_off = st.convByteOffset(slot, cs, want_src[out_r], st.stage_rows) / 2; try std.testing.expectEqualSlices(u16, taps_u16[src_off..][0..w], got_conv[dst_off..][0..w]); } } @@ -117,7 +117,7 @@ test "Cache beginTree and commitPath compact sliding-wrap KV and all 4 conv hist const want_src = tp.convHistorySrc(&path); for (0..3) |out_r| { const dst_off = st.convByteOffset(slot, cs, out_r, 3) / 2; - const src_off = st.convByteOffset(slot, cs, want_src[out_r], 3 + st.max_rows) / 2; + const src_off = st.convByteOffset(slot, cs, want_src[out_r], st.stage_rows) / 2; try std.testing.expectEqualSlices(u16, taps_u16[src_off..][0..w], got_conv[dst_off..][0..w]); } }; From 627d22935367a0ce2afc75ce465ab6b082ff1f06 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:26:19 -0500 Subject: [PATCH 11/13] inkling2 metal: prompt chunks of up to 1,024 rows, which the host may cap while replies decode --- zig/src/families/inkling2/metal/backend.zig | 2 +- zig/src/families/inkling2/metal/experts.zig | 2 +- zig/src/families/inkling2/metal/forward.zig | 1 + zig/src/families/inkling2/metal/glue.zig | 16 ++++++++-------- zig/src/families/inkling2/metal/glue_plan.zig | 2 +- zig/src/families/inkling2/metal/glue_test.zig | 4 +++- zig/src/families/inkling2/metal/loop.zig | 18 +++++++++--------- zig/src/families/inkling2/metal/loop_plan.zig | 2 +- zig/src/families/inkling2/metal/prefill.zig | 12 +++++++----- .../families/inkling2/metal/reset_batch.zig | 2 +- .../inkling2/metal/runtime_kernels_test.zig | 4 +++- .../families/inkling2/metal/runtime_plan.zig | 4 ++-- zig/src/families/inkling2/metal/state.zig | 8 ++++---- 13 files changed, 42 insertions(+), 35 deletions(-) diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index d23bc5c8fe9..da360ec0f75 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -138,7 +138,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .keep_full_lone = true, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .reports_fill = true, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + return .{ .keep_full_lone = true, .chunk_invariant = self.model.experts.units != null, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .reports_fill = true, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; } fn cast(ptr: *anyopaque) *Metal { diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 2a57e4913de..7af2ff2b3d7 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -42,7 +42,7 @@ const mma_names = [_][:0]const u8{ "tf_ink2_mma_group", "tf_ink2_nvfp4_gu_mma", /// The weight rows a simdgroup-matrix threadgroup takes. const mma_tile_rows = 64; /// The route pairs one expert may take: a chunk's rows, each of which names an expert once. -pub const mma_cap: u32 = 256; +pub const mma_cap: u32 = 1024; /// A chunk of at least this many rows takes the simdgroup-matrix kernels. pub const mma_rows: u32 = 16; pub const max_grouped_rows: u32 = plan.max_grouped_rows; diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index a274b8902b8..85cc99fb885 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -320,6 +320,7 @@ fn checkImages(m: *const Model, ids: []const u32, segments: usize, options: Opti pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, ids: []const u32, options: Options) !void { if (comptime @import("builtin").is_test and @hasDecl(mtl, "recordForward")) return mtl.recordForward(m, s, segments, ids, options, sample.encodeForwardDraw); const rows = ids.len; + if (options.all and rows > state.batch_rows) return error.Inkling2RowsExceeded; if (rows == 0 or rows > s.rows or segments.len == 0 or segments.len > state.max_segments or (!options.all and segments.len != 1)) return error.Inkling2RowsExceeded; const final = try sample.validatedFinalPlan(finalPlan(rows, options.all, options.taps != null), options.meta != null and (segments.len != 1 or rows != 1 or segments[0].parents != null), options.draw, options.draws, options.all, segments.len); var seg_meta: [state.max_segments]SegMeta = undefined; diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig index 5fcf3acd5bc..9d13539e558 100644 --- a/zig/src/families/inkling2/metal/glue.zig +++ b/zig/src/families/inkling2/metal/glue.zig @@ -142,7 +142,7 @@ pub fn ar(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, const BlockInvRmsArgs = extern struct { rows: u32, slot: u32 }; pub fn blockInvRms(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, inv_rms: Ref, rows: u32, slot: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and slot < 4); + std.debug.assert(rows > 0 and rows <= 1024 and slot < 4); e.setPipeline(p.block_inv_rms); inline for (.{ blocks, inv_rms }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(BlockInvRmsArgs{ .rows = rows, .slot = slot }, 2); @@ -165,7 +165,7 @@ pub fn cachedArRows(p: anytype, e: anytype, blocks: Ref, partial: Ref, block_inv const AttnPartialArArgs = extern struct { rows: u32, sources: u32, boundary: u32 }; /// Fuses attention_partial, optional block_inv_rms, and single-query MLP cached_ar across all rows. pub fn attnPartialAr(p: *const Pipelines, e: mtl.ComputeEncoder, p_: Ref, attn_conv: Ref, blocks: Ref, block_inv_rms: Ref, partial: Ref, query: Ref, out: Ref, rows: u32, sources_: u32, boundary: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and sources_ > 0 and sources_ <= 5 and boundary <= 4); + std.debug.assert(rows > 0 and rows <= 1024 and sources_ > 0 and sources_ <= 5 and boundary <= 4); e.setPipeline(p.attn_partial_ar); inline for (.{ p_, attn_conv, blocks, block_inv_rms, partial, query, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(AttnPartialArArgs{ .rows = rows, .sources = sources_, .boundary = boundary }, 7); @@ -175,7 +175,7 @@ pub fn attnPartialAr(p: *const Pipelines, e: mtl.ComputeEncoder, p_: Ref, attn_c const MlpPartialArArgs = extern struct { rows: u32, sources: u32, queries: u32 }; /// Fuses mlp_partial, BF16->FP32 widen, and next-visit attn_ar (or output_query AR) across all rows. pub fn mlpPartialAr(p: *const Pipelines, e: mtl.ComputeEncoder, partial_in: Ref, mlp_conv: Ref, blocks: Ref, block_inv_rms: Ref, queries: Ref, p_out: Ref, partial_out: Ref, ar_out: Ref, rows: u32, sources_: u32, queries_: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3); + std.debug.assert(rows > 0 and rows <= 1024 and sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3); e.setPipeline(p.mlp_partial_ar); inline for (.{ partial_in, mlp_conv, blocks, block_inv_rms, queries, p_out, partial_out, ar_out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(MlpPartialArArgs{ .rows = rows, .sources = sources_, .queries = queries_ }, 8); @@ -184,7 +184,7 @@ pub fn mlpPartialAr(p: *const Pipelines, e: mtl.ComputeEncoder, partial_in: Ref, /// Exact BF16-input RMSNorm matching widen + sp_norm bit-for-bit across all rows. pub fn normBf16(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, norm_w: Ref, out: Ref, rows: u32) void { - std.debug.assert(rows > 0 and rows <= 256); + std.debug.assert(rows > 0 and rows <= 1024); e.setPipeline(p.norm_bf16); inline for (.{ x, norm_w, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(EmbedArgs{ .rows = rows }, 3); @@ -193,7 +193,7 @@ pub fn normBf16(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, norm_w: Ref, /// Fuses attention_partial, optional block_inv_rms, single-query MLP AR, and RMSNorm on ungated visits. pub fn attnPartialArNorm(p: *const Pipelines, e: mtl.ComputeEncoder, p_: Ref, attn_conv: Ref, blocks: Ref, block_inv_rms: Ref, partial: Ref, query: Ref, norm_w: Ref, out: Ref, rows: u32, sources_: u32, boundary: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and sources_ > 0 and sources_ <= 5 and boundary <= 4); + std.debug.assert(rows > 0 and rows <= 1024 and sources_ > 0 and sources_ <= 5 and boundary <= 4); e.setPipeline(p.attn_partial_ar_norm); inline for (.{ p_, attn_conv, blocks, block_inv_rms, partial, query, norm_w, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(AttnPartialArArgs{ .rows = rows, .sources = sources_, .boundary = boundary }, 8); @@ -203,7 +203,7 @@ pub fn attnPartialArNorm(p: *const Pipelines, e: mtl.ComputeEncoder, p_: Ref, at const MlpPartialArNormArgs = extern struct { rows: u32, sources: u32 }; /// Fuses mlp_partial, widen, single-query AR, and RMSNorm for ungated local next visits and final output. pub fn mlpPartialArNorm(p: *const Pipelines, e: mtl.ComputeEncoder, partial_in: Ref, mlp_conv: Ref, blocks: Ref, block_inv_rms: Ref, query: Ref, norm_w: Ref, p_out: Ref, partial_out: Ref, norm_out: Ref, rows: u32, sources_: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and sources_ > 0 and sources_ <= 5); + std.debug.assert(rows > 0 and rows <= 1024 and sources_ > 0 and sources_ <= 5); e.setPipeline(p.mlp_partial_ar_norm); inline for (.{ partial_in, mlp_conv, blocks, block_inv_rms, query, norm_w, p_out, partial_out, norm_out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); e.setValue(MlpPartialArNormArgs{ .rows = rows, .sources = sources_ }, 9); @@ -311,7 +311,7 @@ const LogitArgs = extern struct { rows: u32, vocab: u32 }; pub const LogitVariant = enum { r4, r8, r16, r32 }; pub const LogitLaunch = struct { variant: LogitVariant, tile_r: u32, threads: u32 }; pub fn logitLaunch(rows: u32) LogitLaunch { - std.debug.assert(rows > 0 and rows <= 256); + std.debug.assert(rows > 0 and rows <= 1024); if (rows <= 4) return .{ .variant = .r4, .tile_r = 4, .threads = 128 }; if (rows <= 8) return .{ .variant = .r8, .tile_r = 8, .threads = 128 }; if (rows <= 16) return .{ .variant = .r16, .tile_r = 16, .threads = 128 }; @@ -319,7 +319,7 @@ pub fn logitLaunch(rows: u32) LogitLaunch { } pub fn logits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, out: Ref, rows: u32, vocab: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and vocab > 0 and vocab <= 200058); + std.debug.assert(rows > 0 and rows <= 1024 and vocab > 0 and vocab <= 200058); const launch = logitLaunch(rows); const pipe = switch (launch.variant) { .r4 => p.logits_r4, diff --git a/zig/src/families/inkling2/metal/glue_plan.zig b/zig/src/families/inkling2/metal/glue_plan.zig index 3d2f2ccdf30..eebe9b99a5b 100644 --- a/zig/src/families/inkling2/metal/glue_plan.zig +++ b/zig/src/families/inkling2/metal/glue_plan.zig @@ -81,7 +81,7 @@ pub const Call = struct { rows: usize, n: usize, k: usize }; pub fn valid(kind: Kind, c: Call) bool { const key_depth: usize = if (kind == .expert_combine) top_k else 4; const max_width: usize = if (kind == .conv_dynamic or kind == .kv_conv_dynamic) 1024 else hidden; - if (c.rows == 0 or c.rows > 256) return false; + if (c.rows == 0 or c.rows > 1024) return false; return switch (kind) { .embed_norm, .norm_bf16 => c.k == hidden and c.n == hidden, .router => c.k == hidden and c.n == top_k, diff --git a/zig/src/families/inkling2/metal/glue_test.zig b/zig/src/families/inkling2/metal/glue_test.zig index e463793e175..fb149124579 100644 --- a/zig/src/families/inkling2/metal/glue_test.zig +++ b/zig/src/families/inkling2/metal/glue_test.zig @@ -108,7 +108,9 @@ test "shape admission fixes Mini's hidden and routed dimensions" { try t.expect(!p.valid(.router, .{ .rows = 1, .n = 8, .k = 128 })); try t.expect(!p.valid(.conv_dynamic, .{ .rows = 1, .n = 2304, .k = 4 })); try t.expect(p.valid(.kv_conv_static, .{ .rows = 256, .n = p.hidden, .k = 4 })); - try t.expect(!p.valid(.kv_conv_static, .{ .rows = 257, .n = 1024, .k = 4 })); + try t.expect(p.valid(.kv_conv_static, .{ .rows = 257, .n = 1024, .k = 4 })); + try t.expect(p.valid(.kv_conv_static, .{ .rows = 1024, .n = 1024, .k = 4 })); + try t.expect(!p.valid(.kv_conv_static, .{ .rows = 1025, .n = 1024, .k = 4 })); try t.expect(p.valid(.kv_conv_dynamic, .{ .rows = 256, .n = 1024, .k = 4 })); try t.expect(!p.valid(.kv_conv_dynamic, .{ .rows = 1, .n = 2304, .k = 4 })); try t.expect(!p.valid(.swiglu, .{ .rows = 1, .n = p.intermediate + 1, .k = 2 })); diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig index 533b04ce590..a733bcf2f95 100644 --- a/zig/src/families/inkling2/metal/loop.zig +++ b/zig/src/families/inkling2/metal/loop.zig @@ -54,7 +54,7 @@ pub const Pipelines = struct { made += 1; if (pipe.maxThreads() < req_threads) return error.LoopThreads; } - const scratch = try device.buffer(max_gates * 256 * gate_row_bytes, mtl.ResourceOptions.shared); + const scratch = try device.buffer(max_gates * 1024 * gate_row_bytes, mtl.ResourceOptions.shared); return .{ .roles_norm = pipes[5], .roles_zeta = pipes[6], .roles_blend = pipes[7], .roles_scratch = scratch, .messages = pipes[0], .gates = pipes[1], .norm = pipes[2], .down = pipes[3], .apply = pipes[4] }; } pub fn deinit(p: *Pipelines) void { @@ -78,7 +78,7 @@ fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { /// Output layout is [token][12 core layers][q,k,v,mlp][H], all binary32. pub fn crossPassMessageAttention(p: *const Pipelines, e: mtl.ComputeEncoder, bank0: Ref, bank1: Ref, q_mlp: Ref, kv: Ref, out: Ref, rows: u32) void { - std.debug.assert(rows > 0 and rows <= 256); + std.debug.assert(rows > 0 and rows <= 1024); e.setPipeline(p.messages); bind(e, &.{ bank0, bank1, q_mlp, kv, out }); e.setValue(RowsArgs{ .rows = rows }, 5); @@ -87,7 +87,7 @@ pub fn crossPassMessageAttention(p: *const Pipelines, e: mtl.ComputeEncoder, ban /// One controller tuple; h, m and output are [token][H] binary32 tensors. pub fn gates(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32) void { - std.debug.assert(rows > 0 and rows <= 256); + std.debug.assert(rows > 0 and rows <= 1024); e.setPipeline(p.gates); bind(e, &.{ h, m, down, forget, gain, out }); e.setValue(RowsArgs{ .rows = rows }, 6); @@ -97,7 +97,7 @@ pub fn gates(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: R const SplitArgs = extern struct { rows: u32, m_stride: u32 }; /// `gates`' bits for every row in 3 launches; m rows m_stride floats apart; scratch [rows][2H] BF16, [rows][rank] F32. pub fn gatesSplit(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, m_stride: u32, down: Ref, forget: Ref, gain: Ref, out: Ref, normalized: Ref, zeta: Ref, rows: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and m_stride >= hidden); + std.debug.assert(rows > 0 and rows <= 1024 and m_stride >= hidden); const args = SplitArgs{ .rows = rows, .m_stride = m_stride }; e.setPipeline(p.norm); bind(e, &.{ h, m, normalized }); @@ -115,9 +115,9 @@ pub fn gatesSplit(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, m_ e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } -/// The gates of `rows` rows (at most 256) at once: h and out hold [row][H], m's rows are `m_stride` values apart. +/// The gates of `rows` rows (at most 1024) at once: h and out hold [row][H], m's rows are `m_stride` values apart. pub fn gatesRows(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, m_stride: u32, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32) !void { - std.debug.assert(rows > 0 and rows <= 256); + std.debug.assert(rows > 0 and rows <= 1024); const pipe = p.gates_mma orelse return error.NoSimdgroupMatrices; e.setPipeline(pipe); bind(e, &.{ h, m, down, forget, gain, out }); @@ -133,7 +133,7 @@ pub const Gate = struct { h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out /// gatesStrided for up to `max_gates` roles fused along grid.z with barriers between steps; outputs must be distinct. pub fn gatesEach(p: *const Pipelines, e: mtl.ComputeEncoder, items: []const Gate, rows: u32, m_stride: u32) void { - std.debug.assert(rows > 0 and rows <= 256 and items.len > 0 and items.len <= max_gates); + std.debug.assert(rows > 0 and rows <= 1024 and items.len > 0 and items.len <= max_gates); const roles: u32 = @intCast(items.len); const args = GateArgs{ .rows = rows, .stride = m_stride, .roles = roles }; const slot0 = items[0]; @@ -158,8 +158,8 @@ pub fn gatesEach(p: *const Pipelines, e: mtl.ComputeEncoder, items: []const Gate } fn normalizedOf(p: *const Pipelines, tuple: usize) Ref { - return .{ .buf = p.roles_scratch, .off = tuple * 256 * gate_row_bytes }; + return .{ .buf = p.roles_scratch, .off = tuple * 1024 * gate_row_bytes }; } fn zetaOf(p: *const Pipelines, tuple: usize) Ref { - return .{ .buf = p.roles_scratch, .off = tuple * 256 * gate_row_bytes + 256 * 2 * hidden * 2 }; + return .{ .buf = p.roles_scratch, .off = tuple * 1024 * gate_row_bytes + 1024 * 2 * hidden * 2 }; } diff --git a/zig/src/families/inkling2/metal/loop_plan.zig b/zig/src/families/inkling2/metal/loop_plan.zig index 6f1d11e3254..46c62a6dc8d 100644 --- a/zig/src/families/inkling2/metal/loop_plan.zig +++ b/zig/src/families/inkling2/metal/loop_plan.zig @@ -38,7 +38,7 @@ pub const Call = struct { rows: usize, n: usize, k: usize }; pub const Geometry = struct { groups: usize, threads: u32 = 256, tg_memory: u32 }; pub fn valid(kind: Kind, c: Call) bool { - if (c.rows == 0 or c.rows > 256) return false; + if (c.rows == 0 or c.rows > 1024) return false; return switch (kind) { .messages => c.n == message_entries * hidden and c.k == hidden, .gates => c.n == hidden and c.k == rank, diff --git a/zig/src/families/inkling2/metal/prefill.zig b/zig/src/families/inkling2/metal/prefill.zig index 4bf91fc4bfe..9c784cf123a 100644 --- a/zig/src/families/inkling2/metal/prefill.zig +++ b/zig/src/families/inkling2/metal/prefill.zig @@ -9,12 +9,12 @@ const SavedSnap = @import("drafter_snap.zig").Saved; pub fn feed(self: anytype, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows) !void { var at: usize = 0; - while (at < ids.len) at += try feedChunk(self, cache, ids[at..], stream, pictures); + while (at < ids.len) at += try feedChunk(self, cache, ids[at..], stream, pictures, 0); } -pub fn feedChunk(self: anytype, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows) !usize { +pub fn feedChunk(self: anytype, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows, cap: u32) !usize { const base = cache.len; - var end: usize = @min(ids.len, st.prompt_rows); + var end: usize = @min(ids.len, if (cap > 0) @min(st.prompt_rows, cap) else st.prompt_rows); if (stream) |sm| { if (sm.isCancelled()) return error.Cancelled; for (sm.chunks) |x| if (x > base and x < base + end) { @@ -113,7 +113,7 @@ pub fn whole(self: anytype, stream: *lanes.Stream) !void { try feed(self, cache, stream.prompt()[cache.len..], stream, &pictures); } -pub fn step(self: anytype, stream: *lanes.Stream, _: u32) !bool { +pub fn step(self: anytype, stream: *lanes.Stream, max_rows: u32) !bool { if (stream.images.len > 0) { try whole(self, stream); return true; @@ -122,7 +122,9 @@ pub fn step(self: anytype, stream: *lanes.Stream, _: u32) !bool { const cache = self.caches.get(stream) orelse try opening(self, stream); errdefer drop(self, stream); const ids = stream.prompt(); - _ = try feedChunk(self, cache, ids[cache.len..], stream, null); + const busy: u32 = if (self.caches.count() > 1) 256 else 0; + const cap = if (max_rows > 0 and busy > 0) @min(max_rows, busy) else @max(max_rows, busy); + _ = try feedChunk(self, cache, ids[cache.len..], stream, null, cap); return cache.len == ids.len; } diff --git a/zig/src/families/inkling2/metal/reset_batch.zig b/zig/src/families/inkling2/metal/reset_batch.zig index dc31016c4a6..78da1aea7c6 100644 --- a/zig/src/families/inkling2/metal/reset_batch.zig +++ b/zig/src/families/inkling2/metal/reset_batch.zig @@ -3,7 +3,7 @@ const std = @import("std"); pub const hidden: u32 = 2304; pub const block_slots: u32 = 4; -pub const max_rows: usize = 256; +pub const max_rows: usize = 1024; pub const CopyArgs = extern struct { count: u32, width: u32, src_stride: u32, dst_stride: u32 }; pub fn copyArgs(rows: usize) CopyArgs { diff --git a/zig/src/families/inkling2/metal/runtime_kernels_test.zig b/zig/src/families/inkling2/metal/runtime_kernels_test.zig index 525a8aba2f9..6fb1cb3c54f 100644 --- a/zig/src/families/inkling2/metal/runtime_kernels_test.zig +++ b/zig/src/families/inkling2/metal/runtime_kernels_test.zig @@ -81,7 +81,9 @@ test "linear launches bind H=2304 rows and the exact eight-byte argument ABI" { try t.expectEqual(@as(usize, 72), @sizeOf(p.InkConvSeg)); try t.expect(p.valid(.stage_conv, .{ .rows = 256, .n = 2304, .k = 1 })); try t.expect(p.valid(.stage_conv, .{ .rows = 1, .n = 1024, .k = 3 })); - try t.expect(!p.valid(.stage_conv, .{ .rows = 257, .n = 2304, .k = 1 })); + try t.expect(p.valid(.stage_conv, .{ .rows = 257, .n = 2304, .k = 1 })); + try t.expect(p.valid(.stage_conv, .{ .rows = 1024, .n = 2304, .k = 1 })); + try t.expect(!p.valid(.stage_conv, .{ .rows = 1025, .n = 2304, .k = 1 })); try t.expect(!p.valid(.stage_conv, .{ .rows = 1, .n = 1024, .k = 4 })); try t.expect(p.valid(.commit_histories, .{ .rows = 48, .n = 19, .k = 16 })); try t.expect(!p.valid(.commit_histories, .{ .rows = 49, .n = 19, .k = 1 })); diff --git a/zig/src/families/inkling2/metal/runtime_plan.zig b/zig/src/families/inkling2/metal/runtime_plan.zig index 6d9f59cfac4..bc2540cd7a6 100644 --- a/zig/src/families/inkling2/metal/runtime_plan.zig +++ b/zig/src/families/inkling2/metal/runtime_plan.zig @@ -4,8 +4,8 @@ const std = @import("std"); pub const hidden = 2304; pub const block_slots = 4; pub const tap_channels = 4; -pub const max_rows = 256; -pub const max_stage_rows = 256; +pub const max_rows = 1024; +pub const max_stage_rows = 1024; pub const visit_slots = 48; pub const window_rows = 16; pub const conv_states = 4; diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 07e1b7b223a..71180671096 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -24,8 +24,8 @@ pub const StageConvSegsArgs = extern struct { width: u32, n_segs: u32, pairs: u3 pub const window_rows = 16; pub const batch_rows = 32; -pub const prompt_rows = 256; -pub const max_rows = 256; +pub const prompt_rows = 1024; +pub const max_rows = 1024; pub const max_segments = batch_rows; pub const max_attention_stride = 64; pub const hidden = 2304; @@ -419,7 +419,7 @@ fn sizes(rows: usize) [fields.len]usize { r * h * fp, r * h * fp, r * h * bf, r * h * bf, r * h * bf, r * q * bf, r * kv * bf, r * kv * bf, r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf, r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * h * bf, - r * experts_per_token * 4, r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, r * vocabulary * fp, + r * experts_per_token * 4, r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, @as(usize, @min(r, batch_rows)) * vocabulary * fp, r * 128 * fp, r * 2 * h * bf, r * 64 * fp, experts_plan.groupBytes(r, experts_per_token), tr * 4 * 4, tr * window_rows * 4, tr * 2 * 24 * ap.head_dim * fp, tr * 24 * 16, (3 + r) * h * bf, visit_slots * 3 * max_segments * @sizeOf(InkConvSeg), visit_slots * 2 * max_segments * @sizeOf(glue.InkConvDynSeg), tr * 4, sc, sc, r * rb.heads * rb.extent * bf, @@ -534,5 +534,5 @@ pub const buildTreePaths = tree.plan.buildTreePaths; pub const convHistorySrc = tree.plan.convHistorySrc; comptime { - if (sliding_ring != 1280 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); + if (sliding_ring != 2048 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); } From 9d2dcab24028f54c545c6c53cb00ee632f482809 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:15:16 -0500 Subject: [PATCH 12/13] inkling2 metal: on M5 the prompt kernel reads a tile's keys and values from the cache, with no staging between --- zig/inkling2_source_owners_host.zig | 4 +-- .../metal/inkling2/prompt_attention.metal | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index 12ed28bbf1b..b5b6dd38ce8 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -37,8 +37,8 @@ test "every assembled glue kernel uses one scalar or vector width for positional } test "every current generated Inkling and LFM2 library matches its reviewed source pins" { try equal(ink.attention, 28563, "0969f2367a5955f0215ee82017fe536b85d5b9a5f763942383a4f90d1cda6f60"); - try equal(ink.prompt_attention, 37015, "41126214b24221c99eb3e12a4cae8f67647eb6ca7d56f6836375bb4089a2b997"); - try equal(ink.prompt_attention_pre_m5, 37039, "965ee2473d73b71fbcd51f0f514c657fd21df1e0e53a763c39c89c00642d1b47"); + try equal(ink.prompt_attention, 38459, "3057368237eda80ecaa153c6209821d297e6e957a252f0897cf7bf445611315e"); + try equal(ink.prompt_attention_pre_m5, 38483, "e5293db5b5144d0b8490a499c60a51e481e64cbf085ee6150042ce54d21eebef"); try equal(ink.glue, 42623, "0f4564349cd972c641812ab3d1fc71da085b88a045f28c794ecd35ff9718def7"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); try equal(ink.experts_units, 69553, "f60a6ef8610b08a30e878eb735105558034833550fc82115bf7e4460c7f073be"); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal index 8504edca39d..2279a3f2944 100644 --- a/zig/kernels/metal/inkling2/prompt_attention.metal +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -16,6 +16,17 @@ inline uint ink_prompt_first(constant InkPromptArgs& a, uint pos) { return a.window ? (pos + 1 > a.window ? pos + 1 - a.window : 0u) / a.chunk : a.c0; } +#ifndef TF_SIMD_FRAGS +// The 16x16 block at key row r, column c of a tile in the cache, two loads a lane; a key from `keys` on reads as zero. +inline void ink_tile_get(thread tfp::frag& f, const device bfloat* tile, int r, int c, short2 home, int keys) { + const device bfloat* q = tile + (r + home.y) * int(D) + (c + home.x); + const bfloat none = bfloat(0); + const bfloat4 zero = bfloat4(none, none, none, none); + f = tfp::frag(r + home.y < keys ? bfloat4(*(const device bfloat4*)q) : zero, + r + home.y + 8 < keys ? bfloat4(*(const device bfloat4*)(q + 8 * int(D))) : zero); +} +#endif + inline void ink_fold(thread float& mm, thread float& ll, float m, float l, thread float& a, thread float& b) { const float mn = max(mm, m); a = precise::exp2(mm - mn); @@ -44,7 +55,9 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi device float* part_o [[buffer(6)]], device float2* part_ml [[buffer(7)]], constant InkPromptArgs& a [[buffer(8)]], uint3 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) { +#ifdef TF_SIMD_FRAGS threadgroup bfloat ks[KEYS * D], vs[KEYS * D]; +#endif const InkPromptSeg s = segs[0]; const uint group = a.heads / a.kv_heads, total = uint(s.n) * group, m0 = tg.x * PAIRS; if (m0 >= total) return; @@ -66,6 +79,7 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi float upper[2] = {-INFINITY, -INFINITY}, whole[2] = {0.0f, 0.0f}; for (uint kt = b_lo; kt <= k_hi; kt += KEYS) { const uint tile_end = min(kt + KEYS, k_hi + 1); +#ifdef TF_SIMD_FRAGS for (uint e = t; e < KEYS * D; e += 256) { const uint key = e / D, col = e % D, kp = kt + key; const bool live = kp < tile_end; @@ -74,6 +88,12 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi vs[e] = live ? vc[at] : bfloat(0); } threadgroup_barrier(mem_flags::mem_threadgroup); +#else + // A tile is 64 keys from a multiple of 64 and a ring is a multiple of 64 rows, so a tile never wraps its ring. + const device bfloat* tile_k = kc + hb + size_t(kt % a.ring) * D; + const device bfloat* tile_v = vc + hb + size_t(kt % a.ring) * D; + const int keys = int(tile_end - kt); +#endif if ((kt - b_lo) % 1024 == 0) { for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); top[0] = top[1] = -INFINITY; mass[0] = mass[1] = 0.0f; @@ -83,10 +103,17 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi for (uint d = 0; d < 8; ++d) { tfp::frag qa, kb0, kb1, kb2, kb3; tfp::frag_get_rows(qa, qb0, qb1, 16 * d, home, row_a < total, row_b < total); +#ifdef TF_SIMD_FRAGS tfp::frag_get_t(kb0, ks, D, 0, 16 * d, home); tfp::frag_get_t(kb1, ks, D, 16, 16 * d, home); tfp::frag_get_t(kb2, ks, D, 32, 16 * d, home); tfp::frag_get_t(kb3, ks, D, 48, 16 * d, home); +#else + ink_tile_get(kb0, tile_k, 0, 16 * d, home, keys); + ink_tile_get(kb1, tile_k, 16, 16 * d, home, keys); + ink_tile_get(kb2, tile_k, 32, 16 * d, home, keys); + ink_tile_get(kb3, tile_k, 48, 16 * d, home, keys); +#endif tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); } @@ -137,8 +164,13 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) acc[d][e] *= keep[e >> 2]; for (uint f = 0; f < 4; ++f) for (uint d = 0; d < 8; d += 2) { tfp::frag v0, v1; +#ifdef TF_SIMD_FRAGS tfp::frag_get(v0, vs, D, 16 * f, 16 * d, home); tfp::frag_get(v1, vs, D, 16 * f, 16 * d + 16, home); +#else + ink_tile_get(v0, tile_v, 16 * f, 16 * d, home, keys); + ink_tile_get(v1, tile_v, 16 * f, 16 * d + 16, home, keys); +#endif tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); } } @@ -149,7 +181,9 @@ kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const devi ink_fold(upper[h], whole[h], top[h], mass[h], x, y); for (uint d = 0; d < 8; ++d) for (uint e = 4 * h; e < 4 * h + 4; ++e) out[d][e] = out[d][e] * x + acc[d][e] * y; } +#ifdef TF_SIMD_FRAGS threadgroup_barrier(mem_flags::mem_threadgroup); // no simdgroup reads ks/vs when the next tile overwrites them +#endif } if (m >= total) return; for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) { From 69863f2e484eafcc9ecd86c41f5f2c87c0f9552a Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:51:00 -0500 Subject: [PATCH 13/13] inkling2 metal: wide chunks take the routed experts on turned tiles, 16 weight rows by 32 of an expert's pairs an op --- zig/inkling2_source_owners_host.zig | 2 +- .../metal/inkling2/experts_units.metal | 104 ++++++++++++++++++ .../contract/inkling2_units_metal_records.zig | 4 + zig/src/families/inkling2/metal/experts.zig | 17 ++- zig/tests/contract/metal_inkling2_units.zig | 43 ++++++-- .../metal_inkling2_units_controls.zig | 12 +- zig/tests/contract/metal_mapping_test.zig | 2 +- 7 files changed, 165 insertions(+), 19 deletions(-) diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig index b5b6dd38ce8..cce54dcc92c 100644 --- a/zig/inkling2_source_owners_host.zig +++ b/zig/inkling2_source_owners_host.zig @@ -41,7 +41,7 @@ test "every current generated Inkling and LFM2 library matches its reviewed sour try equal(ink.prompt_attention_pre_m5, 38483, "e5293db5b5144d0b8490a499c60a51e481e64cbf085ee6150042ce54d21eebef"); try equal(ink.glue, 42623, "0f4564349cd972c641812ab3d1fc71da085b88a045f28c794ecd35ff9718def7"); try equal(ink.experts, 40741, "5dff5235b0ff5b3c033113043969c3b4d857a9c1751733c5824f6967b0c0db10"); - try equal(ink.experts_units, 69553, "f60a6ef8610b08a30e878eb735105558034833550fc82115bf7e4460c7f073be"); + try equal(ink.experts_units, 75820, "62306b93de9cbfe1ce27ea205762986ae76ca12dbcdc6b18ad65c8e2b322ebc4"); try equal(ink.experts_mma, 54957, "dd04bd9b6cd695404966f9b182831a35a987fb7db81aaf44ee6c440d231bca86"); try equal(ink.dense_mma, 5389, "6d0b015dd66035efbd110ae4d8dd690ca677ed9c500a83837aee7269161b334a"); try equal(ink.dense_tiled, 4324, "cdddebd86d265d9a79fd93b80894266750ca267e7ffeb76c481e6e73ab03c3ee"); diff --git a/zig/kernels/metal/inkling2/experts_units.metal b/zig/kernels/metal/inkling2/experts_units.metal index 851a9e05e37..cdf1507cd2a 100644 --- a/zig/kernels/metal/inkling2/experts_units.metal +++ b/zig/kernels/metal/inkling2/experts_units.metal @@ -136,6 +136,110 @@ inline void ink2_units(device const bfloat* X, device const uchar* W, device con ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); } +// Threadgroup (x, e): 16 weight rows of expert e by its pairs, 32 a band: ink2_units' tile turned, for wide chunks. +template +inline void ink2_units_t(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2UnitsArgs& a, uint2 tg, uint sg, uint lane, threadgroup float* part) { + const uint K = GU ? INK2_GU_K : INK2_DOWN_K, rows_w = GU ? 2u * a.n : a.n, steps = K / 128u; + const uint expert = tg.y, count = counts[expert]; + if (count == 0u) return; + const uint wb = FP8 ? K : K / 2u, sb = FP8 ? K / 32u : K / 16u; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + // A lane's two weight rows: the gate and up rows of output 8x + hy, or rows 16x + hy and 8 on. + const uint row0 = GU ? 2u * (8u * tg.x + hy) : 16u * tg.x + hy, row1 = GU ? row0 + 1u : row0 + 8u; + device const uchar* w0 = W + ulong(expert) * rows_w * wb + ulong(row0) * wb; + device const uchar* w1 = W + ulong(expert) * rows_w * wb + ulong(row1) * wb; + device const uchar* s0 = S + ulong(expert) * rows_w * sb + ulong(row0) * sb; + device const uchar* s1 = S + ulong(expert) * rows_w * sb + ulong(row1) * sb; + for (uint band = 0u; band < count; band += 32u) { + const uint m0 = band + hy, m1 = m0 + 8u, m2 = m0 + 16u, m3 = m0 + 24u; + const bool live0 = m0 < count, live1 = m1 < count, live2 = m2 < count, live3 = m3 < count; + const uint p0 = members[expert * a.cap + min(m0, count - 1u)], p1 = members[expert * a.cap + min(m1, count - 1u)]; + const uint p2 = members[expert * a.cap + min(m2, count - 1u)], p3 = members[expert * a.cap + min(m3, count - 1u)]; + device const bfloat* x0 = X + ulong(GU ? p0 / a.topk : p0) * K + hx; + device const bfloat* x1 = X + ulong(GU ? p1 / a.topk : p1) * K + hx; + device const bfloat* x2 = X + ulong(GU ? p2 / a.topk : p2) * K + hx; + device const bfloat* x3 = X + ulong(GU ? p3 / a.topk : p3) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * steps; b < (sg + 1u) * steps; ++b) { + tfp::frag fa; + if (FP8) fa = tfp::frag(ink2_mx_quad(w0, s0, b, hx), ink2_mx_quad(w1, s1, b, hx)); + else fa = tfp::frag(ink2_nv_quad(w0, s0, phi, b, hx), ink2_nv_quad(w1, s1, phi, b, hx)); + const tfp::frag b0 = ink2_units_x(x0, x1, live0, live1, 16u * b); + const tfp::frag b1 = ink2_units_x(x2, x3, live2, live3, 16u * b); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0u) { + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is weight row (e >> 2 ? row1 : row0), pair band + hx + (e & 3); hi is 16 pairs on. + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint m = band + 16u * side + hx + j; + if (m >= count) continue; + const ulong pair = members[expert * a.cap + m]; + const float v0 = side == 0u ? lo[j] : hi[j], v1 = side == 0u ? lo[4u + j] : hi[4u + j]; + if (GU) { + Y[pair * a.n + 8u * tg.x + hy] = ink2_act(v0, v1); + } else { + Y[pair * a.n + row0] = bfloat(v0); + Y[pair * a.n + row1] = bfloat(v1); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2UnitsArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2UnitsArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2UnitsArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2UnitsArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + struct Ink2LogitArgs { uint rows, vocab; }; // Threadgroup (x, y): vocabulary rows 32x .. + 31 by rows 16y .. + 15 of h, summed as the expert products are. diff --git a/zig/src/core/contract/inkling2_units_metal_records.zig b/zig/src/core/contract/inkling2_units_metal_records.zig index 938c9bffdbf..dcfdbb217c3 100644 --- a/zig/src/core/contract/inkling2_units_metal_records.zig +++ b/zig/src/core/contract/inkling2_units_metal_records.zig @@ -7,6 +7,10 @@ pub const records = [_]M{ .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_gu_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_logits_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, .{ .name = "metal inkling2 units tf_ink2_dense_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, }; diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig index 7af2ff2b3d7..fad279b2d3a 100644 --- a/zig/src/families/inkling2/metal/experts.zig +++ b/zig/src/families/inkling2/metal/experts.zig @@ -54,7 +54,7 @@ pub const Globals = struct { amax: Ref, denominator: Ref }; /// The columns the units kernels read a row: experts_units.metal's INK2_GU_K and INK2_DOWN_K. const units_gu_k = 2304; const units_down_k = 1152; -const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units", "tf_ink2_dense_units" }; +const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units", "tf_ink2_dense_units", "tf_ink2_nvfp4_gu_units_t", "tf_ink2_nvfp4_down_units_t", "tf_ink2_mxfp8_gu_units_t", "tf_ink2_mxfp8_down_units_t" }; pub const Pipelines = struct { units: ?[units_names.len]mtl.Pipeline = null, @@ -299,6 +299,15 @@ pub fn mma(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Re /// gu, or the down products (`down`), after group on the tensor units: an op is 16 of an expert's pairs by 32 rows. pub fn units(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + return launchUnits(p, e, down, c.rows > 512, x, w, scales, nv_globals, out, c); +} + +/// The same products on the turned tiles, 16 rows by 32 of an expert's pairs an op: the same sums, for wide chunks. +pub fn unitsTurned(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + return launchUnits(p, e, down, true, x, w, scales, nv_globals, out, c); +} + +fn launchUnits(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, turned: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { try plan.check(c); const pipes = p.units orelse return error.NoTensorUnits; if (c.rows > mma_cap or c.experts > plan.expert_count) return error.BadExpertShape; @@ -314,15 +323,15 @@ pub fn units(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: const g = nv_globals orelse return error.MissingNvfp4Globals; for ([_]Ref{ x, w, scales, g.amax, g.denominator, counts, members, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(value, 8); - e.setPipeline(pipes[@intFromBool(down)]); + e.setPipeline(pipes[(if (turned) @as(usize, 6) else 0) + @intFromBool(down)]); }, .mxfp8 => { for ([_]Ref{ x, w, scales, counts, members, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); e.setValue(value, 6); - e.setPipeline(pipes[2 + @as(usize, @intFromBool(down))]); + e.setPipeline(pipes[(if (turned) @as(usize, 6) else 0) + 2 + @as(usize, @intFromBool(down))]); }, } - e.dispatchGroups(mtl.Size.of((weight_rows + 31) / 32, c.experts, 1), mtl.Size.of(256, 1, 1)); + e.dispatchGroups(mtl.Size.of(if (turned) weight_rows / 16 else (weight_rows + 31) / 32, c.experts, 1), mtl.Size.of(256, 1, 1)); } /// Bucket route pairs by expert ID into <= 8-pair work items on GPU without host readback. diff --git a/zig/tests/contract/metal_inkling2_units.zig b/zig/tests/contract/metal_inkling2_units.zig index 6651f25ebe2..59f7b79e02e 100644 --- a/zig/tests/contract/metal_inkling2_units.zig +++ b/zig/tests/contract/metal_inkling2_units.zig @@ -11,7 +11,7 @@ const host = @import("tensorfold").inkling2_metal_host.experts; const controls = @import("metal_inkling2_units_controls.zig"); const src = @import("inkling2_metal"); -pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down }; +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_gu_t, nv_down_t, mx_gu_t, mx_down_t }; /// The columns the kernels fix for each product, and the experts `group` lists. const gu_k = 2304; @@ -25,6 +25,10 @@ fn symbol(k: Kind) []const u8 { .nv_down => "tf_ink2_nvfp4_down_units", .mx_gu => "tf_ink2_mxfp8_gu_units", .mx_down => "tf_ink2_mxfp8_down_units", + .nv_gu_t => "tf_ink2_nvfp4_gu_units_t", + .nv_down_t => "tf_ink2_nvfp4_down_units_t", + .mx_gu_t => "tf_ink2_mxfp8_gu_units_t", + .mx_down_t => "tf_ink2_mxfp8_down_units_t", }; } @@ -34,26 +38,43 @@ fn mutation(k: Kind) controls.Mutation { .nv_down => .nv_down_phi, .mx_gu => .mx_gu_scale, .mx_down => .mx_down_scale, + .nv_gu_t => .nv_gu_t_phi, + .nv_down_t => .nv_down_t_phi, + .mx_gu_t => .mx_gu_t_scale, + .mx_down_t => .mx_down_t_scale, }; } fn isNv(k: Kind) bool { - return k == .nv_gu or k == .nv_down; + return k == .nv_gu or k == .nv_down or k == .nv_gu_t or k == .nv_down_t; } fn isGu(k: Kind) bool { - return k == .nv_gu or k == .mx_gu; + return k == .nv_gu or k == .mx_gu or k == .nv_gu_t or k == .mx_gu_t; +} +/// The turned tiles: 16 weight rows by 32 of an expert's pairs an op. +fn isTurned(k: Kind) bool { + return k == .nv_gu_t or k == .nv_down_t or k == .mx_gu_t or k == .mx_down_t; } /// An op is 16 columns: the shared bound on its roundings a step, then the eight partial sums and the epilogue. fn depth(s: c.Shape) usize { return s.k / 16 * contract.attention_range.mma_step + 8 + 3; } +const gu_shapes = [_]c.Shape{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 20, .n = 16, .k = gu_k } }; +const gu_turned_shapes = [_]c.Shape{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 40, .n = 16, .k = gu_k } }; +const down_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 20, .n = 32, .k = down_k } }; +const down_turned_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 40, .n = 32, .k = down_k } }; + pub fn spec(k: Kind, control: bool) c.Spec { const base = if (control) mutation(k).name() else switch (k) { .nv_gu => "metal inkling2 units tf_ink2_nvfp4_gu_units", .nv_down => "metal inkling2 units tf_ink2_nvfp4_down_units", .mx_gu => "metal inkling2 units tf_ink2_mxfp8_gu_units", .mx_down => "metal inkling2 units tf_ink2_mxfp8_down_units", + .nv_gu_t => "metal inkling2 units tf_ink2_nvfp4_gu_units_t", + .nv_down_t => "metal inkling2 units tf_ink2_nvfp4_down_units_t", + .mx_gu_t => "metal inkling2 units tf_ink2_mxfp8_gu_units_t", + .mx_down_t => "metal inkling2 units tf_ink2_mxfp8_down_units_t", }; return .{ .name = base, @@ -62,12 +83,9 @@ pub fn spec(k: Kind, control: bool) c.Spec { .ops = if (isGu(k)) 12 else 3, .mids = if (isGu(k)) 3 else 0, .out = .bf16, - // An expert's pairs go 16 a band: one expert takes every row here, so 20 rows cross a band. - .tiles = .{ .{ .size = 16 }, .{}, .{} }, - .served = if (isGu(k)) - &.{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 20, .n = 16, .k = gu_k } } - else - &.{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 20, .n = 32, .k = down_k } }, + // One expert takes every row here, so 20 rows cross a 16-pair band and 40 a turned tile's 32. + .tiles = .{ .{ .size = if (isTurned(k)) 32 else 16 }, .{}, .{} }, + .served = if (isGu(k)) (if (isTurned(k)) &gu_turned_shapes else &gu_shapes) else if (isTurned(k)) &down_turned_shapes else &down_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and explicit BF16 nodes" }, }; } @@ -204,7 +222,8 @@ pub const Probe = struct { const out = hr(p.refs[if (nv) 6 else 4]); try host.group(&p.pipes, e, ids, p.call()); e.barrier(); - try host.units(&p.pipes, e, !isGu(p.kind), hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), if (nv) .{ .amax = hr(p.refs[3]), .denominator = hr(p.refs[4]) } else null, out, p.call()); + const launch = if (isTurned(p.kind)) &host.unitsTurned else &host.units; + try launch(&p.pipes, e, !isGu(p.kind), hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), if (nv) .{ .amax = hr(p.refs[3]), .denominator = hr(p.refs[4]) } else null, out, p.call()); try p.rig.finish(pass); } @@ -290,7 +309,7 @@ pub const Suite = struct { device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), - probes: [8]Probe = undefined, + probes: [16]Probe = undefined, made: usize = 0, pub fn deinit(s: *Suite) void { @@ -310,7 +329,7 @@ pub const Suite = struct { } }; -test "contract labels resolve to the four units entries" { +test "contract labels resolve to the units entries" { for (std.enums.values(Kind)) |kind| { const name = spec(kind, false).name; try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); diff --git a/zig/tests/contract/metal_inkling2_units_controls.zig b/zig/tests/contract/metal_inkling2_units_controls.zig index abe7446f8f8..b7de39cda79 100644 --- a/zig/tests/contract/metal_inkling2_units_controls.zig +++ b/zig/tests/contract/metal_inkling2_units_controls.zig @@ -9,6 +9,10 @@ pub const Mutation = enum { nv_down_phi, mx_gu_scale, mx_down_scale, + nv_gu_t_phi, + nv_down_t_phi, + mx_gu_t_scale, + mx_down_t_scale, logits_cap, dense_store, @@ -19,6 +23,10 @@ pub const Mutation = enum { .nv_down_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units phi", .mx_gu_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units scale", .mx_down_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units scale", + .nv_gu_t_phi => "control: metal inkling2 units tf_ink2_nvfp4_gu_units_t phi", + .nv_down_t_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units_t phi", + .mx_gu_t_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units_t scale", + .mx_down_t_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units_t scale", .logits_cap => "control: metal inkling2 units tf_ink2_logits_units cap", .dense_store => "control: metal inkling2 units tf_ink2_dense_units store", }; @@ -35,7 +43,9 @@ pub const Mutation = enum { .nv_gu_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, .nv_down_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, // Both MXFP8 entries decode through one helper; a control compiles only its selected entry. - .mx_gu_scale, .mx_down_scale => .{ .from = "const uint scale = uint(scales[b / 2u]);", .to = "const uint scale = uint(scales[b / 2u]) + 1u;" }, + .nv_gu_t_phi => .{ .from = "ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units_t(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_t_phi => .{ .from = "ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units_t(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .mx_gu_scale, .mx_down_scale, .mx_gu_t_scale, .mx_down_t_scale => .{ .from = "const uint scale = uint(scales[b / 2u]);", .to = "const uint scale = uint(scales[b / 2u]) + 1u;" }, .logits_cap => .{ .from = "precise::divide(float(bfloat(dot)), 30.0f)", .to = "precise::divide(float(bfloat(dot)), 15.0f)" }, .dense_store => .{ .from = "Y[row * a.n + v] = bfloat(dot);", .to = "Y[row * a.n + v] = bfloat(2.0f * dot);" }, }; diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index 3969c4930df..eeb9b2e31d9 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -101,5 +101,5 @@ test "Metal launch map: every expert tensor-unit launch is M5-only and resolves" try std.testing.expect(launches.supported(.{ .units = true }, launch)); count += 1; } - try std.testing.expectEqual(@as(usize, 6), count); + try std.testing.expectEqual(@as(usize, 10), count); }