From aeb9cb06c3d58a55979e0156851ab4597d5642b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:01:00 +0100 Subject: [PATCH 01/84] inkling2: Mini's shapes on Small's kernels under the contract Every Inkling 2 CUDA kernel but the EXL3 expert epilogues now also runs at Inkling 2 Mini's one-rank shapes (hidden 2,304, 24 over 8 key heads, k/v width 1,024, 128 experts top 8, floor 8,192, one 201,024-wide vocab row), each with its planted control. No kernel source changes: the widths were already arguments. Small's registrations keep their names, shapes and seeds. Host checks refuse what the kernels cannot hold, by name: Inkling2MixWidth, Inkling2RouterShape, Inkling2ConvHeads, Inkling2Heads. --- zig/src/families/inkling2/kernels.zig | 7 ++ zig/src/families/inkling2/kernels_test.zig | 51 +++++++-- zig/src/families/inkling2/ops.zig | 24 +++- zig/src/families/inkling2/ops_test.zig | 54 +++++++++ zig/tests/cuda/contract_inkling2_attn.zig | 22 ++-- .../cuda/contract_inkling2_attn_prep.zig | 27 +++-- zig/tests/cuda/contract_inkling2_attn_ref.zig | 18 ++- .../cuda/contract_inkling2_attn_rows.zig | 52 +++++---- zig/tests/cuda/contract_inkling2_model.zig | 57 ++++++++++ zig/tests/cuda/contract_inkling2_ops.zig | 50 +++++---- zig/tests/cuda/contract_inkling2_ops_conv.zig | 106 ++++++++++++------ zig/tests/cuda/contract_inkling2_ops_mix.zig | 47 +++++--- zig/tests/cuda/contract_inkling2_ops_pick.zig | 91 +++++++++------ .../cuda/contract_inkling2_ops_route.zig | 20 ++-- zig/tests/cuda/contract_inkling2_ops_rows.zig | 67 +++++++---- 15 files changed, 506 insertions(+), 187 deletions(-) create mode 100644 zig/src/families/inkling2/ops_test.zig create mode 100644 zig/tests/cuda/contract_inkling2_model.zig diff --git a/zig/src/families/inkling2/kernels.zig b/zig/src/families/inkling2/kernels.zig index 42545e7715c..cfdf45eb374 100644 --- a/zig/src/families/inkling2/kernels.zig +++ b/zig/src/families/inkling2/kernels.zig @@ -153,8 +153,14 @@ fn goShared(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, sha try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads }, .shared = shared }, s, a); } +/// Whether heads split into whole groups (query head h reads key head h / (heads / kv_heads)): Small 24/4, Mini 24/8. +pub fn headsFit(r: Rows) error{Inkling2Heads}!void { + if (r.heads == 0 or r.kv_heads == 0 or r.heads % r.kv_heads != 0) return error.Inkling2Heads; +} + /// q, rel (per head) and k, v (per key head, written to the caches at pos % ring) from the projections' rows. pub fn prep(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, c: Prep, raw: [4]u64, scales: [2]u64, q: u64, rel: u64, kv: Cache) !void { + try headsFit(r); var a: cuda.Args = .{}; for (raw) |v| a.add(v); for (scales) |v| a.add(v); @@ -176,6 +182,7 @@ pub fn relTable(k: *const Kernels, s: cuda.Stream, r: Rows, rel: u64, proj: u64, /// Attention into chunk partials (`stride` a row and head; a split call's sub-chunks), then the ordered merge. pub fn attend(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, stride: u32, slots: usize, q: u64, kv: Cache, tab: u64, part_o: u64, part_ml: u64, sink: u64, gate: u64, out: u64) !void { + try headsFit(r); if (slotsFor(l, r.last_pos + 1) > stride) return error.Inkling2Partials; const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); var a: cuda.Args = .{}; diff --git a/zig/src/families/inkling2/kernels_test.zig b/zig/src/families/inkling2/kernels_test.zig index 210ac545eaa..71a96c95385 100644 --- a/zig/src/families/inkling2/kernels_test.zig +++ b/zig/src/families/inkling2/kernels_test.zig @@ -108,8 +108,7 @@ test "inkling2 kernels: sliding partials are a row's window at any depth, a tile } /// A call's sliding stores as tf_ink2_attn makes them: each slot the merge reads once; returns the old strays. -fn slidingStores(a: std.mem.Allocator, p0: usize, n: usize) !usize { - const group = 6; +fn slidingStores(a: std.mem.Allocator, p0: usize, n: usize, group: u32) !usize { const l = k.Layer.sliding(1024, 2048); const stride: usize = k.slotsFor(l, 1); // 5 below 81,920: a stray store lands on a neighbour (row, head)'s slots const count = try a.alloc(u8, n * group * stride); @@ -147,12 +146,46 @@ fn slidingStores(a: std.mem.Allocator, p0: usize, n: usize) !usize { test "inkling2 kernels: sliding stores stay in their own slots for windows that straddle a chunk edge" { const a = t.allocator; // the drafted check's long text: 8-row windows at 2,296..2,302 (a window's first keys cross chunk 5's edge) - try t.expectEqual(@as(usize, 0), try slidingStores(a, 2295, 8)); - try t.expect(try slidingStores(a, 2300, 8) > 0); - try t.expect(try slidingStores(a, 2296, 8) > 0); - var p0: usize = 0; - while (p0 < 4400) : (p0 += 1) for (1..9) |n| { - _ = try slidingStores(a, p0, n); + try t.expectEqual(@as(usize, 0), try slidingStores(a, 2295, 8, 6)); + try t.expect(try slidingStores(a, 2300, 8, 6) > 0); + try t.expect(try slidingStores(a, 2296, 8, 6) > 0); + // Small's 6 query heads a key head at TP=2, Mini's 3 (24 over 8 key heads) + for ([_]u32{ 6, 3 }) |group| { + var p0: usize = 0; + while (p0 < 4400) : (p0 += 1) for (1..9) |n| { + _ = try slidingStores(a, p0, n, group); + }; + for ([_]usize{ 0, 2048, 4096 }) |at| _ = try slidingStores(a, at, 2048, group); + } +} + +test "inkling2 kernels: Mini's 8 key heads launch a group of 3; heads that do not split are refused, nothing launched" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Fake.launch; + const fun = struct { + fn of(drv: *const cuda.Driver, i: usize) cuda.Function { + return .{ .d = drv, .handle = @ptrFromInt(i) }; + } }; - for ([_]usize{ 0, 2048, 4096 }) |at| _ = try slidingStores(a, at, 2048); + const kern: k.Kernels = .{ .mod = .{ .d = &d, .handle = null }, .prep = fun.of(&d, 1), .rel_table = fun.of(&d, 2), .attn = fun.of(&d, 3), .merge = fun.of(&d, 4), .attn_fold = fun.of(&d, 3), .pmod = .{ .d = &d, .handle = null }, .attn_prompt = fun.of(&d, 3) }; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + const cfg: k.Prep = .{ .qk_clip = 22.6, .rel_clip = 8, .floor = 8192, .alpha = 0.1, .eps = 1e-6 }; + const l = k.Layer.global(1048576); + var r: k.Rows = .{ .rows = 2048, .heads = 24, .kv_heads = 8, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 1048575 }; + Fake.count = 0; + try k.prep(&kern, s, r, l, cfg, .{ 0, 0, 0, 0 }, .{ 0, 0 }, 0, 0, .{ .k = 0, .v = 0 }); + try t.expectEqual([3]u32{ 2048, 40, 1 }, Fake.grids[0]); // 24 q heads, 8 k and 8 v heads a row + // a 2,048-row prompt call: 2,048 x 3 pairs a key head in blocks of 128 + try k.attend(&kern, s, r, l, 64, 0, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0); + try t.expectEqual([3]u32{ 48, 8, 64 }, Fake.grids[2]); + try t.expectEqual(@as(u32, 6), k.tileChunks(3, k.Layer.sliding(1024, 1))); // a tile's 21 rows and their windows + try t.expectEqual(@as(usize, 96), k.tileCount(2048, 3)); + const counted = Fake.count; + for ([_][2]u32{ .{ 24, 5 }, .{ 24, 0 }, .{ 0, 8 } }) |h| { + r.heads = h[0]; + r.kv_heads = h[1]; + try t.expectError(error.Inkling2Heads, k.prep(&kern, s, r, l, cfg, .{ 0, 0, 0, 0 }, .{ 0, 0 }, 0, 0, .{ .k = 0, .v = 0 })); + try t.expectError(error.Inkling2Heads, k.attend(&kern, s, r, l, 64, 0, 0, .{ .k = 0, .v = 0 }, 0, 0, 0, 0, 0, 0)); + } + try t.expectEqual(counted, Fake.count); } diff --git a/zig/src/families/inkling2/ops.zig b/zig/src/families/inkling2/ops.zig index fb2bdeeabc6..66e7b5d50a5 100644 --- a/zig/src/families/inkling2/ops.zig +++ b/zig/src/families/inkling2/ops.zig @@ -128,9 +128,24 @@ pub fn embed(k: *const Kernels, s: cuda.Stream, ids: u64, rows: usize, table: u6 try go(k.embed, s, .{ .x = @intCast(rows) }, 256, &a); } +/// Whether tf_ink2_mix holds a row: ops.cu's kMixCache x 512 columns, 16-byte copies (Small 4,608, Mini 2,304). +pub fn mixFits(c: i32) error{Inkling2MixWidth}!void { + if (c <= 0 or c > 10 * 512 or @rem(c, 128) != 0) return error.Inkling2MixWidth; +} + +/// Whether tf_ink2_topk picks: 8 scores a thread of 512, 32 picks at most (Small 384 experts, Mini 128; top 8). +pub fn routerFits(experts: usize, top: usize) error{Inkling2RouterShape}!void { + if (experts == 0 or experts > 512 * 8 or top == 0 or top > 32 or top > experts) return error.Inkling2RouterShape; +} + +/// Whether dynamic conv taps split the width: column c reads head c / (C / heads) (Small 4 key heads, Mini 8). +pub fn convFits(c: ConvArgs) error{Inkling2ConvHeads}!void { + if (c.dyn != 0 and (c.heads <= 0 or c.c <= 0 or @rem(c.c, c.heads) != 0)) return error.Inkling2ConvHeads; +} + /// The residual mix of each row and query, normed: a block a row. pub fn mix(k: *const Kernels, s: cuda.Stream, m: MixArgs) !void { - if (m.c > 10 * 512 or @rem(m.c, 128) != 0) return error.Inkling2MixWidth; // ops.cu: kMixCache x 512 columns, 16-byte copies + try mixFits(m.c); var a: cuda.Args = .{}; a.add(m); try go(if (m.rows <= 16) k.mix else k.mix_rows, s, .{ .x = @intCast(m.rows) }, 512, &a); // equal bits either way @@ -150,7 +165,7 @@ pub fn rowdot(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, out: u64, rows: /// The router's picks and weights from fp32 sigmoid scores [rows, experts] and the selection bias. pub fn topk(k: *const Kernels, s: cuda.Stream, scores: u64, bias: u64, pick: u64, wts: u64, rows: usize, experts: usize, top: usize, scale: f32) !void { - if (experts > 512 * 8 or top > 32) return error.Inkling2RouterShape; + try routerFits(experts, top); var a: cuda.Args = .{}; for ([_]u64{ scores, bias, pick, wts }) |v| a.add(v); a.add(int(experts)); @@ -168,6 +183,7 @@ pub fn gateup(k: *const Kernels, s: cuda.Stream, g: GateUpArgs) !void { /// A short convolution over each of `streams` streams' rows, their states carried (ops.cu's tf_ink2_conv). pub fn conv(k: *const Kernels, s: cuda.Stream, c: ConvArgs, streams: usize) !void { + try convFits(c); var a: cuda.Args = .{}; a.add(c); // a stream's rows in blocks of 32 (blocks past a stream's rows return at once) @@ -252,3 +268,7 @@ test "ops: the argument structs keep ops.cu's layouts" { try std.testing.expectEqual(@as(usize, 32), @sizeOf(RewindSite)); try std.testing.expectEqual(@as(usize, 6 * 8 + 6 * 4), @sizeOf(GateUpArgs)); } + +test { + _ = @import("ops_test.zig"); +} diff --git a/zig/src/families/inkling2/ops_test.zig b/zig/src/families/inkling2/ops_test.zig new file mode 100644 index 00000000000..147f41bef31 --- /dev/null +++ b/zig/src/families/inkling2/ops_test.zig @@ -0,0 +1,54 @@ +//! Inkling 2's glue launchers without a GPU: Mini's and Small's shapes launch, the rest are refused by name. +const std = @import("std"); +const cuda = @import("cuda"); +const ops = @import("ops.zig"); +const t = std.testing; + +const Fake = struct { + var count: usize = 0; + var grid: [3]u32 = undefined; + fn launch(_: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + grid = .{ gx, gy, gz }; + count += 1; + return 0; + } +}; + +fn kernels(d: *const cuda.Driver) ops.Kernels { + var k: ops.Kernels = undefined; + k.mod = .{ .d = d, .handle = null }; + k.rows_mod = .{ .d = d, .handle = null }; + const info = @typeInfo(ops.Kernels).@"struct"; + inline for (info.field_names, info.field_types, 1..) |name, ty, i| { + if (ty == cuda.Function) @field(k, name) = .{ .d = d, .handle = @ptrFromInt(i) }; + } + return k; +} + +test "inkling2 ops: Mini's widths launch (hidden 2,304, 8 key heads, 128 experts) as Small's do" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Fake.launch; + const k = kernels(&d); + const s: cuda.Stream = .{ .d = &d, .handle = null }; + Fake.count = 0; + for ([_]i32{ 2304, 4608 }) |c| try ops.mix(&k, s, .{ .partial = 0, .query = 0, .out = 0, .n_blocks = 8, .partial_bf16 = 1, .nq = 3, .rows = 1, .c = c, .eps = 1e-6 }); + for ([_][2]usize{ .{ 128, 8 }, .{ 384, 8 } }) |e| try ops.topk(&k, s, 0, 0, 0, 0, 16, e[0], e[1], 8); + for ([_][2]i32{ .{ 512, 4 }, .{ 1024, 8 } }) |w| try ops.conv(&k, s, .{ .x = 0, .state = 0, .w = 0, .dyn = 1, .heads = w[1], .c = w[0], .rows = 4, .mode = 0 }, 1); + try t.expectEqual(@as(usize, 6), Fake.count); + try t.expectEqual([3]u32{ 8, 1, 1 }, Fake.grid); // Mini's k/v conv: 1,024 columns in blocks of 128 +} + +test "inkling2 ops: widths, routers and dynamic taps the kernels cannot hold are refused by name, nothing launched" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Fake.launch; + const k = kernels(&d); + const s: cuda.Stream = .{ .d = &d, .handle = null }; + Fake.count = 0; + for ([_]i32{ 0, 2300, 5248, -128 }) |c| try t.expectError(error.Inkling2MixWidth, ops.mix(&k, s, .{ .partial = 0, .query = 0, .out = 0, .n_blocks = 1, .partial_bf16 = 1, .nq = 1, .rows = 1, .c = c, .eps = 1e-6 })); + for ([_][2]usize{ .{ 4097, 8 }, .{ 128, 33 }, .{ 128, 0 }, .{ 4, 8 }, .{ 0, 0 } }) |e| try t.expectError(error.Inkling2RouterShape, ops.topk(&k, s, 0, 0, 0, 0, 1, e[0], e[1], 8)); + for ([_][2]i32{ .{ 1024, 0 }, .{ 1024, 3 }, .{ 1020, 8 } }) |w| try t.expectError(error.Inkling2ConvHeads, ops.conv(&k, s, .{ .x = 0, .state = 0, .w = 0, .dyn = 1, .heads = w[1], .c = w[0], .rows = 1, .mode = 0 }, 1)); + try t.expectEqual(@as(usize, 0), Fake.count); + // static taps read no heads: any width launches + try ops.conv(&k, s, .{ .x = 0, .state = 0, .w = 0, .heads = 3, .c = 1000, .rows = 1, .mode = 0 }, 1); + try t.expectEqual(@as(usize, 1), Fake.count); +} diff --git a/zig/tests/cuda/contract_inkling2_attn.zig b/zig/tests/cuda/contract_inkling2_attn.zig index 3c339b46ef9..53ffc3fdbe3 100644 --- a/zig/tests/cuda/contract_inkling2_attn.zig +++ b/zig/tests/cuda/contract_inkling2_attn.zig @@ -6,21 +6,25 @@ const g = @import("core").contract.gates; const K = @import("inkling2").kernels; const rows = @import("contract_inkling2_attn_rows.zig"); const prep = @import("contract_inkling2_attn_prep.zig"); +const M = @import("contract_inkling2_model.zig"); -/// The attention launches as the forward makes them: prep, the bias table, then the chunks and their merge. +/// The attention launches as the forward makes them (prep, bias table, chunks and merge): Small's, then Mini's. pub const Set = struct { k: K.Kernels = undefined, loaded: bool = false, - attns: [7]rows.Attn = undefined, - preps: [3]prep.Prep = undefined, - tables: [2]prep.Table = undefined, + attns: [14]rows.Attn = undefined, + preps: [6]prep.Prep = undefined, + tables: [2]prep.Table = undefined, // Mini's bias tables have Small's shapes: one registration covers both /// Every registration (the fold first: the split and prompt launches must equal its bits), then the controls. pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { set.k = try K.Kernels.load(gpu.d); const forms = [_]struct { rows.Path, rows.Plant }{ .{ .sliding, .none }, .{ .fold, .none }, .{ .split, .none }, .{ .prompt, .none }, .{ .sliding, .late_bias }, .{ .fold, .no_sink }, .{ .prompt, .q_ulp } }; - for (&set.attns, forms) |*x, f| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .path = f[0], .plant = f[1] }; - for (&set.preps, [_]bool{ false, true, true }, 0..) |*x, global, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .global = global, .tau_off = i == 2 }; + for (&set.attns, 0..) |*x, i| { + const f = forms[i % 7]; + x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .path = f[0], .plant = f[1], .m = if (i < 7) M.small else M.mini }; + } + for (&set.preps, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .global = i % 3 != 0, .tau_off = i % 3 == 2, .m = if (i < 3) M.small else M.mini }; for (&set.tables, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .k = &set.k, .late = i == 1 }; set.loaded = true; errdefer set.deinit(); @@ -29,7 +33,11 @@ pub const Set = struct { for (set.attns[0..4]) |*x| try list.append(a, x.kernel()); try list.append(a, set.preps[2].kernel()); try list.append(a, set.tables[1].kernel()); - for (set.attns[4..]) |*x| try list.append(a, x.kernel()); + for (set.attns[4..7]) |*x| try list.append(a, x.kernel()); + for (set.preps[3..5]) |*x| try list.append(a, x.kernel()); + for (set.attns[7..11]) |*x| try list.append(a, x.kernel()); + try list.append(a, set.preps[5].kernel()); + for (set.attns[11..]) |*x| try list.append(a, x.kernel()); } pub fn deinit(set: *Set) void { diff --git a/zig/tests/cuda/contract_inkling2_attn_prep.zig b/zig/tests/cuda/contract_inkling2_attn_prep.zig index 35cea83270a..294944902fc 100644 --- a/zig/tests/cuda/contract_inkling2_attn_prep.zig +++ b/zig/tests/cuda/contract_inkling2_attn_prep.zig @@ -5,6 +5,7 @@ const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_attn_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const contract = core.contract; const c = contract.spec; @@ -12,7 +13,6 @@ const g = contract.gates; const K = ink.kernels; const D = ref.D; const heads = ref.heads; -const kv = ref.kv; const R = ref.d_rel; const u: f64 = 0x1p-24; @@ -24,9 +24,9 @@ fn depthPrep(_: c.Shape) usize { return 4 + 5; // a lane's four squares, then the warp's five butterfly adds } -/// rows x 24 heads x 128 (q); k: the first stream's context, so global rows meet tau at 1M positions. -pub fn prepSpec(global: bool) c.Spec { - const name = if (global) "inkling2 attn tf_ink2_prep global (q, rel scaled by tau; k, v into a 4,096-slot ring)" else "inkling2 attn tf_ink2_prep sliding (q, rel, k, v rows into the 3,072-slot ring)"; +/// rows x 24 heads x 128 (q); k: the first stream's context, so global rows meet tau at 1M positions (Mini: 8 kv). +pub fn prepSpec(global: bool, mini: bool) c.Spec { + const name = if (global) M.named("inkling2 attn tf_ink2_prep global (q, rel scaled by tau; k, v into a 4,096-slot ring)", mini) else M.named("inkling2 attn tf_ink2_prep sliding (q, rel, k, v rows into the 3,072-slot ring)", mini); const why = "a head's sum of squares only scales it: a bf16 sum's error stays under the bf16 output's rounding"; return .{ .name = name, .accum = .f32, .depth = depthPrep, .ops = 16, .out = .bf16, .served = &prep_shapes, .nan = .{ .stated = nan_rule }, .sums = .{ .f16 = 100, .bf16 = 0, .why = why } }; } @@ -37,11 +37,12 @@ pub const Prep = struct { k: *const K.Kernels, global: bool, tau_off: bool = false, // control: the device runs with alpha 0 + m: M.Model = M.small, shape: c.Shape = undefined, fill: g.Fill = .random, ring: usize = 0, streams: usize = 1, - raw: [4][]u16 = .{ &.{}, &.{}, &.{}, &.{} }, // q [rows][24][128], k, v [rows][4][128], rel [rows][24][16] + raw: [4][]u16 = .{ &.{}, &.{}, &.{}, &.{} }, // q [rows][24][128], k, v [rows][kv][128], rel [rows][24][16] scales: [2][]u16 = .{ &.{}, &.{} }, // q_scale [24][128], rel_scale [24][16] pos: []usize = &.{}, stream: []usize = &.{}, @@ -79,8 +80,8 @@ pub const Prep = struct { } pub fn kernel(self: *Prep) g.Kernel { - var s = prepSpec(self.global); - if (self.tau_off) s.name = "control: inkling2 attn tf_ink2_prep global rows without tau"; + var s = prepSpec(self.global, self.m.mini); + if (self.tau_off) s.name = M.named("control: inkling2 attn tf_ink2_prep global rows without tau", self.m.mini); return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.tau_off) .shapes else null }; } @@ -88,7 +89,7 @@ pub const Prep = struct { fn sizes(self: *const Prep) [4]usize { const rows = self.shape.rows; - const cache = self.streams * kv * self.ring * D; + const cache = self.streams * self.m.kv * self.ring * D; return .{ rows * heads * D, rows * heads * R, cache, cache }; } @@ -106,6 +107,7 @@ pub const Prep = struct { self.fill = fill; const a = self.rig.gpu.gpa; const rows = shape.rows; + const kv = self.m.kv; self.ring = if (self.global) 4096 else K.Layer.sliding(1024, 2048).ring; self.streams = if (rows >= 2 and rows <= 128) 2 else 1; const n1 = if (self.streams == 2) rows / 2 else 0; @@ -159,9 +161,9 @@ pub const Prep = struct { const sz = self.sizes(); try self.rig.zero(self.out[2], sz[2] * 2); // slots no row writes stay 0, so a stray write shows try self.rig.zero(self.out[3], sz[3] * 2); - const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = self.dev[0], .seg_of = self.dev[1], .segs = self.dev[2], .tiles = 0, .n_tiles = 0, .last_pos = @intCast(self.shape.k - 1) }; + const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = @intCast(self.m.kv), .pos = self.dev[0], .seg_of = self.dev[1], .segs = self.dev[2], .tiles = 0, .n_tiles = 0, .last_pos = @intCast(self.shape.k - 1) }; const l: K.Layer = .{ .window = if (self.global) 0 else 1024, .ring = @intCast(self.ring), .chunk = 0, .tau = self.global }; - const cfg: K.Prep = .{ .qk_clip = @floatCast(ref.qk_clip), .rel_clip = @floatCast(ref.rel_clip), .floor = @floatCast(ref.floor_pos), .alpha = if (self.tau_off) @as(f32, 0) else @as(f32, @floatCast(ref.alpha)), .eps = @floatCast(ref.eps) }; + const cfg: K.Prep = .{ .qk_clip = @floatCast(ref.qk_clip), .rel_clip = @floatCast(ref.rel_clip), .floor = @floatCast(self.m.floor), .alpha = if (self.tau_off) @as(f32, 0) else @as(f32, @floatCast(ref.alpha)), .eps = @floatCast(ref.eps) }; try K.prep(self.k, self.rig.s, r, l, cfg, self.in[0..4].*, self.in[4..6].*, self.out[0], self.out[1], .{ .k = self.out[2], .v = self.out[3] }); try self.rig.s.synchronize(); } @@ -199,9 +201,10 @@ pub const Prep = struct { @memset(@field(self, f), 0); } const sz = self.sizes(); + const kv = self.m.kv; var x: [D]f64 = undefined; for (0..self.shape.rows) |r| { - const t: ?f64 = if (self.global) ref.tau(self.pos[r]) else null; + const t: ?f64 = if (self.global) ref.tauAt(self.pos[r], self.m.floor) else null; for (0..heads) |h| { for (x[0..D], 0..) |*v, i| v.* = ref.bf(self.raw[0][(r * heads + h) * D + i]) * ref.bf(self.scales[0][h * D + i]); self.head(x[0..D], ref.qk_clip, t, (r * heads + h) * D, acc, order); @@ -354,7 +357,7 @@ pub const Table = struct { } pub fn run(self: *Table) !void { - const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 0 }; + const r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = ref.kv, .pos = 0, .seg_of = 0, .segs = 0, .tiles = 0, .n_tiles = 0, .last_pos = 0 }; try K.relTable(self.k, self.rig.s, r, self.in[0], self.in[2], self.out); try self.rig.s.synchronize(); } diff --git a/zig/tests/cuda/contract_inkling2_attn_ref.zig b/zig/tests/cuda/contract_inkling2_attn_ref.zig index 6fde5cee62a..fda79c4c048 100644 --- a/zig/tests/cuda/contract_inkling2_attn_ref.zig +++ b/zig/tests/cuda/contract_inkling2_attn_ref.zig @@ -59,7 +59,12 @@ pub fn clipFactor(x: []const f64, thr: f64) f64 { /// The log-scaling factor of a global layer's q and rel at position `pos`: 1 + alpha ln(max((pos + 1) / floor, 1)). pub fn tau(pos: usize) f64 { - return 1 + alpha * @log(@max(@as(f64, @floatFromInt(pos + 1)) / floor_pos, 1)); + return tauAt(pos, floor_pos); +} + +/// tau at a model's own log_scaling_n_floor (Mini's is 8,192). +pub fn tauAt(pos: usize, floor: f64) f64 { + return 1 + alpha * @log(@max(@as(f64, @floatFromInt(pos + 1)) / floor, 1)); } /// One attention call's host inputs as the device holds them (bf16 bits) and where its rows sit. @@ -75,6 +80,11 @@ pub const Call = struct { ring: usize, window: usize, // 0: a global layer, every key from 0 exact: bool = false, // gate 4's rows: every p is 1 and every sum an integer below 2^24 + kv: usize = kv, // key heads a rank: Small's 4, Mini's 8 + + pub fn perKv(call: *const Call) usize { + return heads / call.kv; + } /// The fp32 sums' longest chain at a row: 4 mma (k16) a 64-key tile and its rescale, then the folds. fn depth(call: *const Call, pos: usize) f64 { @@ -92,7 +102,7 @@ pub const Call = struct { } fn keyRow(call: *const Call, which: []const u16, st: usize, kvh: usize, slot: usize) []const u16 { - return which[((st * kv + kvh) * call.ring + slot) * D ..][0..D]; + return which[((st * call.kv + kvh) * call.ring + slot) * D ..][0..D]; } }; @@ -141,7 +151,7 @@ fn sigmoid(g: f64) f64 { pub fn row(call: *const Call, r: usize, h: usize, ks: *Keys, want: []f64, tol: []f64) void { ks.gather(call, r, h); const st = call.stream[r]; - const kvh = h / group; + const kvh = h / call.perKv(); const pos = call.pos[r]; const qr = call.q[(r * heads + h) * D ..][0..D]; const z = bf(call.sink[r * heads + h]); @@ -190,7 +200,7 @@ pub fn row(call: *const Call, r: usize, h: usize, ks: *Keys, want: []f64, tol: [ /// Row r, head h with every sum in `acc` and `order` over the keys one by one (gate 4), output rounded to bf16. pub fn simulate(call: *const Call, r: usize, h: usize, acc: c.Accum, order: contract.gates.Order, p: []f64, col: []f64, out: []f64) void { const st = call.stream[r]; - const kvh = h / group; + const kvh = h / call.perKv(); const pos = call.pos[r]; const lo = if (call.window > 0) (pos + 1) -| call.window else 0; const n = pos + 1 - lo; diff --git a/zig/tests/cuda/contract_inkling2_attn_rows.zig b/zig/tests/cuda/contract_inkling2_attn_rows.zig index 71aaac07794..a371f54c6d5 100644 --- a/zig/tests/cuda/contract_inkling2_attn_rows.zig +++ b/zig/tests/cuda/contract_inkling2_attn_rows.zig @@ -5,6 +5,7 @@ const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_attn_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const contract = core.contract; const c = contract.spec; @@ -12,7 +13,6 @@ const g = contract.gates; const K = ink.kernels; const D = ref.D; const heads = ref.heads; -const kv = ref.kv; const n_out = heads * D; const global_ring = 4096; // global keys to 1M wrap a 4,096-slot ring (key p in slot p % ring): no 2 GiB cache needed @@ -22,7 +22,8 @@ pub const Path = enum { sliding, fold, split, prompt }; /// A control's planted fault, through the device's inputs only: the served kernels run as they are. pub const Plant = enum { none, late_bias, no_sink, q_ulp }; -pub const fold_name = "inkling2 attn tf_ink2_attn_fold + tf_ink2_merge (global layers, 16,384-key chunks)"; +const fold_base = "inkling2 attn tf_ink2_attn_fold + tf_ink2_merge (global layers, 16,384-key chunks)"; +pub const fold_name = fold_base; /// Unused beside `bounds`: the reference derives each output's allowance from the device's own steps. fn depth(_: c.Shape) usize { @@ -34,33 +35,33 @@ const fold_shapes = [_]c.Shape{ .{ .rows = 16, .n = n_out, .k = 20000 }, .{ .row const split_shapes = [_]c.Shape{ .{ .rows = 16, .n = n_out, .k = 20000 }, .{ .rows = 1, .n = n_out, .k = 1048576 }, .{ .rows = 8, .n = n_out, .k = 1048576 }, .{ .rows = 64, .n = n_out, .k = 70000 }, .{ .rows = 33, .n = n_out, .k = 1030 } }; const prompt_shapes = [_]c.Shape{ .{ .rows = 130, .n = n_out, .k = 20000 }, .{ .rows = 1, .n = n_out, .k = 1048576 }, .{ .rows = 2048, .n = n_out, .k = 2048 }, .{ .rows = 2048, .n = n_out, .k = 18432 }, .{ .rows = 256, .n = n_out, .k = 1048576 } }; -/// rows x 24 heads x 128 outputs; k: the first stream's context (its last row's position + 1). -pub fn spec(path: Path) c.Spec { +/// rows x 24 heads x 128 outputs; k: the first stream's context (Mini: same shapes, 8 key heads in the inputs). +pub fn spec(path: Path, mini: bool) c.Spec { const no: c.Tile = .{}; - const rows32: c.Tile = .{ .size = 32 }; // 192 (row, head) pairs: three 64-pair tiles + const rows32: c.Tile = .{ .size = if (mini) 64 else 32 }; // 192 (row, head) pairs: three 64-pair tiles const s: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 12, .out = .bf16, .served = &fold_shapes }; var x = s; switch (path) { .sliding => { - x.name = "inkling2 attn tf_ink2_attn + tf_ink2_merge (sliding layers: window 1,024, 256-key chunks)"; + x.name = M.named("inkling2 attn tf_ink2_attn + tf_ink2_merge (sliding layers: window 1,024, 256-key chunks)", mini); x.served = &sliding_shapes; x.tiles = .{ rows32, no, .{ .size = 1024 } }; }, .fold => { - x.name = fold_name; + x.name = M.named(fold_base, mini); x.tiles = .{ rows32, no, .{ .size = 16384 } }; }, .split => { - x.name = "inkling2 attn tf_ink2_attn split + tf_ink2_merge (global layers, a block a 1,024-key sub-chunk)"; + x.name = M.named("inkling2 attn tf_ink2_attn split + tf_ink2_merge (global layers, a block a 1,024-key sub-chunk)", mini); x.served = &split_shapes; x.tiles = .{ rows32, no, .{ .size = 1024 } }; - x.replaces = fold_name; + x.replaces = M.named(fold_base, mini); }, .prompt => { - x.name = "inkling2 attn tf_ink2_attn_prompt + tf_ink2_merge (one stream's prompt rows, 128 pairs a block)"; + x.name = M.named("inkling2 attn tf_ink2_attn_prompt + tf_ink2_merge (one stream's prompt rows, 128 pairs a block)", mini); x.served = &prompt_shapes; - x.tiles = .{ .{ .size = 64 }, no, .{ .size = 16384 } }; - x.replaces = fold_name; + x.tiles = .{ .{ .size = if (mini) 128 else 64 }, no, .{ .size = 16384 } }; // 384 pairs: three blocks + x.replaces = M.named(fold_base, mini); }, } return x; @@ -79,6 +80,7 @@ pub const Attn = struct { k: *const K.Kernels, path: Path, plant: Plant = .none, + m: M.Model = M.small, shape: c.Shape = undefined, fill: g.Fill = .random, layer: K.Layer = undefined, @@ -117,12 +119,12 @@ pub const Attn = struct { } pub fn kernel(self: *Attn) g.Kernel { - var s = spec(self.path); + var s = spec(self.path, self.m.mini); s.name = switch (self.plant) { .none => s.name, - .late_bias => "control: inkling2 attn sliding rows read each distance's bias one distance late", - .no_sink => "control: inkling2 attn global fold rows merged without their sink", - .q_ulp => "control: inkling2 attn prompt rows with one q value a bf16 step up (bit equality must see it)", + .late_bias => M.named("control: inkling2 attn sliding rows read each distance's bias one distance late", self.m.mini), + .no_sink => M.named("control: inkling2 attn global fold rows merged without their sink", self.m.mini), + .q_ulp => M.named("control: inkling2 attn prompt rows with one q value a bf16 step up (bit equality must see it)", self.m.mini), }; return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.plant == .none) null else .shapes }; } @@ -134,7 +136,7 @@ pub const Attn = struct { } fn call(self: *const Attn) ref.Call { - return .{ .q = self.q, .k = self.kc, .v = self.vc, .tab = self.tab, .sink = self.sink, .gate = self.gate, .pos = self.pos, .stream = self.stream, .ring = self.layer.ring, .window = self.layer.window, .exact = self.fill == .stress }; + return .{ .q = self.q, .k = self.kc, .v = self.vc, .tab = self.tab, .sink = self.sink, .gate = self.gate, .pos = self.pos, .stream = self.stream, .ring = self.layer.ring, .window = self.layer.window, .exact = self.fill == .stress, .kv = self.m.kv }; } /// Two streams for decode windows (2..128 rows; the second at half the context), else one; prompt: one. @@ -153,7 +155,7 @@ pub const Attn = struct { const n1 = if (self.streams == 2) rows / 2 else 0; const n0 = rows - n1; const last1 = @max(n1, shape.k / 2); - const segs = [2]K.Seg{ .{ .row0 = 0, .n = @intCast(n0), .p0 = @intCast(shape.k - n0), .off = 0 }, .{ .row0 = @intCast(n0), .n = @intCast(n1), .p0 = @intCast(last1 - n1), .off = @intCast(ring * kv * D) } }; + const segs = [2]K.Seg{ .{ .row0 = 0, .n = @intCast(n0), .p0 = @intCast(shape.k - n0), .off = 0 }, .{ .row0 = @intCast(n0), .n = @intCast(n1), .p0 = @intCast(last1 - n1), .off = @intCast(ring * self.m.kv * D) } }; self.pos = try a.alloc(usize, rows); self.stream = try a.alloc(usize, rows); for (0..rows) |r| { @@ -165,9 +167,9 @@ pub const Attn = struct { const rng = prng.random(); try self.fillAll(rng, ring); if (fill == .nonfinite) self.plantNonfinite(ring); - const tiles = try a.alloc(K.Tile, K.tileCount(rows, ref.group) + 2); + const tiles = try a.alloc(K.Tile, K.tileCount(rows, @intCast(self.m.group())) + 2); defer a.free(tiles); - self.n_tiles = @intCast(try K.tiles(segs[0..self.streams], ref.group, tiles)); + self.n_tiles = @intCast(try K.tiles(segs[0..self.streams], @intCast(self.m.group()), tiles)); const pos32 = try a.alloc(i32, 2 * rows); defer a.free(pos32); for (0..rows) |r| { @@ -201,6 +203,7 @@ pub const Attn = struct { const rows = self.shape.rows; const stress = self.fill == .stress; self.q = try a.alloc(u16, rows * n_out); + const kv = self.m.kv; self.kc = try a.alloc(u16, self.streams * kv * ring * D); self.vc = try a.alloc(u16, self.kc.len); self.tab = try a.alloc(u16, rows * heads * ref.extent); @@ -300,7 +303,7 @@ pub const Attn = struct { /// kernels.attend as the forward calls it; `path` picks its branch through `streams` and the partial room. fn launch(self: *Attn, path: Path, q: u64, tab: u64, sink: u64, out: u64) !void { const d = self.dev; - var r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = kv, .pos = d.pos, .seg_of = d.seg_of, .segs = d.segs, .tiles = d.tiles, .n_tiles = self.n_tiles, .last_pos = @intCast(self.shape.k - 1), .streams = @intCast(self.streams) }; + var r: K.Rows = .{ .rows = @intCast(self.shape.rows), .heads = heads, .kv_heads = @intCast(self.m.kv), .pos = d.pos, .seg_of = d.seg_of, .segs = d.segs, .tiles = d.tiles, .n_tiles = self.n_tiles, .last_pos = @intCast(self.shape.k - 1), .streams = @intCast(self.streams) }; const stride = K.slotsFor(self.layer, self.shape.k); var slots: usize = 0; // no partial room for sub-chunks: global calls take the fold or the prompt kernel switch (path) { @@ -340,7 +343,7 @@ pub const Attn = struct { std.debug.assert(self.fill == .stress); const a = self.rig.gpu.gpa; const cl = self.call(); - try Pool.run(a, .{ .call = &cl, .want = out, .tol = &.{}, .sim = .{ .acc = acc, .order = order } }, self.shape.rows * kv); + try Pool.run(a, .{ .call = &cl, .want = out, .tol = &.{}, .sim = .{ .acc = acc, .order = order } }, self.shape.rows * self.m.kv); } }; @@ -365,11 +368,12 @@ const Pool = struct { var i = j.first; while (i < j.items) : (i += j.step) { if (pool.sim) |s| { + const kv = pool.call.kv; const r = i / kv; - const h0 = (i % kv) * ref.group; + const h0 = (i % kv) * pool.call.perKv(); const o = pool.want[(r * heads + h0) * D ..][0..D]; ref.simulate(pool.call, r, h0, s.acc, s.order, j.p, j.col, o); - for (1..ref.group) |e| @memcpy(pool.want[(r * heads + h0 + e) * D ..][0..D], o); + for (1..pool.call.perKv()) |e| @memcpy(pool.want[(r * heads + h0 + e) * D ..][0..D], o); } else { const at = i * D; ref.row(pool.call, i / heads, i % heads, j.ks, pool.want[at..][0..D], pool.tol[at..][0..D]); diff --git a/zig/tests/cuda/contract_inkling2_model.zig b/zig/tests/cuda/contract_inkling2_model.zig new file mode 100644 index 00000000000..c2d341aadbe --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_model.zig @@ -0,0 +1,57 @@ +//! Inkling 2's served geometries under the contract: Small at TP=2 (a rank's share) and Mini at one rank. + +/// What a rank's kernels see of a model: widths, heads, router, vocabulary rows, log-scaling floor. +pub const Model = struct { + mini: bool, + hidden: usize, + heads: usize, // query heads a rank + kv: usize, // key heads a rank + experts: usize, + top: usize, + ranks: usize, // the vocabulary's shares, one a rank + floor: f64, // log_scaling_n_floor + vocab: usize = 201_024, + real: usize = 200_058, // unpadded_vocab_size + + pub fn group(m: Model) usize { + return m.heads / m.kv; + } + + /// The k/v rows' width (key heads x 128): the k/v convs' channels. + pub fn kvWidth(m: Model) usize { + return m.kv * 128; + } + + /// The dynamic conv taps a row: 4 a key head (weight_proj's rows). + pub fn taps(m: Model) usize { + return m.kv * 4; + } + + /// A rank's vocabulary columns. + pub fn share(m: Model) usize { + return m.vocab / m.ranks; + } + + /// The last rank's real columns. + pub fn lastReal(m: Model) usize { + return m.real - (m.ranks - 1) * m.share(); + } +}; + +/// Small (config.json of Inkling-2-Small) at TP=2: hidden 4,608, 4 key heads and 24 query heads a rank, 384 experts. +pub const small: Model = .{ .mini = false, .hidden = 4608, .heads = 24, .kv = 4, .experts = 384, .top = 8, .ranks = 2, .floor = 128000 }; +/// Mini (config.json of Inkling-2-Mini) at one rank: hidden 2,304, 24 query and 8 key heads, 128 experts, top 8. +pub const mini: Model = .{ .mini = true, .hidden = 2304, .heads = 24, .kv = 8, .experts = 128, .top = 8, .ranks = 1, .floor = 8192 }; + +pub const suffix = " at Mini's shapes"; + +/// A registration's name: Small's unchanged (its seeds hash the name), Mini's with the suffix. +pub fn named(comptime base: []const u8, mini_: bool) []const u8 { + return if (mini_) base ++ suffix else base; +} + +/// Entry `i` of a comptime name table, Mini's with the suffix. +pub fn namedAt(comptime table: []const []const u8, i: usize, mini_: bool) []const u8 { + inline for (table, 0..) |n, j| if (i == j) return named(n, mini_); + unreachable; +} diff --git a/zig/tests/cuda/contract_inkling2_ops.zig b/zig/tests/cuda/contract_inkling2_ops.zig index 48cbc7606a8..c94e088aa60 100644 --- a/zig/tests/cuda/contract_inkling2_ops.zig +++ b/zig/tests/cuda/contract_inkling2_ops.zig @@ -14,21 +14,22 @@ const G = ref.Gated; const K = ref.Checked; const groups = .{ "embeds", "mixes", "dots", "topks", "gateups", "convs", "rewinds", "caps", "tails", "top1s", "races", "tobfs", "words" }; +/// Small's registrations, then Mini's of every kernel but the EXL3 epilogues (gateup, prompt tail) and put_words. pub const Set = struct { k: ref.Kernels = undefined, loaded: bool = false, - mixes: [7]G(mix.Mix) = undefined, - embeds: [2]G(rows.Embed) = undefined, - dots: [6]G(rows.Rowdot) = undefined, - caps: [2]G(rows.Softcap) = undefined, - topks: [2]K(route.Topk) = undefined, + mixes: [14]G(mix.Mix) = undefined, + embeds: [4]G(rows.Embed) = undefined, + dots: [12]G(rows.Rowdot) = undefined, + caps: [4]G(rows.Softcap) = undefined, + topks: [4]K(route.Topk) = undefined, gateups: [2]G(route.Gateup) = undefined, tails: [3]G(route.Tail) = undefined, - convs: [8]G(conv.Conv) = undefined, - rewinds: [2]K(conv.Rewind) = undefined, - top1s: [2]K(pick.Top1) = undefined, - races: [2]K(pick.Race) = undefined, - tobfs: [2]K(pick.Tobf) = undefined, + convs: [16]G(conv.Conv) = undefined, + rewinds: [4]K(conv.Rewind) = undefined, + top1s: [4]K(pick.Top1) = undefined, + races: [4]K(pick.Race) = undefined, + tobfs: [4]K(pick.Tobf) = undefined, words: [2]K(pick.Words) = undefined, /// Every registration, each control after the kernel it breaks, appended to `list`. @@ -38,20 +39,29 @@ pub const Set = struct { const k = &set.k; const rig: @import("contract_rig.zig").Rig = .{ .gpu = gpu, .s = s }; const forms = [_]mix.Form{ .attn, .mlp, .first, .attn, .mlp, .first, .mlp }; - for (&set.mixes, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .form = f, .narrow = i >= 3 and i < 6, .fault = if (i == 6) .short else .none } }; - for (&set.embeds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .shifted = i == 1 } }; + for (&set.mixes, 0..) |*x, j| { + const i = j % 7; + x.* = .{ .rig = rig, .k = .{ .kern = k, .form = forms[i], .narrow = i >= 3 and i < 6, .fault = if (i == 6) .short else .none, .mini = j >= 7 } }; + } + for (&set.embeds, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .shifted = j % 2 == 1, .mini = j >= 2 } }; const dots = [_]rows.Dot{ .router, .sink, .taps, .router, .taps, .router }; - for (&set.dots, dots, 0..) |*x, d, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .dot = d, .tiles = i == 3 or i == 4, .short = i == 5 } }; - for (&set.caps, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .wrong = i == 1 } }; - for (&set.topks, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .unbiased = i == 1 } }; + for (&set.dots, 0..) |*x, j| { + const i = j % 6; + x.* = .{ .rig = rig, .k = .{ .kern = k, .dot = dots[i], .tiles = i == 3 or i == 4, .short = i == 5, .mini = j >= 6 } }; + } + for (&set.caps, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .wrong = j % 2 == 1, .mini = j >= 2 } }; + for (&set.topks, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .unbiased = j % 2 == 1, .mini = j >= 2 } }; for (&set.gateups, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .swapped = i == 1 } }; for (&set.tails, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .f32_out = i == 1, .shifted = i == 2 } }; const cf = [_]conv.Form{ .kv_static, .kv_dynamic, .attn, .attn_boundary, .mlp, .kv_static, .attn, .kv_static }; - for (&set.convs, cf, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .form = f, .view = if (i == 5 or i == 6) .state else .out, .fault = if (i == 7) .one_slot else .none } }; - for (&set.rewinds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .long = i == 1 } }; - for (&set.top1s, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } }; - for (&set.races, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .late = i == 1 } }; - for (&set.tobfs, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .unpadded = i == 1 } }; + for (&set.convs, 0..) |*x, j| { + const i = j % 8; + x.* = .{ .rig = rig, .k = .{ .kern = k, .form = cf[i], .view = if (i == 5 or i == 6) .state else .out, .fault = if (i == 7) .one_slot else .none, .mini = j >= 8 } }; + } + for (&set.rewinds, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .long = j % 2 == 1, .mini = j >= 2 } }; + for (&set.top1s, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = j % 2 == 1, .mini = j >= 2 } }; + for (&set.races, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .late = j % 2 == 1, .mini = j >= 2 } }; + for (&set.tobfs, 0..) |*x, j| x.* = .{ .rig = rig, .k = .{ .kern = k, .unpadded = j % 2 == 1, .mini = j >= 2 } }; for (&set.words, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } }; inline for (groups) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); } diff --git a/zig/tests/cuda/contract_inkling2_ops_conv.zig b/zig/tests/cuda/contract_inkling2_ops_conv.zig index 15cb1e5f318..2599d8d469b 100644 --- a/zig/tests/cuda/contract_inkling2_ops_conv.zig +++ b/zig/tests/cuda/contract_inkling2_ops_conv.zig @@ -3,6 +3,7 @@ const std = @import("std"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; @@ -20,12 +21,22 @@ pub const View = enum { out, state }; /// The served kernel, or the control: every stream reading and writing slot 0's state. pub const Fault = enum { none, one_slot }; -fn width(f: Form) usize { - return if (f == .kv_static or f == .kv_dynamic) ref.kv_width else ref.hidden; +fn model(mini: bool) M.Model { + return if (mini) M.mini else M.small; } -fn parts(f: Form) usize { - return if (f == .attn or f == .attn_boundary or f == .mlp) 2 else 1; +fn width(f: Form, mini: bool) usize { + return if (f == .kv_static or f == .kv_dynamic) model(mini).kvWidth() else model(mini).hidden; +} + +/// A residual site's input: o_proj's or the experts' fp32 sums, rounded to bf16 once summed over the ranks. +fn residual(f: Form) bool { + return f == .attn or f == .attn_boundary or f == .mlp; +} + +/// Rank partials of a site's input: Small's two at TP=2, Mini's one rank its own. +fn parts(f: Form, mini: bool) usize { + return if (residual(f)) model(mini).ranks else 1; } fn mode(f: Form) i32 { @@ -49,16 +60,27 @@ const names = [5][2][]const u8{ .{ "inkling2 ops tf_ink2_conv MLP site (rank partials, bf16(resid + bf16(y)))", "" }, }; +/// Mini at one rank: its residual sites take one fp32 input, rounded to bf16. +const mini_names = [5][2][]const u8{ + names[0], + names[1], + .{ "inkling2 ops tf_ink2_conv attention site (one rank, base + bf16(y))", "inkling2 ops tf_ink2_conv attention site, states and kept inputs" }, + names[3], + .{ "inkling2 ops tf_ink2_conv MLP site (one rank, bf16(resid + bf16(y)))", "" }, +}; + fn servedAt(comptime C: usize) []const c.Shape { return &.{ .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 4 }, .{ .rows = 128, .n = C, .k = 8 }, .{ .rows = 8, .n = C, .k = 8 }, .{ .rows = 2048, .n = C, .k = 1 } }; } /// Rows of the call x the site's width x streams (each its rows, its state slot): decode, windows, prompt chunks. -pub fn convSpec(f: Form, v: View, fault: Fault) c.Spec { - const served = if (width(f) == ref.kv_width) servedAt(ref.kv_width) else servedAt(ref.hidden); +pub fn convSpec(f: Form, v: View, fault: Fault, mini: bool) c.Spec { + const kv_site = f == .kv_static or f == .kv_dynamic; + const served = if (mini) (if (kv_site) servedAt(M.mini.kvWidth()) else servedAt(M.mini.hidden)) else if (kv_site) servedAt(M.small.kvWidth()) else servedAt(M.small.hidden); + const at = @as(usize, @backingInt(f)) * 2 + @backingInt(v); var s: c.Spec = .{ - .name = names[@backingInt(f)][@backingInt(v)], - .accum = if (v == .state and parts(f) == 1) .none else .f32, // a plain site keeps its inputs: no sums + .name = if (mini) M.namedAt(&flat(mini_names), at, true) else names[@backingInt(f)][@backingInt(v)], + .accum = if (v == .state and parts(f, mini) == 1) .none else .f32, // a plain site keeps its inputs: no sums .depth = depth, .out = if (v == .out and mode(f) != 1) .bf16 else .f32, .in_place = v == .state, @@ -66,19 +88,24 @@ pub fn convSpec(f: Form, v: View, fault: Fault) c.Spec { .served = served, }; if (fault == .one_slot) { - s.name = "control: inkling2 ops tf_ink2_conv k/v static taps, every stream on slot 0's state"; + s.name = M.named("control: inkling2 ops tf_ink2_conv k/v static taps, every stream on slot 0's state", mini); s.served = served[2..4]; s.tiles = .{ .{}, .{}, .{} }; } return s; } +fn flat(t: [5][2][]const u8) [10][]const u8 { + return t[0] ++ t[1] ++ t[2] ++ t[3] ++ t[4]; +} + /// One conv launch over `k` streams' rows: inputs uploaded, the states restored before every launch. pub const Conv = struct { kern: *const ops.Kernels, form: Form, view: View = .out, fault: Fault = .none, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, // [parts][rows][C] w: []u16 = &.{}, // static [C][4], dynamic [4][C] @@ -93,7 +120,7 @@ pub const Conv = struct { pub const sums = {}; pub fn spec(self: *const Conv) c.Spec { - return convSpec(self.form, self.view, self.fault); + return convSpec(self.form, self.view, self.fault, self.mini); } pub fn control(self: *const Conv) ?g.Gate { @@ -107,18 +134,22 @@ pub const Conv = struct { } } - const heads = 4; + /// The dynamic taps' heads: a rank's key heads. + fn dynHeads(self: *const Conv) usize { + return model(self.mini).kv; + } /// Values in [-2, 2); stress: products near 2^16 adding to 2^18 (fp16 overflows), partials near 2^17 cancelling. pub fn prepare(self: *Conv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - const C = width(self.form); + const C = width(self.form, self.mini); + const heads = self.dynHeads(); if (shape.rows == 0 or shape.n != C or shape.k == 0) return false; self.free(a); self.shape = shape; const rows = shape.rows; - const np = parts(self.form); + const np = parts(self.form, self.mini); const stress = fill == .stress; - const round = np == 2; + const round = residual(self.form); self.x = try a.alloc(f32, np * rows * C); for (0..rows * C) |i| { const v = if (stress) ref.int(rng, -256, 256) else rng.float(f32) * 4 - 2; @@ -176,7 +207,7 @@ pub const Conv = struct { .state_stride = @intCast(3 * C), .parts = @intCast(np), .round_in = @intFromBool(round), - .heads = heads, + .heads = @intCast(heads), .c = @intCast(C), .rows = @intCast(rows), .mode = mode(self.form), @@ -192,21 +223,21 @@ pub const Conv = struct { } pub fn count(self: *const Conv) usize { - const C = width(self.form); + const C = width(self.form, self.mini); return if (self.view == .out) self.shape.rows * C else self.state.len + self.shape.rows * C; } /// Row t's input at column col: the ranks' partials added in order, rounded to bf16 at the residual sites. fn input(self: *const Conv, s: Sums, t: usize, col: usize) Iv { - const C = width(self.form); + const C = width(self.form, self.mini); const rows = self.shape.rows; var x = Iv.of(self.x[t * C + col]); - if (parts(self.form) == 2) x = step(s, x, Iv.of(self.x[(rows + t) * C + col]), false).bf(); + if (parts(self.form, self.mini) == 2) x = step(s, x, Iv.of(self.x[(rows + t) * C + col]), false).bf() else if (residual(self.form)) x = x.bf(); return x; } pub fn solve(self: *const Conv, _: std.mem.Allocator, s: Sums, out: []Iv) !void { - const C = width(self.form); + const C = width(self.form, self.mini); const hist = out[if (self.view == .state) self.state.len else 0..]; if (self.view == .state) for (out[0..self.state.len], self.state) |*o, v| { o.* = Iv.of(v); @@ -228,15 +259,16 @@ pub const Conv = struct { } fn tap(self: *const Conv, k: usize, col: usize) Iv { - const C = width(self.form); + const C = width(self.form, self.mini); return Iv.of(ref.bf(self.w[if (self.form == .kv_dynamic) k * C + col else col * 4 + k])); } /// The site's output at row t from its three prior inputs h (oldest first) and x. fn y(self: *const Conv, s: Sums, t: usize, col: usize, h: [3]Iv, x: Iv) Iv { - const C = width(self.form); + const C = width(self.form, self.mini); var v: Iv = undefined; if (self.form == .kv_dynamic) { + const heads = self.dynHeads(); const d = self.dyn[(t * heads + col / (C / heads)) * 4 ..][0..4]; var w: [4]Iv = undefined; for (&w, 0..) |*wk, k| wk.* = self.tap(k, col).add(Iv.of(d[k])); @@ -259,10 +291,14 @@ pub const Conv = struct { } }; -/// Kept rows x the widest site x the slot's first row in hist: four sites, two 512 wide and two 4,608. -pub fn rewindSpec(long: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 3, .n = ref.hidden, .k = 0 }, .{ .rows = 1, .n = ref.hidden, .k = 5 }, .{ .rows = 2, .n = ref.hidden, .k = 0 }, .{ .rows = 4, .n = ref.hidden, .k = 3 }, .{ .rows = 17, .n = ref.hidden, .k = 5 }, .{ .rows = 128, .n = ref.hidden, .k = 0 } }; - const name = if (long) "control: inkling2 ops tf_ink2_conv_rewind keeping one row more" else "inkling2 ops tf_ink2_conv_rewind (a slot's states from its backup and kept rows)"; +fn rewindServed(comptime C: usize) []const c.Shape { + return &.{ .{ .rows = 3, .n = C, .k = 0 }, .{ .rows = 1, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 0 }, .{ .rows = 4, .n = C, .k = 3 }, .{ .rows = 17, .n = C, .k = 5 }, .{ .rows = 128, .n = C, .k = 0 } }; +} + +/// Kept rows x the widest site x the slot's first row in hist: four sites, 512 and 4,608 wide (Mini: 1,024, 2,304). +pub fn rewindSpec(long: bool, mini: bool) c.Spec { + const served = if (mini) rewindServed(M.mini.hidden) else rewindServed(M.small.hidden); + const name = if (long) M.named("control: inkling2 ops tf_ink2_conv_rewind keeping one row more", mini) else M.named("inkling2 ops tf_ink2_conv_rewind (a slot's states from its backup and kept rows)", mini); return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .in_place = true, .nan = .{ .stated = "a move: every bit copied, NaN payloads too" }, .served = if (long) served[0..2] else served }; } @@ -270,6 +306,7 @@ pub fn rewindSpec(long: bool) c.Spec { pub const Rewind = struct { kern: *const ops.Kernels, long: bool = false, + mini: bool = false, shape: c.Shape = undefined, hist: []f32 = &.{}, backup: []f32 = &.{}, @@ -277,12 +314,16 @@ pub const Rewind = struct { dev: [3]u64 = @splat(0), out: [4]u64 = @splat(0), - const widths = [4]usize{ ref.kv_width, ref.kv_width, ref.hidden, ref.hidden }; + /// The four sites' widths: k, v, attention's, the MLP's. + fn widths(self: *const Rewind) [4]usize { + const m = model(self.mini); + return .{ m.kvWidth(), m.kvWidth(), m.hidden, m.hidden }; + } const slots = 3; const slot = 1; pub fn spec(self: *const Rewind) c.Spec { - return rewindSpec(self.long); + return rewindSpec(self.long, self.mini); } pub fn control(self: *const Rewind) ?g.Gate { @@ -303,12 +344,13 @@ pub const Rewind = struct { } pub fn prepare(self: *Rewind, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != ref.hidden) return false; + if (shape.rows == 0 or shape.n != model(self.mini).hidden) return false; self.free(a); self.shape = shape; const hr = self.histRows(); var total: usize = 0; - for (widths) |w| total += w; + const ws = self.widths(); + for (ws) |w| total += w; self.hist = try ref.f32s(a, rng, hr * total, -4, 4); self.backup = try ref.f32s(a, rng, 3 * total, -4, 4); if (fill == .nonfinite) { @@ -318,7 +360,7 @@ pub const Rewind = struct { var sites: [4]ops.RewindSite = undefined; var h_off: usize = 0; var b_off: usize = 0; - for (&sites, &self.states, &self.out, widths) |*st, *s, *o, w| { + for (&sites, &self.states, &self.out, ws) |*st, *s, *o, w| { s.* = try ref.f32s(a, rng, slots * 3 * w, -4, 4); o.* = try rig.output(s.len * 4); st.* = .{ .state = o.*, .hist = @intCast(h_off * 4), .backup = @intCast(b_off * 4), .c = @intCast(w) }; @@ -332,7 +374,7 @@ pub const Rewind = struct { pub fn run(self: *Rewind, rig: *rig_.Rig) !void { for (self.states, self.out) |s, o| try ref.restore(rig, o, std.mem.sliceAsBytes(s)); const n = self.shape.rows + @intFromBool(self.long); - try ops.rewind(self.kern, rig.s, self.dev[0], 4, ref.hidden, self.dev[1], self.dev[2], slot, self.shape.k, n); + try ops.rewind(self.kern, rig.s, self.dev[0], 4, model(self.mini).hidden, self.dev[1], self.dev[2], slot, self.shape.k, n); } pub fn count(self: *const Rewind) usize { @@ -348,7 +390,7 @@ pub const Rewind = struct { var at: usize = 0; var h_off: usize = 0; var b_off: usize = 0; - for (self.states, widths, 0..) |s, w, site| { + for (self.states, self.widths(), 0..) |s, w, site| { for (s, 0..) |old, e| { const sl = e / (3 * w); const k = e / w % 3; diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index 22fc073bf40..4672fef3f6c 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -4,13 +4,13 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const C = ref.hidden; /// forward.zig's mixes: attention's (q, k and v queries, bf16 stream), the MLP's (fp32 residual), layer 0's (no query). pub const Form = enum { attn, mlp, first }; @@ -23,22 +23,33 @@ fn nq(f: Form) usize { } /// A thread's columns 512 apart, then the block's two shuffle stages. -fn depth(_: c.Shape) usize { - return ref.blockDepth(C, 512); +fn depth(s: c.Shape) usize { + return ref.blockDepth(s.n, 512); +} + +/// A width's served calls: wide, decode, and layer 0's of each (comptime arrays: a spec outlives the call). +fn servedAt(comptime C: usize) [4][]const c.Shape { + return .{ + &.{ .{ .rows = 17, .n = C, .k = 9 }, .{ .rows = 64, .n = C, .k = 5 }, .{ .rows = 2048, .n = C, .k = 9 }, .{ .rows = 128, .n = C, .k = 1 }, .{ .rows = 32, .n = C, .k = 2 } }, + &.{ .{ .rows = 1, .n = C, .k = 9 }, .{ .rows = 16, .n = C, .k = 9 }, .{ .rows = 8, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 1 }, .{ .rows = 4, .n = C, .k = 2 } }, + &.{ .{ .rows = 17, .n = C, .k = 1 }, .{ .rows = 2048, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 1 } }, + &.{ .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 5, .n = C, .k = 1 } }, + }; } /// Rows x hidden x blocks (completed blocks + the partial): mix_rows takes calls of more than 16 rows, mix the rest. -pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { - const wide = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 9 }, .{ .rows = 64, .n = C, .k = 5 }, .{ .rows = 2048, .n = C, .k = 9 }, .{ .rows = 128, .n = C, .k = 1 }, .{ .rows = 32, .n = C, .k = 2 } }; - const decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 9 }, .{ .rows = 16, .n = C, .k = 9 }, .{ .rows = 8, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 1 }, .{ .rows = 4, .n = C, .k = 2 } }; - const one = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 1 }, .{ .rows = 2048, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 1 } }; - const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 5, .n = C, .k = 1 } }; +pub fn mixSpec(f: Form, narrow: bool, fault: Fault, mini: bool) c.Spec { + const all = if (mini) servedAt(M.mini.hidden) else servedAt(M.small.hidden); + const wide = all[0]; + const decode = all[1]; + const one = all[2]; + const one_decode = all[3]; const names = [2][3][]const u8{ .{ "inkling2 ops tf_ink2_mix_rows attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix_rows MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix_rows layer 0 (no query)" }, .{ "inkling2 ops tf_ink2_mix attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix layer 0 (no query)" }, }; var s: c.Spec = .{ - .name = names[@intFromBool(narrow)][@backingInt(f)], + .name = M.namedAt(&(names[0] ++ names[1]), @as(usize, @intFromBool(narrow)) * 3 + @backingInt(f), mini), .accum = .f32, .depth = depth, .out = .bf16, @@ -46,7 +57,7 @@ pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { }; if (narrow) s.replaces = "tf_ink2_mix_rows"; if (fault == .short) { - s.name = "control: inkling2 ops tf_ink2_mix_rows MLP told one completed block fewer"; + s.name = M.named("control: inkling2 ops tf_ink2_mix_rows MLP told one completed block fewer", mini); s.served = wide[0..2]; } return s; @@ -58,6 +69,7 @@ pub const Mix = struct { form: Form, narrow: bool = false, fault: Fault = .none, + mini: bool = false, shape: c.Shape = undefined, blocks: []u16 = &.{}, // [n_blocks][rows][C] part: []f32 = &.{}, // [rows][C], bf16 values when the form's partial is bf16 @@ -69,7 +81,7 @@ pub const Mix = struct { pub const sums = {}; pub fn spec(self: *const Mix) c.Spec { - return mixSpec(self.form, self.narrow, self.fault); + return mixSpec(self.form, self.narrow, self.fault, self.mini); } pub fn control(self: *const Mix) ?g.Gate { @@ -87,12 +99,17 @@ pub const Mix = struct { self.norm = &.{}; } + fn width(self: *const Mix) usize { + return if (self.mini) M.mini.hidden else M.small.hidden; + } + fn bf16Part(self: *const Mix) bool { return self.form != .mlp; } /// Values in [-2, 2) with one in 61 eight times larger, queries in [-1, 1); stress: integers in [-16, 16]. pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const C = self.width(); if (shape.rows == 0 or shape.n != C or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; self.free(a); self.shape = shape; @@ -116,7 +133,7 @@ pub const Mix = struct { if (nb == 0) ref.plant(f32, self.part, 1, C, ref.asF32); if (rows > 1) ref.plant(f32, self.part[C..], @min(rows - 1, 3), C, ref.asF32); } - var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = C, .eps = ref.eps }; + var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = @intCast(C), .eps = ref.eps }; for (0..nb) |j| m.blocks[j] = try ref.input(rig, self.blocks[j * rows * C ..][0 .. rows * C]); if (self.bf16Part()) { const h = try a.alloc(u16, rows * C); @@ -153,11 +170,12 @@ pub const Mix = struct { } pub fn count(self: *const Mix) usize { - return nq(self.form) * self.shape.rows * C; + return nq(self.form) * self.shape.rows * self.shape.n; } fn at(self: *const Mix, j: usize, r: usize, col: usize) f64 { const nb = self.shape.k - 1; + const C = self.shape.n; return if (j < nb) ref.bf(self.blocks[(j * self.shape.rows + r) * C + col]) else self.part[r * C + col]; } @@ -166,6 +184,7 @@ pub const Mix = struct { const rows = self.shape.rows; const n = self.shape.k; const q = nq(self.form); + const C = self.shape.n; const terms = try a.alloc(Iv, C); defer a.free(terms); const scratch = try a.alloc(f64, C); @@ -173,7 +192,7 @@ pub const Mix = struct { const h = try a.alloc(Iv, q * C); defer a.free(h); const d = depth(self.shape); - const root = Iv.of(C).rsqrt(); + const root = Iv.of(@floatFromInt(C)).rsqrt(); for (0..rows) |r| { var rr: [ops.max_blocks + 1]Iv = undefined; var w: [ops.max_queries][ops.max_blocks + 1]Iv = undefined; diff --git a/zig/tests/cuda/contract_inkling2_ops_pick.zig b/zig/tests/cuda/contract_inkling2_ops_pick.zig index 28564cb375c..fdb634b51ca 100644 --- a/zig/tests/cuda/contract_inkling2_ops_pick.zig +++ b/zig/tests/cuda/contract_inkling2_ops_pick.zig @@ -3,6 +3,7 @@ const std = @import("std"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; @@ -11,23 +12,31 @@ const ops = ref.ops; /// A rank's view of the head (shape.k: 1 rank 0, 2 rank 1): its first id, its rows' stride, the real ids it holds. const Rank = struct { base: usize, stride: usize, n: usize }; -fn rank(s: c.Shape) Rank { - return if (s.k == 2) .{ .base = ref.share, .stride = ref.share, .n = s.n } else .{ .base = 0, .stride = ref.share, .n = s.n }; +fn model(mini: bool) M.Model { + return if (mini) M.mini else M.small; +} + +/// Mini at one rank: rows of the whole 201,024, its 200,058 real ids from 0. +fn rank(s: c.Shape, mini: bool) Rank { + const share = model(mini).share(); + return if (s.k == 2) .{ .base = share, .stride = share, .n = s.n } else .{ .base = 0, .stride = share, .n = s.n }; } const ranks = [_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 }, .{ .rows = 16, .n = ref.share1_real, .k = 2 }, .{ .rows = 1, .n = ref.share1_real, .k = 2 } }; +const mini_rows = [_]c.Shape{ .{ .rows = 16, .n = M.mini.real, .k = 1 }, .{ .rows = 1, .n = M.mini.real, .k = 1 }, .{ .rows = 128, .n = M.mini.real, .k = 1 } }; const top_rule = "the largest value and its lowest id plus the rank's base; a NaN never picked, -inf picked when all else is NaN, a row of NaNs (-inf, base)"; /// Rows x a rank's real ids x the rank: greedy draws of a window's rows, the drafter's single row. -pub fn top1Spec(short: bool) c.Spec { - const name = if (short) "control: inkling2 ops tf_ink2_top1 one id short" else "inkling2 ops tf_ink2_top1 (greedy pick, fp32 logits)"; - return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = top_rule }, .served = if (short) ranks[0..2] else &ranks }; +pub fn top1Spec(short: bool, mini: bool) c.Spec { + const name = if (short) M.named("control: inkling2 ops tf_ink2_top1 one id short", mini) else M.named("inkling2 ops tf_ink2_top1 (greedy pick, fp32 logits)", mini); + const served: []const c.Shape = if (mini) &mini_rows else &ranks; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = top_rule }, .served = if (short) served[0..2] else served }; } /// Values on 1/8 steps of [-64, 64) and padding past the real ids at 1000: equal maxima, and a read past n shows. -fn logits(a: std.mem.Allocator, rng: std.Random, s: c.Shape, fill: g.Fill) ![]f32 { - const rk = rank(s); +fn logits(a: std.mem.Allocator, rng: std.Random, s: c.Shape, fill: g.Fill, mini: bool) ![]f32 { + const rk = rank(s, mini); const x = try a.alloc(f32, s.rows * rk.stride); for (x, 0..) |*v, i| v.* = if (i % rk.stride < rk.n) ref.int(rng, -512, 511) / 8 else 1000; if (fill != .nonfinite) { @@ -63,13 +72,14 @@ fn scan(row: []const f32) struct { v: f32, i: usize } { pub const Top1 = struct { kern: *const ops.Kernels, short: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, out: [2]u64 = @splat(0), pub fn spec(self: *const Top1) c.Spec { - return top1Spec(self.short); + return top1Spec(self.short, self.mini); } pub fn control(self: *const Top1) ?g.Gate { @@ -82,17 +92,17 @@ pub const Top1 = struct { } pub fn prepare(self: *Top1, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n < 4 or shape.n > ref.share) return false; + if (shape.rows == 0 or shape.n < 4 or shape.n > model(self.mini).share()) return false; self.free(a); self.shape = shape; - self.x = try logits(a, rng, shape, fill); + self.x = try logits(a, rng, shape, fill, self.mini); self.dev = try ref.input(rig, self.x); self.out = .{ try rig.output(shape.rows * 4), try rig.output(shape.rows * 4) }; return true; } pub fn run(self: *Top1, rig: *rig_.Rig) !void { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); try ops.top1(self.kern, rig.s, self.dev, self.shape.rows, rk.stride, rk.n - @intFromBool(self.short), rk.base, self.out[0], self.out[1]); } @@ -101,7 +111,7 @@ pub const Top1 = struct { } pub fn check(self: *const Top1, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); const rows = self.shape.rows; for (0..rows) |r| { const want = scan(self.x[r * rk.stride ..][0..rk.n]); @@ -121,9 +131,9 @@ const race_rule = "the largest bf16(x) / T + Gumbel(sample.cu's key at pos, id): "better beyond it; NaN never picked, the lowest +Inf first, a row of NaNs (-inf, base)"; /// One row a launch (the drafter's draw at a position) x a rank's real ids x the rank. -pub fn raceSpec(late: bool) c.Spec { - const name = if (late) "control: inkling2 ops tf_ink2_race1 keyed one position late" else "inkling2 ops tf_ink2_race1 (keyed Gumbel race, a launch a row)"; - const served = &[_]c.Shape{ .{ .rows = 4, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 2, .n = ref.share1_real, .k = 2 } }; +pub fn raceSpec(late: bool, mini: bool) c.Spec { + const name = if (late) M.named("control: inkling2 ops tf_ink2_race1 keyed one position late", mini) else M.named("inkling2 ops tf_ink2_race1 (keyed Gumbel race, a launch a row)", mini); + const served: []const c.Shape = if (mini) &.{ .{ .rows = 4, .n = M.mini.real, .k = 1 }, .{ .rows = 1, .n = M.mini.real, .k = 1 }, .{ .rows = 2, .n = M.mini.real, .k = 1 } } else &.{ .{ .rows = 4, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 2, .n = ref.share1_real, .k = 2 } }; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = race_rule }, .served = if (late) served[0..2] else served }; } @@ -149,13 +159,14 @@ fn uniform(pos: u32, id: u32) f32 { pub const Race = struct { kern: *const ops.Kernels, late: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, out: [2]u64 = @splat(0), pub fn spec(self: *const Race) c.Spec { - return raceSpec(self.late); + return raceSpec(self.late, self.mini); } pub fn control(self: *const Race) ?g.Gate { @@ -168,10 +179,10 @@ pub const Race = struct { } pub fn prepare(self: *Race, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n < 4 or shape.n > ref.share) return false; + if (shape.rows == 0 or shape.n < 4 or shape.n > model(self.mini).share()) return false; self.free(a); self.shape = shape; - self.x = try logits(a, rng, shape, fill); + self.x = try logits(a, rng, shape, fill, self.mini); for (self.x) |*v| if (std.math.isFinite(v.*)) { v.* /= 32; // logits within a few Gumbel widths, so the keys decide }; @@ -181,7 +192,7 @@ pub const Race = struct { } pub fn run(self: *Race, rig: *rig_.Rig) !void { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); for (0..self.shape.rows) |r| { const pos = pos0 + r + @intFromBool(self.late); try ops.race1(self.kern, rig.s, self.dev + r * rk.stride * 4, rk.n, rk.base, seed, inv_t, pos, self.out[0] + r * 4, self.out[1] + r * 4); @@ -201,7 +212,7 @@ pub const Race = struct { } pub fn check(self: *const Race, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const rk = rank(self.shape); + const rk = rank(self.shape, self.mini); const rows = self.shape.rows; for (0..rows) |r| { const row = self.x[r * rk.stride ..][0..rk.n]; @@ -229,10 +240,11 @@ pub const Race = struct { } }; -/// Rows x a rank's share x the rank: logits into the sampler's whole bf16 rows at the rank's columns. -pub fn tobfSpec(unpadded: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 2 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 2 } }; - const name = if (unpadded) "control: inkling2 ops tf_ink2_tobf rounding rank 1's padding ids" else "inkling2 ops tf_ink2_tobf (bf16 rows, padding ids -inf)"; +/// Rows x a rank's share x the rank: logits into the sampler's whole bf16 rows at the rank's columns (Mini: one row). +pub fn tobfSpec(unpadded: bool, mini: bool) c.Spec { + const V = M.mini.vocab; + const served: []const c.Shape = if (mini) &.{ .{ .rows = 16, .n = V, .k = 1 }, .{ .rows = 1, .n = V, .k = 1 }, .{ .rows = 128, .n = V, .k = 1 } } else &.{ .{ .rows = 16, .n = ref.share, .k = 2 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 2 } }; + const name = if (unpadded) (if (mini) M.named("control: inkling2 ops tf_ink2_tobf rounding the padding ids", true) else "control: inkling2 ops tf_ink2_tobf rounding rank 1's padding ids") else M.named("inkling2 ops tf_ink2_tobf (bf16 rows, padding ids -inf)", mini); return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = "a rounding: each value to bf16 at nearest even, NaN to NaN" }, .served = if (unpadded) served[0..1] else served }; } @@ -240,13 +252,14 @@ pub fn tobfSpec(unpadded: bool) c.Spec { pub const Tobf = struct { kern: *const ops.Kernels, unpadded: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, out: u64 = 0, pub fn spec(self: *const Tobf) c.Spec { - return tobfSpec(self.unpadded); + return tobfSpec(self.unpadded, self.mini); } pub fn control(self: *const Tobf) ?g.Gate { @@ -259,32 +272,40 @@ pub const Tobf = struct { } pub fn prepare(self: *Tobf, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != ref.share) return false; + if (shape.rows == 0 or shape.n != model(self.mini).share()) return false; self.free(a); self.shape = shape; self.x = try ref.f32s(a, rng, shape.rows * shape.n, -40, 40); if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); self.dev = try ref.input(rig, self.x); - self.out = try rig.output(shape.rows * 2 * ref.share * 2); + self.out = try rig.output(shape.rows * model(self.mini).vocab * 2); return true; } + /// The rank's first column, and its real ids (the last rank's stop at unpadded_vocab_size). + fn cols(self: *const Tobf) [2]usize { + const m = model(self.mini); + const col0: usize = if (self.shape.k == 2) m.share() else 0; + return .{ col0, if (self.shape.k == m.ranks) m.lastReal() else self.shape.n }; + } + pub fn run(self: *Tobf, rig: *rig_.Rig) !void { - const col0: usize = if (self.shape.k == 2) ref.share else 0; - const n = if (self.shape.k == 2 and !self.unpadded) ref.share1_real else self.shape.n; - try ops.tobf(self.kern, rig.s, self.dev, self.shape.rows, self.shape.n, n, self.out, 2 * ref.share, col0, self.shape.n); + const at = self.cols(); + const n = if (self.unpadded) self.shape.n else at[1]; + try ops.tobf(self.kern, rig.s, self.dev, self.shape.rows, self.shape.n, n, self.out, model(self.mini).vocab, at[0], self.shape.n); } pub fn count(self: *const Tobf) usize { - return self.shape.rows * 2 * ref.share * 2; + return self.shape.rows * model(self.mini).vocab * 2; } pub fn check(self: *const Tobf, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { const n = self.shape.n; - const col0: usize = if (self.shape.k == 2) ref.share else 0; - const real = if (self.shape.k == 2) ref.share1_real else n; - for (0..self.shape.rows) |r| for (0..2 * ref.share) |col| { - const have = std.mem.readInt(u16, got[2 * (r * 2 * ref.share + col) ..][0..2], .little); + const V = model(self.mini).vocab; + const col0 = self.cols()[0]; + const real = self.cols()[1]; + for (0..self.shape.rows) |r| for (0..V) |col| { + const have = std.mem.readInt(u16, got[2 * (r * V + col) ..][0..2], .little); const mine = col >= col0 and col < col0 + n; const i = col -% col0; const want: u16 = if (!mine) 0xffff else if (i < real) c.toBf16(self.x[r * n + i]) else 0xff80; diff --git a/zig/tests/cuda/contract_inkling2_ops_route.zig b/zig/tests/cuda/contract_inkling2_ops_route.zig index c17be9c5860..5d85776dd9f 100644 --- a/zig/tests/cuda/contract_inkling2_ops_route.zig +++ b/zig/tests/cuda/contract_inkling2_ops_route.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; @@ -12,17 +13,21 @@ const Sums = ref.Sums; const ops = ref.ops; const step = ref.step; -const experts = 384; -const top = 8; const route_scale: f32 = 8; const topk_rule = "the 8 largest score + bias, the lower id on ties, a NaN never picked, a pick's value then -inf; " ++ "weights score / (sum of the picks' scores + 1e-20) x 8 in fp32"; -/// Rows x experts x picks: every row of a call, a block each. -pub fn topkSpec(unbiased: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top } }; - const name = if (unbiased) "control: inkling2 ops tf_ink2_topk without the selection bias" else "inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)"; +fn topkServed(comptime m: M.Model) []const c.Shape { + const E = m.experts; + const top = m.top; + return &.{ .{ .rows = 16, .n = E, .k = top }, .{ .rows = 1, .n = E, .k = top }, .{ .rows = 128, .n = E, .k = top }, .{ .rows = 2048, .n = E, .k = top } }; +} + +/// Rows x experts x picks: every row of a call, a block each (Small: 384 experts, Mini: 128, both top 8). +pub fn topkSpec(unbiased: bool, mini: bool) c.Spec { + const served = if (mini) topkServed(M.mini) else topkServed(M.small); + const name = if (unbiased) M.named("control: inkling2 ops tf_ink2_topk without the selection bias", mini) else M.named("inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)", mini); return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = topk_rule }, .served = if (unbiased) served[0..2] else served }; } @@ -30,6 +35,7 @@ pub fn topkSpec(unbiased: bool) c.Spec { pub const Topk = struct { kern: *const ops.Kernels, unbiased: bool = false, + mini: bool = false, shape: c.Shape = undefined, scores: []f32 = &.{}, bias: []f32 = &.{}, @@ -37,7 +43,7 @@ pub const Topk = struct { out: [2]u64 = @splat(0), pub fn spec(self: *const Topk) c.Spec { - return topkSpec(self.unbiased); + return topkSpec(self.unbiased, self.mini); } pub fn control(self: *const Topk) ?g.Gate { diff --git a/zig/tests/cuda/contract_inkling2_ops_rows.zig b/zig/tests/cuda/contract_inkling2_ops_rows.zig index cb17ac6cbe0..87edd67fc67 100644 --- a/zig/tests/cuda/contract_inkling2_ops_rows.zig +++ b/zig/tests/cuda/contract_inkling2_ops_rows.zig @@ -4,13 +4,13 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const ref = @import("contract_inkling2_ops_ref.zig"); +const M = @import("contract_inkling2_model.zig"); const c = core.contract.spec; const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const C = ref.hidden; /// Rows of the fixture's table: ids are a bijection of the rows, so planted rows stay in their rows. const table_rows = 4096; @@ -19,17 +19,22 @@ fn embedDepth(s: c.Shape) usize { return ref.blockDepth(s.k, 256); } +fn embedServed(comptime C: usize) []const c.Shape { + return &.{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C } }; +} + /// Rows x hidden x hidden: a prompt chunk, a verify window, one decode row (the drafter's anchor embeds one too). -pub fn embedSpec(shifted: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C } }; - if (shifted) return .{ .name = "control: inkling2 ops tf_ink2_embed gathering the next row", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; - return .{ .name = "inkling2 ops tf_ink2_embed (embed_norm, rounded once)", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; +pub fn embedSpec(shifted: bool, mini: bool) c.Spec { + const served = if (mini) embedServed(M.mini.hidden) else embedServed(M.small.hidden); + if (shifted) return .{ .name = M.named("control: inkling2 ops tf_ink2_embed gathering the next row", mini), .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; + return .{ .name = M.named("inkling2 ops tf_ink2_embed (embed_norm, rounded once)", mini), .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; } /// out = bf16(w * (e * rsqrtf(mean(e^2) + eps))) of each id's embedding row. pub const Embed = struct { kern: *const ops.Kernels, shifted: bool = false, + mini: bool = false, shape: c.Shape = undefined, table: []u16 = &.{}, // [table_rows + 1][C]: the control reads one row on w: []u16 = &.{}, @@ -40,7 +45,7 @@ pub const Embed = struct { pub const sums = {}; pub fn spec(self: *const Embed) c.Spec { - return embedSpec(self.shifted); + return embedSpec(self.shifted, self.mini); } pub fn control(self: *const Embed) ?g.Gate { @@ -111,27 +116,40 @@ fn dotDepth(s: c.Shape) usize { return (s.k + 31) / 32 + 5; } -/// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. -pub fn dotSpec(d: Dot, tiles: bool, short: bool) c.Spec { +/// A model's row-dot calls, plain then tiled: router (experts), sinks (query heads), dynamic taps (4 a key head). +fn dotServed(comptime m: M.Model, d: Dot) [2][]const c.Shape { + const C = m.hidden; + const E = m.experts; + const H = m.heads; + const T = comptime m.taps(); const plain: []const c.Shape = switch (d) { // comptime arrays: a spec outlives this call - .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C } }, - .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C } }, - .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C } }, + .router => &.{ .{ .rows = 16, .n = E, .k = C }, .{ .rows = 1, .n = E, .k = C }, .{ .rows = 31, .n = E, .k = C }, .{ .rows = 7, .n = E, .k = C } }, + .sink => &.{ .{ .rows = 16, .n = H, .k = C }, .{ .rows = 1, .n = H, .k = C }, .{ .rows = 128, .n = H, .k = C }, .{ .rows = 2048, .n = H, .k = C } }, + .taps => &.{ .{ .rows = 16, .n = T, .k = C }, .{ .rows = 1, .n = T, .k = C }, .{ .rows = 31, .n = T, .k = C } }, }; const wide: []const c.Shape = if (d == .router) - &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C } } + &.{ .{ .rows = 64, .n = E, .k = C }, .{ .rows = 32, .n = E, .k = C }, .{ .rows = 100, .n = E, .k = C }, .{ .rows = 2048, .n = E, .k = C } } else - &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C } }; + &.{ .{ .rows = 64, .n = T, .k = C }, .{ .rows = 32, .n = T, .k = C }, .{ .rows = 100, .n = T, .k = C }, .{ .rows = 2048, .n = T, .k = C } }; + return .{ plain, wide }; +} + +/// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. +pub fn dotSpec(d: Dot, tiles: bool, short: bool, mini: bool) c.Spec { + const both = if (mini) dotServed(M.mini, d) else dotServed(M.small, d); + const plain = both[0]; + const wide = both[1]; const names = [3][2][]const u8{ .{ "inkling2 ops tf_ink2_rowdot router (fp32 sigmoid scores)", "inkling2 ops tf_ink2_rowdot_tiles router (fp32 sigmoid scores)" }, .{ "inkling2 ops tf_ink2_rowdot attention sinks (bf16 sigmoid)", "" }, .{ "inkling2 ops tf_ink2_rowdot dynamic conv taps (fp32)", "inkling2 ops tf_ink2_rowdot_tiles dynamic conv taps (fp32)" }, }; - var s: c.Spec = .{ .name = names[@backingInt(d)][@intFromBool(tiles)], .accum = .f32, .depth = dotDepth, .out = if (d == .sink) .bf16 else .f32, .served = if (tiles) wide else plain }; + const flat = names[0] ++ names[1] ++ names[2]; + var s: c.Spec = .{ .name = M.namedAt(&flat, @as(usize, @backingInt(d)) * 2 + @intFromBool(tiles), mini), .accum = .f32, .depth = dotDepth, .out = if (d == .sink) .bf16 else .f32, .served = if (tiles) wide else plain }; s.tiles = if (tiles) .{ .{ .size = 32, .min = 32 }, .{ .size = 16 }, .{} } else .{ .{}, .{ .size = 8 }, .{} }; if (tiles) s.replaces = "tf_ink2_rowdot"; if (short) { - s.name = "control: inkling2 ops tf_ink2_rowdot router one 32-column step short"; + s.name = M.named("control: inkling2 ops tf_ink2_rowdot router one 32-column step short", mini); s.tiles = .{ .{}, .{}, .{} }; s.served = plain[0..2]; } @@ -144,6 +162,7 @@ pub const Rowdot = struct { dot: Dot, tiles: bool = false, short: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []u16 = &.{}, w: []u16 = &.{}, @@ -154,7 +173,7 @@ pub const Rowdot = struct { pub const sums = {}; pub fn spec(self: *const Rowdot) c.Spec { - return dotSpec(self.dot, self.tiles, self.short); + return dotSpec(self.dot, self.tiles, self.short, self.mini); } pub fn control(self: *const Rowdot) ?g.Gate { @@ -238,22 +257,28 @@ pub const Rowdot = struct { } }; -/// Rows x a rank's vocabulary share x 1: the head's fp32 logits, in place. -pub fn capSpec(wrong: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 128, .n = ref.share, .k = 1 } }; - return .{ .name = if (wrong) "control: inkling2 ops tf_ink2_softcap at cap 20" else "inkling2 ops tf_ink2_softcap (final logits, cap 30, in place)", .accum = .none, .depth = ref.noSums, .out = .f32, .in_place = true, .served = if (wrong) served[0..1] else served }; +fn capServed(comptime V: usize) []const c.Shape { + return &.{ .{ .rows = 16, .n = V, .k = 1 }, .{ .rows = 1, .n = V, .k = 1 }, .{ .rows = 128, .n = V, .k = 1 } }; +} + +/// Rows x a rank's vocabulary share x 1: the head's fp32 logits, in place (Mini: the whole 201,024 at one rank). +pub fn capSpec(wrong: bool, mini: bool) c.Spec { + const served = if (mini) capServed(M.mini.share()) else capServed(M.small.share()); + const name = if (wrong) M.named("control: inkling2 ops tf_ink2_softcap at cap 20", mini) else M.named("inkling2 ops tf_ink2_softcap (final logits, cap 30, in place)", mini); + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .f32, .in_place = true, .served = if (wrong) served[0..1] else served }; } /// x = tanhf(x / 30) * 30 over the logits in place. pub const Softcap = struct { kern: *const ops.Kernels, wrong: bool = false, + mini: bool = false, shape: c.Shape = undefined, x: []f32 = &.{}, out: u64 = 0, pub fn spec(self: *const Softcap) c.Spec { - return capSpec(self.wrong); + return capSpec(self.wrong, self.mini); } pub fn control(self: *const Softcap) ?g.Gate { From 913847b4d4a06c1cb380ba63c2156b0f621be34b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:13:16 +0100 Subject: [PATCH 02/84] cuda experts: Inkling 2 Mini's stored experts, MXFP8 and soft-capped SwiGLU in core Core grouped experts gain Format.mxfp8 (e4m3 codes times one E8M0 scale per row per 32 inputs, folded exactly into the bf16 mma operand, fp32 sums) and Layer.caps, Inkling's soft-capped SwiGLU epilogue (experts.cuh epilogue 4) on the NVFP4 decode and prompt kernels and on the new MXFP8 ones. NVFP4's per-expert factor is amax / denominator, each rounded to bf16 (experts_mx.nvfp4Factor, open question F1). Evidence: stored-experts contract 9 kernels pass gates 1-4, 7 short-K controls red; checkpoint layers 0 and 20 decode bit for bit on every weight of 128 experts, outputs within the fp32 bound; SASS of all 465 pre-existing (unit, sm, function) triples equal main on sm_80/86/89/120/121. --- zig/kernels/cuda/experts.cuh | 12 +- zig/kernels/cuda/fp8_experts.cu | 220 +++++++++ zig/kernels/cuda/nvfp4_experts.cu | 37 +- zig/src/core/contract/registry_joins.zig | 2 + .../core/contract/stored_experts_records.zig | 20 + zig/src/core/expert_decode.zig | 74 +++ zig/src/core/root.zig | 2 + zig/src/cuda/experts.zig | 83 +--- zig/src/cuda/experts_host_test.zig | 72 ++- zig/src/cuda/experts_mx.zig | 223 +++++++++ zig/src/cuda/experts_mx_test.zig | 133 ++++++ zig/src/cuda/root.zig | 2 + zig/tests/cuda/contract_family_sets.zig | 5 + zig/tests/cuda/contract_stored_experts.zig | 422 ++++++++++++++++++ zig/tests/cuda/main.zig | 10 + zig/tests/cuda/main_usage.zig | 1 + zig/tests/cuda/stored_experts_bench.zig | 99 ++++ zig/tests/cuda/stored_experts_check.zig | 203 +++++++++ zig/tests/cuda/stored_experts_tests.zig | 206 +++++++++ zig/tests/fixtures/gradient-serving.tsv | 10 +- 20 files changed, 1753 insertions(+), 83 deletions(-) create mode 100644 zig/src/core/contract/stored_experts_records.zig create mode 100644 zig/src/core/expert_decode.zig create mode 100644 zig/src/cuda/experts_mx.zig create mode 100644 zig/src/cuda/experts_mx_test.zig create mode 100644 zig/tests/cuda/contract_stored_experts.zig create mode 100644 zig/tests/cuda/stored_experts_bench.zig create mode 100644 zig/tests/cuda/stored_experts_check.zig create mode 100644 zig/tests/cuda/stored_experts_tests.zig diff --git a/zig/kernels/cuda/experts.cuh b/zig/kernels/cuda/experts.cuh index 73621f811e9..30656262d6f 100644 --- a/zig/kernels/cuda/experts.cuh +++ b/zig/kernels/cuda/experts.cuh @@ -53,6 +53,13 @@ __device__ __forceinline__ float swiglu(float g, float u, float limit) { return bf(gv / (1.f + expf(-gv))) * uv; } +// Inkling's soft-capped SwiGLU on fp32 sums (tf_ink2_gateup's form): gc tanh(g / gc) sigmoid(g) uc tanh(u / uc). +// sigmoid from exp(-|g|): a gate far below zero keeps its tiny value instead of 1 / (1 + inf) = 0. +__device__ __forceinline__ float softcap_swiglu(float g, float u, float gc, float uc) { + const float e = expf(-fabsf(g)), sg = g >= 0.f ? 1.f / (1.f + e) : e / (1.f + e); + return gc * tanhf(g / gc) * sg * (uc * tanhf(u / uc)); +} + // a < 0 ? 0 : a, not fmaxf, which would make a NaN sum 0. __device__ __forceinline__ float relu2(float a) { const float b = bf(a), u = b < 0.f ? 0.f : b; @@ -61,7 +68,7 @@ __device__ __forceinline__ float relu2(float a) { template __device__ __forceinline__ void epilogue(const float (&acc)[M][RT][NTW][4], int r, void* out, int N, int col0, int pr0, - int pr1, bool v0, bool v1, float limit) { + int pr1, bool v0, bool v1, float limit, float limit2 = 0.f) { #pragma unroll for (int h = 0; h < 2; ++h) { if (!(h ? v1 : v0)) continue; @@ -80,6 +87,9 @@ __device__ __forceinline__ void epilogue(const float (&acc)[M][RT][NTW][4], int } else if constexpr (EPI == 2) { o0 = swiglu(a0, acc[M - 1][r][j][2 * h], limit); o1 = swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit); + } else if constexpr (EPI == 4) { // limit and limit2: the gate's and the up's caps + o0 = softcap_swiglu(a0, acc[M - 1][r][j][2 * h], limit, limit2); + o1 = softcap_swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit, limit2); } else { o0 = a0; o1 = a1; diff --git a/zig/kernels/cuda/fp8_experts.cu b/zig/kernels/cuda/fp8_experts.cu index 10c2492ba2e..21e02a6a427 100644 --- a/zig/kernels/cuda/fp8_experts.cu +++ b/zig/kernels/cuda/fp8_experts.cu @@ -268,3 +268,223 @@ template __global__ void fp8_expert_prompt_kernel<2, 2, 2, 2>(const __nv_bfloat1 template __global__ void fp8_expert_prompt_kernel<1, 0, 4, 4>(const __nv_bfloat16* __restrict__, int, int, const uint4* __restrict__, const float* __restrict__, int, int, const int* __restrict__, const int* __restrict__, const int* __restrict__, void* __restrict__, int, float, int); template __global__ void fp8_expert_prompt_kernel<1, 3, 4, 4>(const __nv_bfloat16* __restrict__, int, int, const uint4* __restrict__, const float* __restrict__, int, int, const int* __restrict__, const int* __restrict__, const int* __restrict__, void* __restrict__, int, float, int); } + +// MXFP8 experts (Inkling 2 Mini's layers 20-23): e4m3 codes, one E8M0 scale per output row per 32 inputs. Each code +// times its scale is exact in bf16 (a power of two), so the weights enter the mma decoded and the sums stay fp32. +namespace tf_mxfp8_experts { + +using tf_common::fp8pair; +using tf_common::mul2; + +constexpr int MXB = 66; // uint4 a (32 columns, 32 inputs) block: fp8g's 64 of codes, then 32 E8M0 bytes +constexpr int PWARPS = 4, PSTAGES = 4; + +// 2^(e - 127) in both bf16 halves: code 0 is 2^-127 (a bf16 subnormal), 255 is NaN. +__device__ __forceinline__ uint32_t e8m0x2(uint32_t e) { + const uint32_t b = e == 0u ? 0x0040u : e == 255u ? 0x7FC0u : e << 7; + return b | (b << 16); +} + +// Column j * 8 + gq's decoded pair (inputs 4t, 4t + 1) and (4t + 2, 4t + 3) of a lane's word. +__device__ __forceinline__ void pairs(uint32_t word, uint32_t sv, uint32_t& b0, uint32_t& b1) { + b0 = mul2(fp8pair(word), sv); + b1 = mul2(fp8pair(word >> 16), sv); +} + +template +struct Stage { + uint4 w[M][2]; + uint32_t s[M]; // byte j: column j * 8 + gq's scale + uint2 xa[2], xb[2]; +}; + +template +__device__ __forceinline__ void load(Stage& st, const uint4* blk, int g, int lane, int gq, int t, + const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { + const uint4* b = blk + (size_t)g * (M * MXB); +#pragma unroll + for (int m = 0; m < M; ++m) { + st.w[m][0] = tf_common::ld_nc(b + m * MXB + 2 * lane); + st.w[m][1] = tf_common::ld_nc(b + m * MXB + 2 * lane + 1); + st.s[m] = __ldg(reinterpret_cast(b + m * MXB + 64) + gq); + } + const uint2 zero = make_uint2(0u, 0u); + const int k0 = g * 32 + 4 * t; +#pragma unroll + for (int h = 0; h < 2; ++h) { + st.xa[h] = v0 ? __ldg(reinterpret_cast(x0 + k0 + 16 * h)) : zero; + st.xb[h] = v1 ? __ldg(reinterpret_cast(x1 + k0 + 16 * h)) : zero; + } +} + +template +__device__ __forceinline__ void sum(float (&acc)[M][1][NTW][4], const Stage& st) { +#pragma unroll + for (int m = 0; m < M; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) { + const uint32_t sv = e8m0x2((st.s[m] >> (8 * j)) & 0xFFu); +#pragma unroll + for (int h = 0; h < 2; ++h) { + uint32_t b0, b1; + pairs(comp(st.w[m][h], j), sv, b0, b1); + mma(acc[m][0][j], st.xa[h].x, st.xb[h].x, st.xa[h].y, st.xb[h].y, b0, b1); + } + } +} + +// Decode rows: a warp's 32 columns of an item over all K, 16 pairs at a time, two k32 stages in registers. +template +__device__ __forceinline__ void decode_body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, + const uint4* __restrict__ W, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, + void* __restrict__ out, int N, float cap0, float cap1, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(counts) * NB; + for (int unit = blockIdx.x * 4 + (threadIdx.x >> 5); unit < units; unit += gridDim.x * 4) { + const int it = unit / NB, cb = unit - it * NB; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + const uint4* blk = W + ((size_t)e * NB + cb) * (size_t)KG * (M * MXB); + for (int r0 = 0; r0 < cnt; r0 += 16) { + const bool v0 = r0 + gq < cnt, v1 = r0 + gq + 8 < cnt; + const int pr0 = v0 ? __ldg(members + first + r0 + gq) : 0; + const int pr1 = v1 ? __ldg(members + first + r0 + gq + 8) : 0; + const __nv_bfloat16* x0 = X + (size_t)(slots ? pr0 / slots : pr0) * x_stride; + const __nv_bfloat16* x1 = X + (size_t)(slots ? pr1 / slots : pr1) * x_stride; + float acc[M][1][NTW][4]; +#pragma unroll + for (int m = 0; m < M; ++m) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[m][0][j][0] = acc[m][0][j][1] = acc[m][0][j][2] = acc[m][0][j][3] = 0.f; + Stage st[2]; +#pragma unroll + for (int d = 0; d < 2; ++d) + if (d < KG) load(st[d], blk, d, lane, gq, t, x0, x1, v0, v1); + for (int g0 = 0; g0 < KG; g0 += 2) { +#pragma unroll + for (int d = 0; d < 2; ++d) { + if (g0 + d >= KG) break; + sum(acc, st[d]); + if (g0 + d + 2 < KG) load(st[d], blk, g0 + d + 2, lane, gq, t, x0, x1, v0, v1); + } + } + epilogue(acc, 0, out, N, cb * COLS + 2 * t, pr0, pr1, v0, v1, cap0, cap1); + } + } +} + +// Prompt rows: items of 64 pairs, CW warps of columns by 4 / CW warps of rows, k32 groups staged in shared memory. +template +__device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, + const uint4* __restrict__ W, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, + void* __restrict__ out, int N, float cap0, float cap1, int skip) { + static_assert((PWARPS / CW) * RT * 16 == 64, "a prompt item holds 64 pairs"); + __shared__ uint4 sw[PSTAGES][CW][M * MXB]; + __shared__ uint4 sx[PSTAGES][64][4]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int cw = warp % CW, rw = warp / CW; + const int groups = NB / CW, units = __ldg(counts) * groups; + for (int unit = blockIdx.x; unit < units; unit += gridDim.x) { + const int it = unit / groups, cg = unit - it * groups; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + const int cb = cg * CW + cw; + int pr0[RT], pr1[RT]; + bool v0[RT], v1[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int r0 = (rw * RT + r) * 16; + v0[r] = r0 + gq < cnt; + v1[r] = r0 + gq + 8 < cnt; + pr0[r] = v0[r] ? __ldg(members + first + r0 + gq) : 0; + pr1[r] = v1[r] ? __ldg(members + first + r0 + gq + 8) : 0; + } + const __nv_bfloat16* xrow[2]; +#pragma unroll + for (int c = 0; c < 2; ++c) { + const int i = threadIdx.x + c * PWARPS * 32, pr = __ldg(members + first + min(i / 4, cnt - 1)); + xrow[c] = X + (size_t)(slots ? pr / slots : pr) * x_stride + (i % 4) * 8; + } + const uint4* base = W + ((size_t)e * NB + cg * CW) * (size_t)KG * (M * MXB); + auto stage = [&](int g) { +#pragma unroll + for (int c = 0; c < 2; ++c) { + const int i = threadIdx.x + c * PWARPS * 32; + cp16(&sx[g % PSTAGES][i / 4][i % 4], xrow[c] + g * 32); + } + for (int i = threadIdx.x; i < CW * M * MXB; i += PWARPS * 32) { + const int c = i / (M * MXB), j = i % (M * MXB); + cp16(&sw[g % PSTAGES][c][j], base + ((size_t)c * KG + g) * (M * MXB) + j); + } + }; + __syncthreads(); +#pragma unroll + for (int g = 0; g < PSTAGES - 1; ++g) { + if (g < KG) stage(g); + cp_commit(); + } + float acc[M][RT][NTW][4]; +#pragma unroll + for (int m = 0; m < M; ++m) +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[m][r][j][0] = acc[m][r][j][1] = acc[m][r][j][2] = acc[m][r][j][3] = 0.f; + const bool live = rw * RT * 16 < cnt; + for (int g = 0; g < KG; ++g) { + cp_wait(); + __syncthreads(); + if (g + PSTAGES - 1 < KG) stage(g + PSTAGES - 1); + cp_commit(); + if (!live) continue; + const int sg = g % PSTAGES; +#pragma unroll + for (int h = 0; h < 2; ++h) { + uint2 xa[RT], xb[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int r0 = (rw * RT + r) * 16 + gq; + xa[r] = reinterpret_cast(&sx[sg][r0][0])[4 * h + t]; + xb[r] = reinterpret_cast(&sx[sg][r0 + 8][0])[4 * h + t]; + } +#pragma unroll + for (int m = 0; m < M; ++m) { + const uint4 wv = sw[sg][cw][m * MXB + 2 * lane + h]; + const uint32_t s4 = reinterpret_cast(&sw[sg][cw][m * MXB + 64])[gq]; +#pragma unroll + for (int j = 0; j < NTW; ++j) { + uint32_t b0, b1; + pairs(comp(wv, j), e8m0x2((s4 >> (8 * j)) & 0xFFu), b0, b1); +#pragma unroll + for (int r = 0; r < RT; ++r) mma(acc[m][r][j], xa[r].x, xb[r].x, xa[r].y, xb[r].y, b0, b1); + } + } + } + } + cp_wait<0>(); + if (live) { +#pragma unroll + for (int r = 0; r < RT; ++r) + epilogue(acc, r, out, N, cb * COLS + 2 * t, pr0[r], pr1[r], v0[r], v1[r], cap0, cap1); + } + } +} + +} // namespace tf_mxfp8_experts + +// The MXFP8 entries (cap0, cap1: the gate's and the up's caps; the downs ignore them), 128 threads each. +#define TF_MX_ENTRY(NAME, BODY) \ + extern "C" __global__ void __launch_bounds__(128) \ + NAME(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, int KG, \ + int NB, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, \ + void* __restrict__ out, int N, float cap0, float cap1, int skip) { \ + tf_mxfp8_experts::BODY(X, x_stride, slots, W, KG, NB, items, counts, members, out, N, cap0, cap1, skip); \ + } +#define TF_MX_ARGS(...) __VA_ARGS__ +TF_MX_ENTRY(tf_mxfp8_softcap, decode_body) +TF_MX_ENTRY(tf_mxfp8_down_f32, decode_body) +TF_MX_ENTRY(tf_mxfp8_down_bf16, decode_body) +TF_MX_ENTRY(tf_mxfp8_prompt_softcap, prompt_body) +TF_MX_ENTRY(tf_mxfp8_prompt_down, prompt_body) diff --git a/zig/kernels/cuda/nvfp4_experts.cu b/zig/kernels/cuda/nvfp4_experts.cu index 5a360758b93..4c913326b73 100644 --- a/zig/kernels/cuda/nvfp4_experts.cu +++ b/zig/kernels/cuda/nvfp4_experts.cu @@ -165,7 +165,8 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, int const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ members, - void* __restrict__ out, int N, float limit, int skip) { + void* __restrict__ out, int N, float limit, int skip, + float limit2 = 0.f) { TF_RING_STORAGE Ring ring; const int it = unit / NB, cb = unit - it * NB; const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); @@ -192,7 +193,7 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, int #pragma unroll for (int q = 0; q < 4; ++q) acc[m][0][j][q] *= g; } - epilogue(acc, 0, out, N, cb * COLS + 2 * t, pr0, pr1, v0, v1, limit); + epilogue(acc, 0, out, N, cb * COLS + 2 * t, pr0, pr1, v0, v1, limit, limit2); } } @@ -362,7 +363,7 @@ template __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ members, void* __restrict__ out, int N, - float limit, int cbt, int e, int first, int cnt) { + float limit, int cbt, int e, int first, int cnt, float limit2 = 0.f) { using P = Prompt4; constexpr int STAGES = P::STAGES; extern __shared__ uint4 sm[]; @@ -494,7 +495,7 @@ __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X const int m0 = base + 16 * r + gq, m1 = m0 + 8; const bool v0 = m0 < cnt, v1 = m1 < cnt; const int p0 = v0 ? __ldg(members + first + m0) : 0, p1 = v1 ? __ldg(members + first + m1) : 0; - epilogue(acc, r, out, N, cb * COLS + 2 * t, p0, p1, v0, v1, limit); + epilogue(acc, r, out, N, cb * COLS + 2 * t, p0, p1, v0, v1, limit, limit2); } } } @@ -504,7 +505,7 @@ __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, int N, - float limit, int skip) { + float limit, int skip, float limit2 = 0.f) { static_assert(RT == 4, "the dispatch below spells out 0 .. 4 row tiles"); const int nbt = (NB + WN - 1) / WN, it = blockIdx.x / nbt, cbt = blockIdx.x - it * nbt; if (it >= __ldg(counts)) return; @@ -512,7 +513,8 @@ __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, if (e == skip) return; // an expert the family computes itself, left alone as the decode form does const int nt = max(0, min(RT, (cnt - 16 * RT * ((threadIdx.x >> 5) / WN) + 15) >> 4)); #define TF_TILES(NT) \ - prompt_tiles(X, x_stride, slots, W, scale, KG, NB, members, out, N, limit, cbt, e, first, cnt) + prompt_tiles(X, x_stride, slots, W, scale, KG, NB, members, out, N, limit, cbt, e, \ + first, cnt, limit2) switch (nt) { case 4: TF_TILES(4); break; case 3: TF_TILES(3); break; @@ -568,3 +570,26 @@ TF_NVFP4_PROMPT(tf_nvfp4_prompt_down, 1, 3, 8) } TF_NVFP4_FACT(tf_nvfp4_fact_swiglu, 2, 2, 4) TF_NVFP4_FACT(tf_nvfp4_fact_down_f32, 1, 0, 8) + +// Soft-capped SwiGLU gate-up (Inkling 2 Mini): the decode units of nvfp4_expert_kernel<2, 2, 4> and the prompt tiles of +// tf_nvfp4_prompt_swiglu, with experts.cuh's epilogue 4 over the gate's and the up's caps. +extern "C" __global__ void __launch_bounds__(128) + tf_nvfp4_softcap(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, + const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, int N, + float gate_cap, float up_cap, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(counts) * NB; + for (int unit = blockIdx.x * 4 + (threadIdx.x >> 5); unit < units; unit += gridDim.x * 4) + tf_nvfp4_experts::unit_full<2, 4, 4>(unit, lane, gq, t, threadIdx.x >> 5, X, x_stride, slots, W, scale, KG, NB, + items, members, out, N, gate_cap, skip, up_cap); +} + +extern "C" __global__ void __launch_bounds__(128) + tf_nvfp4_prompt_softcap(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, + const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, + const int* __restrict__ counts, const int* __restrict__ members, void* __restrict__ out, + int N, float gate_cap, float up_cap, int skip) { + tf_nvfp4_experts::prompt_body<2, 4, 4, 1, 4>(X, x_stride, slots, W, scale, KG, NB, items, counts, members, out, N, + gate_cap, skip, up_cap); +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index e696c6929e5..db05785f111 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -13,6 +13,7 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("modelopt_lane_records.zig").cuda ++ @import("nvfp4_fact_records.zig").cuda ++ @import("nvfp4_experts32_records.zig").cuda ++ + @import("stored_experts_records.zig").cuda ++ @import("experts_bf16_records.zig").cuda ++ @import("lane_half_records.zig").cuda ++ @import("pocket_records.zig").cuda ++ @@ -34,6 +35,7 @@ pub const nvcc_132_after = @import("registry_learning.zig").cuda_132 ++ @import("qwen_served_records.zig").cuda_132 ++ @import("flashnext_tile_records.zig").cuda_132 ++ @import("nvfp4_fact_records.zig").cuda_132 ++ + @import("stored_experts_records.zig").cuda_132 ++ @import("experts_bf16_records.zig").cuda_132 ++ @import("pocket_records.zig").cuda_132 ++ @import("minimax_cuda_records.zig").cuda_132 ++ diff --git a/zig/src/core/contract/stored_experts_records.zig b/zig/src/core/contract/stored_experts_records.zig new file mode 100644 index 00000000000..baec49f15c5 --- /dev/null +++ b/zig/src/core/contract/stored_experts_records.zig @@ -0,0 +1,20 @@ +//! Inkling 2 Mini's stored experts (soft-capped NVFP4, MXFP8): nvcc 13.0.88, sm_80/86/89/120/121. +const CudaRecord = @import("registry.zig").CudaRecord; + +pub const cuda = [_]CudaRecord{ + .{ .launch = .{ .name = "nvfp4_experts tf_nvfp4_softcap", .symbol = "tf_nvfp4_softcap", .image = "nvfp4_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 100, .static = 34816, .bound = 128 }, .{ .regs = 106, .static = 34816, .bound = 128 }, .{ .regs = 134, .static = 34816, .bound = 128 }, .{ .regs = 129, .static = 34816, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts tf_nvfp4_prompt_softcap", .symbol = "tf_nvfp4_prompt_softcap", .image = "nvfp4_experts", .threads = 128, .dynamic = 34816 }, .usage = .{ .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 209, .static = 0, .bound = 128 }, .{ .regs = 209, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_softcap", .symbol = "tf_mxfp8_softcap", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 119, .static = 0, .bound = 128 }, .{ .regs = 119, .static = 0, .bound = 128 }, .{ .regs = 119, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 }, .{ .regs = 124, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_down_f32", .symbol = "tf_mxfp8_down_f32", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_down_bf16", .symbol = "tf_mxfp8_down_bf16", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 }, .{ .regs = 89, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_prompt_softcap", .symbol = "tf_mxfp8_prompt_softcap", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 146, .static = 33280, .bound = 128 }, .{ .regs = 146, .static = 33280, .bound = 128 }, .{ .regs = 146, .static = 33280, .bound = 128 }, .{ .regs = 160, .static = 33280, .bound = 128 }, .{ .regs = 160, .static = 33280, .bound = 128 } } }, + .{ .launch = .{ .name = "fp8_experts tf_mxfp8_prompt_down", .symbol = "tf_mxfp8_prompt_down", .image = "fp8_experts", .threads = 128, .dynamic = 0 }, .usage = .{ .{ .regs = 140, .static = 33280, .bound = 128 }, .{ .regs = 142, .static = 33280, .bound = 128 }, .{ .regs = 142, .static = 33280, .bound = 128 }, .{ .regs = 154, .static = 33280, .bound = 128 }, .{ .regs = 154, .static = 33280, .bound = 128 } } }, +}; + +/// What nvcc 13.2.78 compiles differently. +pub const cuda_132 = [_]@import("registry.zig").Override{ + .{ .name = "nvfp4_experts tf_nvfp4_softcap", .usage = .{ .{ .regs = 100, .static = 34816, .bound = 128 }, .{ .regs = 106, .static = 34816, .bound = 128 }, .{ .regs = 134, .static = 34816, .bound = 128 }, .{ .regs = 128, .static = 34816, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts tf_nvfp4_prompt_softcap", .usage = .{ .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 239, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 } } }, + .{ .name = "fp8_experts tf_mxfp8_down_f32", .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 } } }, + .{ .name = "fp8_experts tf_mxfp8_down_bf16", .usage = .{ .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 }, .{ .regs = 92, .static = 0, .bound = 128 } } }, +}; diff --git a/zig/src/core/expert_decode.zig b/zig/src/core/expert_decode.zig new file mode 100644 index 00000000000..7d46bd0cff6 --- /dev/null +++ b/zig/src/core/expert_decode.zig @@ -0,0 +1,74 @@ +//! Stored routed-expert weights decoded on the host (Inkling 2 Mini): NVFP4 and MXFP8 as stored, no requantizing. +const std = @import("std"); + +/// An E2M1 code (low 4 bits; bit 3 the sign): 0, 0.5, 1, 1.5, 2, 3, 4, 6. +pub fn e2m1(code: u8) f64 { + const magnitude = [8]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = magnitude[code & 7]; + return if (code & 8 != 0) -v else v; +} + +/// An E4M3 (fn) code; 0x7F and 0xFF are NaN. +pub fn e4m3(code: u8) f64 { + const e: i32 = (code >> 3) & 15; + const m: f64 = @floatFromInt(code & 7); + const v: f64 = if (e == 15 and code & 7 == 7) std.math.nan(f64) else if (e == 0) m * 0x1p-9 else (8 + m) * std.math.ldexp(@as(f64, 1), e - 10); + return if (code & 0x80 != 0) -v else v; +} + +/// An E8M0 scale: 2^(code - 127); 255 is NaN. +pub fn e8m0(code: u8) f64 { + if (code == 255) return std.math.nan(f64); + return std.math.ldexp(@as(f64, 1), @as(i32, code) - 127); +} + +/// Input i's E2M1 code of a row of packed bytes, low nibble first (the order the CUDA packers assume). +pub fn nibble(row: []const u8, i: usize) u8 { + const b = row[i / 2]; + return if (i % 2 == 0) b & 15 else b >> 4; +} + +/// NVFP4 weight (row, i) of one expert's [n, k/2] codes and [n, k/16] E4M3 scales, times its factor: exact in f64. +pub fn nvfp4(codes: []const u8, scales: []const u8, k: usize, row: usize, i: usize, factor: f64) f64 { + return e2m1(nibble(codes[row * (k / 2) ..][0 .. k / 2], i)) * e4m3(scales[row * (k / 16) + i / 16]) * factor; +} + +/// The same weight as the decode kernels form it in fp32: code x block scale (exact), then one rounding by the factor. +pub fn nvfp4F32(codes: []const u8, scales: []const u8, k: usize, row: usize, i: usize, factor: f32) f32 { + const cs: f32 = @floatCast(e2m1(nibble(codes[row * (k / 2) ..][0 .. k / 2], i)) * e4m3(scales[row * (k / 16) + i / 16])); + return cs * factor; +} + +/// MXFP8 weight (row, i) of one expert's [n, k] E4M3 codes and [n, k/32] E8M0 scales: exact in f64 and in f32. +pub fn mxfp8(codes: []const u8, scales: []const u8, k: usize, row: usize, i: usize) f64 { + return e4m3(codes[row * k + i]) * e8m0(scales[row * (k / 32) + i / 32]); +} + +test "E2M1, E4M3 and E8M0 decode their extremes, signs and NaN codes" { + const t = std.testing; + try t.expectEqual(@as(f64, 6), e2m1(7)); + try t.expectEqual(@as(f64, -0.5), e2m1(9)); + try t.expect(std.math.signbit(e2m1(8))); + try t.expectEqual(@as(f64, 448), e4m3(0x7E)); + try t.expectEqual(@as(f64, -0x1p-9), e4m3(0x81)); // the least subnormal + try t.expectEqual(@as(f64, 1), e4m3(0x38)); + try t.expect(std.math.isNan(e4m3(0x7F)) and std.math.isNan(e4m3(0xFF))); + try t.expectEqual(@as(f64, 1), e8m0(127)); + try t.expectEqual(@as(f64, 0x1p-127), e8m0(0)); + try t.expect(std.math.isNan(e8m0(255))); +} + +test "NVFP4 and MXFP8 weights take input i's nibble, its 16- or 32-input scale and the factor" { + const t = std.testing; + const codes = [_]u8{ 0x7A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16 }; + const scales = [_]u8{ 0x40, 0x38 }; // 2, then 1 + try t.expectEqual(@as(f64, -1 * 2 * 0.25), nvfp4(&codes, &scales, 32, 0, 0, 0.25)); // low nibble 0xA = -1 + try t.expectEqual(@as(f64, 6 * 2 * 0.25), nvfp4(&codes, &scales, 32, 0, 1, 0.25)); + try t.expectEqual(@as(f64, 4 * 1 * 0.25), nvfp4(&codes, &scales, 32, 0, 30, 0.25)); // byte 15 low: 6 = 4 + try t.expectEqual(@as(f32, 4 * 0.1), nvfp4F32(&codes, &scales, 32, 0, 30, 0.1)); + var mx: [64]u8 = @splat(0x38); + mx[33] = 0xC0; // -2 + const ms = [_]u8{ 127, 120 }; + try t.expectEqual(@as(f64, 1), mxfp8(&mx, &ms, 64, 0, 31)); + try t.expectEqual(@as(f64, -2 * 0x1p-7), mxfp8(&mx, &ms, 64, 0, 33)); +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 83ceaa32e28..8ae5fa0a520 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -57,6 +57,7 @@ pub const contract = @import("contract.zig"); pub const nvfp4 = @import("nvfp4.zig"); pub const nvfp4_csf32 = @import("nvfp4_csf32.zig"); pub const modelopt = @import("modelopt.zig"); +pub const expert_decode = @import("expert_decode.zig"); /// Pictures as 0.6.6 loaded them: PNG, JPEG through the pinned libjpeg-turbo, orientation, the shared bicubic resizes. pub const picture = @import("picture/picture.zig"); /// Qwen-VL image input every Qwen3.5-VL checkpoint shares: settings, geometry, M-RoPE positions, the tower's tables. @@ -86,6 +87,7 @@ test { _ = profile; _ = checkpoint_weights; _ = safetensors; + _ = expert_decode; _ = gguf; _ = affine4_host; _ = rope_yarn; diff --git a/zig/src/cuda/experts.zig b/zig/src/cuda/experts.zig index 3f7bb4de962..e4b51cc85a0 100644 --- a/zig/src/cuda/experts.zig +++ b/zig/src/cuda/experts.zig @@ -7,6 +7,7 @@ const kernels = @import("kernels.zig"); const grouped = @import("grouped.zig"); const driver = @import("driver.zig"); const ggml = @import("ggml.zig"); +const mx = @import("experts_mx.zig"); const Driver = driver.Driver; const Module = module.Module; @@ -16,7 +17,7 @@ const Plan = grouped.Plan; const Affine3Experts = @import("experts3.zig").Affine3Experts; pub const Bf16Experts = @import("experts_bf16.zig").Bf16Experts; -pub const Format = enum { affine4, affine3, fp8g, nvfp4, nvfp4_csf0, exl3, iq2xxs, bf16 }; +pub const Format = enum { affine4, affine3, fp8g, nvfp4, nvfp4_csf0, exl3, iq2xxs, bf16, mxfp8 }; /// One layer's experts on the device as each format's make() lays them out; a family stacks its shared ones last. pub const Layer = struct { @@ -33,6 +34,7 @@ pub const Layer = struct { after: bool = false, // exl3: clamp silu's output (min(silu(g), L): Ling), not its input (silu(min(g, L))); others refuse it relu2: bool = false, // nvfp4: up is one projection under relu^2 (Nemotron), not SwiGLU's gate and up; iq2xxs: always swiglu: bool = false, // affine4: up is gate and up interleaved per group ([E][NI/32][D/64][2][288]) under SwiGLU + caps: [2]f32 = .{ 0, 0 }, // nvfp4, mxfp8: Inkling's soft-capped SwiGLU (gate cap, up cap); 0, 0 for none shared: i32 = -1, // affine3: the expert whose tables are 4-bit (a SwiGLU pair at shared_up, down at shared_down) shared_up: u64 = 0, shared_down: u64 = 0, @@ -54,10 +56,12 @@ pub const Grouped = struct { nvfp4_csf0: ?*const @import("experts32.zig").Nvfp4b32Experts = null, iq2xxs: ?*const Iq2xxsExperts = null, bf16: ?*const Bf16Experts = null, + mxfp8: ?*const mx.Mxfp8Experts = null, /// Decode rows: `items` bounds the plan, `pairs` its picks; `tile` 16 or 64 (EXL3 only); `skip` an expert or -1. pub fn decode(g: Grouped, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, pairs: usize, tile: usize, skip: i32) !void { if (l.after and l.format != .exl3) return error.OptionNotBuilt; // the clamp-after order is built for EXL3 only + try mx.capsBuilt(l); switch (l.format) { .exl3 => return (g.exl3 orelse return error.FormatNotLoaded).run(s, epi, in, l, p, out, items, pairs, tile, skip), .affine4 => { @@ -80,12 +84,14 @@ pub const Grouped = struct { .nvfp4_csf0 => return (g.nvfp4_csf0 orelse return error.FormatNotLoaded).run(s, epi, in, l, p, out, items, skip), .iq2xxs => return iq2Run(g.iq2xxs orelse return error.FormatNotLoaded, s, false, epi, in, l, p, out, items, skip), .bf16 => return (g.bf16 orelse return error.FormatNotLoaded).run(s, false, epi, in, l, p, out, items, skip), + .mxfp8 => return (g.mxfp8 orelse return error.FormatNotLoaded).run(s, false, epi, in, l, p, out, items, skip), } } /// Prompt rows: `items` bounds the plan, `pairs` its picks; `tile` 16 or 64 (EXL3 only); `skip` an expert or -1. pub fn prompt(g: Grouped, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, pairs: usize, tile: usize, skip: i32) !void { if (l.after and l.format != .exl3) return error.OptionNotBuilt; // the clamp-after order is built for EXL3 only + try mx.capsBuilt(l); switch (l.format) { .exl3 => return (g.exl3 orelse return error.FormatNotLoaded).run(s, epi, in, l, p, out, items, pairs, tile, skip), .affine4 => { @@ -108,6 +114,7 @@ pub const Grouped = struct { .nvfp4_csf0 => return (g.nvfp4_csf0 orelse return error.FormatNotLoaded).runPrompt(s, epi, in, l, p, out, items, skip), .iq2xxs => return iq2Run(g.iq2xxs orelse return error.FormatNotLoaded, s, true, epi, in, l, p, out, items, skip), .bf16 => return (g.bf16 orelse return error.FormatNotLoaded).run(s, true, epi, in, l, p, out, items, skip), + .mxfp8 => return (g.mxfp8 orelse return error.FormatNotLoaded).run(s, true, epi, in, l, p, out, items, skip), } } }; @@ -115,7 +122,7 @@ pub const Grouped = struct { /// Pairs a prompt item holds, per format (the Python engines' prompt tiles). pub fn promptTile(f: Format) usize { return switch (f) { - .affine4, .affine3, .fp8g, .nvfp4, .nvfp4_csf0, .exl3, .iq2xxs, .bf16 => 64, + .affine4, .affine3, .fp8g, .nvfp4, .nvfp4_csf0, .exl3, .iq2xxs, .bf16, .mxfp8 => 64, }; } @@ -345,6 +352,7 @@ pub const Nvfp4Experts = struct { resident: [7]usize, // blocks the grid may hold: per SM times SMs prompt_fns: [3]Function, // relu^2 up, SwiGLU gate-up, bf16 sums down fact_fns: [2]Function, // the decode form's sums on prompt tiles: SwiGLU gate-up, fp32 down + softcap: mx.Softcap = .{}, // Inkling's soft-capped SwiGLU gate-up, decode and prompt (experts_mx.zig) warps: usize = 4, pub const cols = 32; // output columns a block @@ -411,6 +419,7 @@ pub const Nvfp4Experts = struct { f.* = try mod.function(name); try f.allowDynamicShared(promptSmem(parts, wn)); } + e.softcap = try mx.Softcap.resolve(mod, sms); return e; } @@ -420,6 +429,7 @@ pub const Nvfp4Experts = struct { /// One call of nvfp4/experts.py's _run on a plan of at most `items` items. pub fn run(e: *const Nvfp4Experts, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { + if (epi == .up and l.caps[0] != 0) return e.softcap.run(s, false, in, l, p, out, items, skip); const gate = epi == .up; const kg = (if (gate) l.dims else l.width) / 32; const nb = (if (gate) l.width else l.dims) / cols; @@ -444,6 +454,7 @@ pub const Nvfp4Experts = struct { /// Prompt rows on a plan of at most `items` items of 64 pairs: up (relu^2 or SwiGLU by the layer), bf16 sums down. pub fn runPrompt(e: *const Nvfp4Experts, s: Stream, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { if (epi == .down_f32) return error.EpilogueNotBuilt; + if (epi == .up and l.caps[0] != 0) return e.softcap.run(s, true, in, l, p, out, items, skip); const gate = epi == .up; const parts: usize = if (gate and !l.relu2) 2 else 1; const nb = (if (gate) l.width else l.dims) / cols; @@ -516,74 +527,6 @@ pub const Nvfp4Experts = struct { } }; -test "a packed nvfp4 block puts each nibble and scale where nvfp4/experts.py's _pack does" { - const gpa = std.testing.allocator; - const n = 64; - const k = 64; - const codes = try gpa.alloc(u8, n * k / 2); - defer gpa.free(codes); - for (codes, 0..) |*c, i| c.* = @truncate(i * 29 + 3); - var scales: [n * k / 16]u8 = undefined; - for (&scales, 0..) |*c, i| c.* = @truncate(i * 7 + 1); - var out: [n / 32 * (k / 32) * Nvfp4Experts.words]u32 = undefined; - Nvfp4Experts.packOne(&out, codes, &scales, n, k); - const words = Nvfp4Experts.words; - // block (cb 1, g 1), lane gq 3, t 2, tile j 1: row 32 + 8 + 3 = 43; input 32 + 16 + 8 + 3 (h 1, q 3) -> slot 7 - const w = out[(1 * 2 + 1) * words + (3 * 4 + 2) * 4 + 1]; - try std.testing.expectEqual(@as(u32, codes[43 * 32 + 59 / 2] >> 4), (w >> Nvfp4Experts.slot(1, 3)) & 0xF); - // its scale byte (t 2, h 1, j 1, c 0): row 32 + 8 + 4 = 44, k16 group 3 - const sc = std.mem.sliceAsBytes(out[(1 * 2 + 1) * words + 128 ..][0..16]); - try std.testing.expectEqual(scales[44 * 4 + 3], sc[((2 * 2 + 1) * 4 + 1) * 2]); -} - -test "packGateUp stacks packOne's gate and up blocks per (column block, k32 group)" { - const n = 64; - const k = 64; - const words = Nvfp4Experts.words; - var codes: [2][n * k / 2]u8 = undefined; - var scales: [2][n * k / 16]u8 = undefined; - for (0..2) |m| { - for (&codes[m], 0..) |*c, i| c.* = @truncate(i * 29 + 3 + m * 101); - for (&scales[m], 0..) |*c, i| c.* = @truncate(i * 7 + 1 + m * 13); - } - var one: [2][n / 32 * (k / 32) * words]u32 = undefined; - for (0..2) |m| Nvfp4Experts.packOne(&one[m], &codes[m], &scales[m], n, k); - var both: [2 * one[0].len]u32 = undefined; - Nvfp4Experts.packGateUp(&both, .{ &codes[0], &scales[0] }, .{ &codes[1], &scales[1] }, n, k); - for (0..one[0].len / words) |b| for (0..2) |m| { - try std.testing.expectEqualSlices(u32, one[m][b * words ..][0..words], both[(2 * b + m) * words ..][0..words]); - }; -} - -test "nvfp4 rows of either kind are refused when the format is not loaded" { - const g: Grouped = .{}; - const l: Layer = .{ .format = .nvfp4, .up = 0, .down = 0, .width = 64, .dims = 64, .experts = 2, .relu2 = true }; - const s: Stream = undefined; // never reached: the refusal comes first - const p: Plan = .{ .members = 0, .items = 0, .counts = 0, .rank = 0, .hist = 0 }; - try std.testing.expectError(error.FormatNotLoaded, g.prompt(s, .up, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 64, -1)); - try std.testing.expectError(error.FormatNotLoaded, g.decode(s, .down_bf16, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 16, -1)); - try std.testing.expectEqual(@as(usize, 2 * 2 * 3 * 144 * 4), Nvfp4Experts.bytes(2, 64, 96, 1)); - try std.testing.expectEqual(@as(u32, 2 * 17408), Nvfp4Experts.promptSmem(1, 8)); // 64 rows x 64 inputs, 8 x 2 blocks - try std.testing.expectEqual(@as(u32, 2 * 17408), Nvfp4Experts.promptSmem(2, 4)); - try std.testing.expectEqual(@as(u32, 3 * 12800), Nvfp4Experts.promptSmem(1, 4)); -} - -test "a packed fp8 expert puts each word where fp8/experts.py's pack does" { - const gpa = std.testing.allocator; - const n = 128; - const k = 128; - const w = try gpa.alloc(u8, n * k); - defer gpa.free(w); - for (w, 0..) |*b, i| b.* = @truncate(i * 31 + 7); - const out = try gpa.alloc(u32, n * k / 4); - defer gpa.free(out); - Fp8Experts.packOne(out, w, n, k); - // (cb 1, g 2, gq 5, t 3, h 1, j 2): row 32 + 16 + 5 = 53, word 2 * 8 + 4 + 3 = 23 - const idx = (((((1 * 4 + 2) * 8 + 5) * 4 + 3) * 2 + 1) * 4) + 2; - const words = std.mem.bytesAsSlice(u32, @as([]align(1) const u8, w)); - try std.testing.expectEqual(words[53 * (k / 4) + 23], out[idx]); -} - test { _ = @import("experts_host_test.zig"); // Grouped's refusals before any launch } diff --git a/zig/src/cuda/experts_host_test.zig b/zig/src/cuda/experts_host_test.zig index 65f4a7f7952..2e9ba45e8e4 100644 --- a/zig/src/cuda/experts_host_test.zig +++ b/zig/src/cuda/experts_host_test.zig @@ -1,4 +1,4 @@ -//! Grouped's refusals before any launch: a format not loaded, an epilogue or an option it was not built with. +//! Grouped's refusals before any launch, and the NVFP4 and FP8 block packings' layouts. const std = @import("std"); const experts = @import("experts.zig"); @@ -6,6 +6,8 @@ const Grouped = experts.Grouped; const Layer = experts.Layer; const Plan = @import("grouped.zig").Plan; const Stream = @import("stream.zig").Stream; +const Nvfp4Experts = experts.Nvfp4Experts; +const Fp8Experts = experts.Fp8Experts; test "a format that is not loaded, or an option it was not built with, is refused before any launch" { const g: Grouped = .{}; @@ -53,3 +55,71 @@ test "bf16 experts refuse dims or widths off the 32-wide blocks before any launc } } } + +test "a packed nvfp4 block puts each nibble and scale where nvfp4/experts.py's _pack does" { + const gpa = std.testing.allocator; + const n = 64; + const k = 64; + const codes = try gpa.alloc(u8, n * k / 2); + defer gpa.free(codes); + for (codes, 0..) |*c, i| c.* = @truncate(i * 29 + 3); + var scales: [n * k / 16]u8 = undefined; + for (&scales, 0..) |*c, i| c.* = @truncate(i * 7 + 1); + var out: [n / 32 * (k / 32) * Nvfp4Experts.words]u32 = undefined; + Nvfp4Experts.packOne(&out, codes, &scales, n, k); + const words = Nvfp4Experts.words; + // block (cb 1, g 1), lane gq 3, t 2, tile j 1: row 32 + 8 + 3 = 43; input 32 + 16 + 8 + 3 (h 1, q 3) -> slot 7 + const w = out[(1 * 2 + 1) * words + (3 * 4 + 2) * 4 + 1]; + try std.testing.expectEqual(@as(u32, codes[43 * 32 + 59 / 2] >> 4), (w >> Nvfp4Experts.slot(1, 3)) & 0xF); + // its scale byte (t 2, h 1, j 1, c 0): row 32 + 8 + 4 = 44, k16 group 3 + const sc = std.mem.sliceAsBytes(out[(1 * 2 + 1) * words + 128 ..][0..16]); + try std.testing.expectEqual(scales[44 * 4 + 3], sc[((2 * 2 + 1) * 4 + 1) * 2]); +} + +test "packGateUp stacks packOne's gate and up blocks per (column block, k32 group)" { + const n = 64; + const k = 64; + const words = Nvfp4Experts.words; + var codes: [2][n * k / 2]u8 = undefined; + var scales: [2][n * k / 16]u8 = undefined; + for (0..2) |m| { + for (&codes[m], 0..) |*c, i| c.* = @truncate(i * 29 + 3 + m * 101); + for (&scales[m], 0..) |*c, i| c.* = @truncate(i * 7 + 1 + m * 13); + } + var one: [2][n / 32 * (k / 32) * words]u32 = undefined; + for (0..2) |m| Nvfp4Experts.packOne(&one[m], &codes[m], &scales[m], n, k); + var both: [2 * one[0].len]u32 = undefined; + Nvfp4Experts.packGateUp(&both, .{ &codes[0], &scales[0] }, .{ &codes[1], &scales[1] }, n, k); + for (0..one[0].len / words) |b| for (0..2) |m| { + try std.testing.expectEqualSlices(u32, one[m][b * words ..][0..words], both[(2 * b + m) * words ..][0..words]); + }; +} + +test "nvfp4 rows of either kind are refused when the format is not loaded" { + const g: Grouped = .{}; + const l: Layer = .{ .format = .nvfp4, .up = 0, .down = 0, .width = 64, .dims = 64, .experts = 2, .relu2 = true }; + const s: Stream = undefined; // never reached: the refusal comes first + const p: Plan = .{ .members = 0, .items = 0, .counts = 0, .rank = 0, .hist = 0 }; + try std.testing.expectError(error.FormatNotLoaded, g.prompt(s, .up, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 64, -1)); + try std.testing.expectError(error.FormatNotLoaded, g.decode(s, .down_bf16, .{ .x = 0, .stride = 64 }, l, p, 0, 1, 1, 16, -1)); + try std.testing.expectEqual(@as(usize, 2 * 2 * 3 * 144 * 4), Nvfp4Experts.bytes(2, 64, 96, 1)); + try std.testing.expectEqual(@as(u32, 2 * 17408), Nvfp4Experts.promptSmem(1, 8)); // 64 rows x 64 inputs, 8x2 blocks + try std.testing.expectEqual(@as(u32, 2 * 17408), Nvfp4Experts.promptSmem(2, 4)); + try std.testing.expectEqual(@as(u32, 3 * 12800), Nvfp4Experts.promptSmem(1, 4)); +} + +test "a packed fp8 expert puts each word where fp8/experts.py's pack does" { + const gpa = std.testing.allocator; + const n = 128; + const k = 128; + const w = try gpa.alloc(u8, n * k); + defer gpa.free(w); + for (w, 0..) |*b, i| b.* = @truncate(i * 31 + 7); + const out = try gpa.alloc(u32, n * k / 4); + defer gpa.free(out); + Fp8Experts.packOne(out, w, n, k); + // (cb 1, g 2, gq 5, t 3, h 1, j 2): row 32 + 16 + 5 = 53, word 2 * 8 + 4 + 3 = 23 + const idx = (((((1 * 4 + 2) * 8 + 5) * 4 + 3) * 2 + 1) * 4) + 2; + const words = std.mem.bytesAsSlice(u32, @as([]align(1) const u8, w)); + try std.testing.expectEqual(words[53 * (k / 4) + 23], out[idx]); +} diff --git a/zig/src/cuda/experts_mx.zig b/zig/src/cuda/experts_mx.zig new file mode 100644 index 00000000000..448826ec853 --- /dev/null +++ b/zig/src/cuda/experts_mx.zig @@ -0,0 +1,223 @@ +//! Stored-format experts for Inkling 2 Mini: MXFP8 (fp8_experts.cu) and the soft-capped SwiGLU on NVFP4's kernels. +const std = @import("std"); +const module = @import("module.zig"); +const launch_ = @import("launch.zig"); +const stream_ = @import("stream.zig"); +const kernels = @import("kernels.zig"); +const driver = @import("driver.zig"); +const experts = @import("experts.zig"); + +const Module = module.Module; +const Function = module.Function; +const Stream = stream_.Stream; +const Plan = @import("grouped.zig").Plan; +const Layer = experts.Layer; +const Epi = experts.Epi; +const Rows = experts.Rows; + +/// NVFP4's per-expert factor: amax / denominator, each rounded to bf16 as the reference loads it (open question F1). +pub fn nvfp4Factor(amax: f32, denominator: f32) f32 { + return bf16(amax) / bf16(denominator); +} + +/// x rounded to bf16 (nearest, ties to even), as an f32; the checkpoint's amax values are finite. +fn bf16(x: f32) f32 { + const b: u32 = @bitCast(x); + return @bitCast((b +% 0x7FFF +% ((b >> 16) & 1)) & 0xFFFF0000); +} + +/// A layer's caps: both 0 (plain), or both positive and finite (soft-capped SwiGLU); refused where no kernel has them. +pub fn capsBuilt(l: Layer) !void { + if (l.caps[0] == 0 and l.caps[1] == 0) { + if (l.format == .mxfp8) return error.OptionNotBuilt; // MXFP8's gate-up is built soft-capped only + return; + } + for (l.caps) |c| if (!(c > 0 and c < std.math.inf(f32))) return error.BadSoftcap; + if (l.format != .nvfp4 and l.format != .mxfp8) return error.OptionNotBuilt; + if (l.relu2 or l.limit != 0 or l.swiglu or l.after) return error.OptionNotBuilt; + if (l.width % 32 != 0 or l.dims % 32 != 0) return error.UnexpectedShape; // whole blocks of 32 both ways +} + +/// An expert call's arguments as the soft-capped and MXFP8 entries take them; `scale` null for MXFP8 (in its blocks). +pub fn argsOf(in: Rows, gate: bool, w: u64, scale: ?u64, kg: usize, nb: usize, p: Plan, out: u64, n: usize, caps: [2]f32, skip: i32) launch_.Args { + var a: launch_.Args = .{}; + a.add(in.x); + a.add(@as(i32, @intCast(in.stride))); + a.add(@as(i32, @intCast(if (gate) in.slots else 0))); + a.add(w); + if (scale) |v| a.add(v); + a.add(@as(i32, @intCast(kg))); + a.add(@as(i32, @intCast(nb))); + for ([_]u64{ p.items, p.counts, p.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(caps[0]); + a.add(caps[1]); + a.add(skip); + return a; +} + +/// nvfp4_experts.cu's soft-capped SwiGLU gate-up: decode units of 4 warps, and the prompt tiles of 4 warps. +pub const Softcap = struct { + fns: [2]Function = undefined, // decode, prompt + resident: usize = 0, + + pub const symbols = [2][:0]const u8{ "tf_nvfp4_softcap", "tf_nvfp4_prompt_softcap" }; + pub const prompt_wn = 4; + + pub fn resolve(mod: Module, sms: usize) !Softcap { + var c: Softcap = .{}; + for (symbols, &c.fns) |name, *f| f.* = try mod.function(name); + try c.fns[1].allowDynamicShared(experts.Nvfp4Experts.promptSmem(2, prompt_wn)); + c.resident = @max(1, try c.fns[0].occupancy(128, 0)) * sms; + return c; + } + + /// Gate-up on a plan of at most `items` items (16 pairs decode, 64 prompt); capsBuilt checked the layer. + pub fn run(c: Softcap, s: Stream, prompt: bool, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { + const nb = l.width / 32; + var a = argsOf(in, true, l.up, l.up_scale, l.dims / 32, nb, p, out, l.width, l.caps, skip); + const grid = if (prompt) items * ((nb + prompt_wn - 1) / prompt_wn) else @min((items * nb + 3) / 4, c.resident); + if (grid < 1) return; + const smem: u32 = if (prompt) experts.Nvfp4Experts.promptSmem(2, prompt_wn) else 0; + const cfg: launch_.Config = .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 }, .shared = smem }; + try launch_.launch(c.fns[@intFromBool(prompt)], cfg, s, &a); + } +}; + +/// MXFP8 experts: e4m3 codes with one E8M0 scale per output row per 32 inputs, blocks of 32 columns by 32 inputs. +pub const Mxfp8Experts = struct { + mod: Module, + fns: [5]Function, // decode: soft-capped gate-up, fp32 down, bf16 down; prompt: soft-capped gate-up, bf16 down + resident: [3]usize, // the decode entries' blocks a grid may hold + + pub const words = 264; // int32 a block: fp8g's 256 code words ([32 lanes][2][4]), then 32 E8M0 bytes + pub const prompt_cw = [2]usize{ 2, 4 }; // column warps a prompt CTA: gate-up, down (64 pairs an item) + pub const symbols = [5][:0]const u8{ "tf_mxfp8_softcap", "tf_mxfp8_down_f32", "tf_mxfp8_down_bf16", "tf_mxfp8_prompt_softcap", "tf_mxfp8_prompt_down" }; + + pub fn load(d: *const driver.Driver, sms: usize) !Mxfp8Experts { + if (!kernels.available) return error.BuiltWithoutKernels; + var mod = try Module.load(d, kernels.fp8_experts); + errdefer mod.unload(); + var e: Mxfp8Experts = .{ .mod = mod, .fns = undefined, .resident = undefined }; + for (symbols, &e.fns) |name, *f| f.* = try mod.function(name); + for (&e.resident, 0..) |*r, i| r.* = @max(1, try e.fns[i].occupancy(128, 0)) * sms; + return e; + } + + pub fn unload(e: *Mxfp8Experts) void { + e.mod.unload(); + } + + /// The entry a call takes, or the refusal: prompt rows have no fp32 down. + pub fn entry(prompt: bool, epi: Epi) !usize { + return switch (epi) { + .up => if (prompt) 3 else 0, + .down_f32 => if (prompt) error.EpilogueNotBuilt else 1, + .down_bf16 => if (prompt) 4 else 2, + }; + } + + /// One call on a plan of at most `items` items (16 pairs decode, 64 prompt); the layer's caps already checked. + pub fn run(e: *const Mxfp8Experts, s: Stream, prompt: bool, epi: Epi, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { + const fi = try entry(prompt, epi); + const gate = epi == .up; + const n = if (gate) l.width else l.dims; + const k = if (gate) l.dims else l.width; + if (n % 32 != 0 or k % 32 != 0) return error.UnexpectedShape; + const nb = n / 32; + const cw = prompt_cw[@intFromBool(!gate)]; + if (prompt and nb % cw != 0) return error.UnexpectedShape; + const grid = if (prompt) items * (nb / cw) else @min((items * nb + 3) / 4, e.resident[fi]); + if (grid < 1) return; + var a = argsOf(in, gate, if (gate) l.up else l.down, null, k / 32, nb, p, out, n, l.caps, skip); + try launch_.launch(e.fns[fi], .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, s, &a); + } + + /// Bytes of `count` experts' blocks for n outputs from k inputs: [E][n/32][k/32][parts][264] int32. + pub fn bytes(count: usize, n: usize, k: usize, parts: usize) usize { + return count * (n / 32) * (k / 32) * parts * words * 4; + } + + /// One expert's e4m3 codes [n, k] and E8M0 scales [n, k/32] (row-major, as stored) as blocks [n/32][k/32][264]. + pub fn packOne(out: []u32, codes: []const u8, scales: []const u8, n: usize, k: usize) void { + packPart(out, 1, 0, codes, scales, n, k); + } + + /// Gate and up interleaved per (column block, k32 group): [n/32][k/32][2][264], each [codes, scales] as stored. + pub fn packGateUp(out: []u32, gate: [2][]const u8, up: [2][]const u8, n: usize, k: usize) void { + packPart(out, 2, 0, gate[0], gate[1], n, k); + packPart(out, 2, 1, up[0], up[1], n, k); + } + + /// Lane (gq, t)'s words [h][j]: row j * 8 + gq, inputs 16h + 4t .. + 3 (fp8g's order); scale byte 4 gq + j. + fn packPart(out: []u32, parts: usize, part: usize, codes: []const u8, scales: []const u8, n: usize, k: usize) void { + const kg = k / 32; + std.debug.assert(n % 32 == 0 and k % 32 == 0 and out.len == n / 32 * kg * parts * words and part < parts); + std.debug.assert(codes.len == n * k and scales.len == n * kg); + for (0..n / 32) |cb| for (0..kg) |g| { + const block = out[((cb * kg + g) * parts + part) * words ..][0..words]; + for (0..8) |gq| for (0..4) |t| for (0..2) |h| for (0..4) |j| { + const row = cb * 32 + j * 8 + gq; + const at = row * k + g * 32 + h * 16 + t * 4; + block[((gq * 4 + t) * 2 + h) * 4 + j] = std.mem.readInt(u32, codes[at..][0..4], .little); + }; + const sc = std.mem.sliceAsBytes(block[256..]); + for (0..8) |gq| for (0..4) |j| { + sc[gq * 4 + j] = scales[(cb * 32 + j * 8 + gq) * kg + g]; + }; + }; + } +}; + +test "the NVFP4 factor rounds amax and the denominator to bf16 before it divides" { + const amax: f32 = 0.3310546875 + 0x1p-12; // not a bf16 + const want = @as(f32, 0.33203125) / 2688.0; // bf16(amax) is 0.33203125; 2688 = 6 x 448 is a bf16 + try std.testing.expectEqual(want, nvfp4Factor(amax, 2688)); + try std.testing.expect(nvfp4Factor(amax, 2688) != amax / 2688); +} + +test "a packed MXFP8 block holds fp8g's code words and each row's scale at byte 4 gq + j" { + const gpa = std.testing.allocator; + const n = 64; + const k = 96; + const codes = try gpa.alloc(u8, n * k); + defer gpa.free(codes); + for (codes, 0..) |*c, i| c.* = @truncate(i * 31 + 7); + var scales: [n * k / 32]u8 = undefined; + for (&scales, 0..) |*c, i| c.* = @truncate(i * 13 + 5); + const out = try gpa.alloc(u32, Mxfp8Experts.bytes(1, n, k, 1) / 4); + defer gpa.free(out); + Mxfp8Experts.packOne(out, codes, &scales, n, k); + // the code words of every block are Fp8Experts.packOne's order (fp8_experts.cu's lane loads) + for (0..n / 32) |cb| for (0..k / 32) |g| for (0..8) |gq| for (0..4) |t| for (0..2) |h| for (0..4) |j| { + const row = cb * 32 + j * 8 + gq; + const w = std.mem.readInt(u32, codes[row * k + g * 32 + h * 16 + t * 4 ..][0..4], .little); + try std.testing.expectEqual(w, out[(cb * (k / 32) + g) * Mxfp8Experts.words + ((gq * 4 + t) * 2 + h) * 4 + j]); + }; + // block (cb 1, g 2): row 32 + 8 j + gq's scale for group 2 at byte 4 gq + j of the block's last 32 + const sc = std.mem.sliceAsBytes(out[(1 * 3 + 2) * Mxfp8Experts.words + 256 ..][0..8]); + for (0..8) |gq| for (0..4) |j| try std.testing.expectEqual(scales[(32 + 8 * j + gq) * 3 + 2], sc[gq * 4 + j]); +} + +test "packGateUp stacks gate then up per (column block, k32 group)" { + const n = 32; + const k = 64; + var codes: [2][n * k]u8 = undefined; + var scales: [2][n * k / 32]u8 = undefined; + for (0..2) |m| { + for (&codes[m], 0..) |*c, i| c.* = @truncate(i * 29 + 3 + m * 101); + for (&scales[m], 0..) |*c, i| c.* = @truncate(i * 7 + 1 + m * 13); + } + var one: [2][Mxfp8Experts.bytes(1, n, k, 1) / 4]u32 = undefined; + for (0..2) |m| Mxfp8Experts.packOne(&one[m], &codes[m], &scales[m], n, k); + var both: [2 * one[0].len]u32 = undefined; + Mxfp8Experts.packGateUp(&both, .{ &codes[0], &scales[0] }, .{ &codes[1], &scales[1] }, n, k); + const w = Mxfp8Experts.words; + for (0..one[0].len / w) |b| for (0..2) |m| { + try std.testing.expectEqualSlices(u32, one[m][b * w ..][0..w], both[(2 * b + m) * w ..][0..w]); + }; +} + +test { + _ = @import("experts_mx_test.zig"); // dispatch, arguments and refusals on a mock launcher +} diff --git a/zig/src/cuda/experts_mx_test.zig b/zig/src/cuda/experts_mx_test.zig new file mode 100644 index 00000000000..d8460b35c5f --- /dev/null +++ b/zig/src/cuda/experts_mx_test.zig @@ -0,0 +1,133 @@ +//! Stored-format experts on a mock launcher: the entry each call takes, its arguments, refusals that launch none. +const std = @import("std"); +const abi = @import("abi.zig"); +const experts = @import("experts.zig"); +const mx = @import("experts_mx.zig"); +const Driver = @import("driver.zig").Driver; +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; +const Plan = @import("grouped.zig").Plan; + +const Mock = struct { + var launches: usize = 0; + var selected: usize = 0; + var grid: u32 = 0; + var shared: u32 = 0; + var words: [16]u64 = undefined; + fn launch(f: abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, sm: c_uint, _: abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) abi.Result { + launches += 1; + selected = @intFromPtr(f.?); + grid = gx; + shared = sm; + // the soft-capped NVFP4 entry has 15 arguments, the MXFP8 ones 14 (no scale pointer) + const wide = [_]usize{ 0, 3, 4, 7, 8, 9, 10 }; + const n: usize = if (selected < 40) 15 else 14; + for (0..n) |i| { + const big = if (selected < 40) std.mem.indexOfScalar(usize, &wide, i) != null else std.mem.indexOfScalar(usize, &[_]usize{ 0, 3, 6, 7, 8, 9 }, i) != null; + words[i] = if (big) @as(*const u64, @ptrCast(@alignCast(params.?[i].?))).* else @as(*const u32, @ptrCast(@alignCast(params.?[i].?))).*; + } + return 0; + } +}; + +const plan: Plan = .{ .items = 60, .counts = 70, .members = 80, .rank = 90, .hist = 100 }; +const in_up: experts.Rows = .{ .x = 10, .stride = 2304, .slots = 8 }; +const mini: experts.Layer = .{ .format = .nvfp4, .up = 20, .down = 30, .up_scale = 40, .down_scale = 50, .width = 1152, .dims = 2304, .experts = 128, .caps = .{ 4, 25 } }; + +fn kernelsOn(d: *Driver) struct { k4: experts.Nvfp4Experts, k8: mx.Mxfp8Experts } { + d.api.cuLaunchKernel = Mock.launch; + var k4: experts.Nvfp4Experts = undefined; // only the soft-capped entries are reachable from the calls below + k4.softcap = .{ .fns = .{ .{ .d = d, .handle = @ptrFromInt(31) }, .{ .d = d, .handle = @ptrFromInt(32) } }, .resident = 96 }; + var k8: mx.Mxfp8Experts = .{ .mod = undefined, .fns = undefined, .resident = @splat(96) }; + for (&k8.fns, 0..) |*f, i| f.* = .{ .d = d, .handle = @ptrFromInt(41 + i) }; + return .{ .k4 = k4, .k8 = k8 }; +} + +test "soft-capped NVFP4 gate-up takes tf_nvfp4_softcap with both caps; prompt rows the prompt entry and its shared" { + var d: Driver = undefined; + const k = kernelsOn(&d); + const g: experts.Grouped = .{ .nvfp4 = &k.k4 }; + const s: Stream = .{ .d = &d, .handle = null }; + try g.decode(s, .up, in_up, mini, plan, 110, 5, 32, 16, -1); + try std.testing.expectEqual(@as(usize, 31), Mock.selected); + try std.testing.expectEqual(@as(u32, (5 * 36 + 3) / 4), Mock.grid); + try std.testing.expectEqual(@as(u64, 8), Mock.words[2]); // slots + try std.testing.expectEqual(@as(u64, 40), Mock.words[4]); // the per-expert factors + try std.testing.expectEqual(@as(u64, 2304 / 32), Mock.words[5]); + try std.testing.expectEqual(@as(u64, 1152 / 32), Mock.words[6]); + try std.testing.expectEqual(@as(u32, @bitCast(@as(f32, 4))), @as(u32, @truncate(Mock.words[12]))); + try std.testing.expectEqual(@as(u32, @bitCast(@as(f32, 25))), @as(u32, @truncate(Mock.words[13]))); + try std.testing.expectEqual(@as(u64, @as(u32, @bitCast(@as(i32, -1)))), Mock.words[14]); + try g.prompt(s, .up, in_up, mini, plan, 110, 3, 192, 64, 7); + try std.testing.expectEqual(@as(usize, 32), Mock.selected); + try std.testing.expectEqual(@as(u32, 3 * 9), Mock.grid); + try std.testing.expectEqual(experts.Nvfp4Experts.promptSmem(2, 4), Mock.shared); + try std.testing.expectEqual(@as(u64, 7), Mock.words[14]); +} + +test "MXFP8 calls take their entry by form and epilogue, with no scale pointer and the layer's caps" { + var d: Driver = undefined; + const k = kernelsOn(&d); + const g: experts.Grouped = .{ .mxfp8 = &k.k8 }; + const s: Stream = .{ .d = &d, .handle = null }; + var l = mini; + l.format = .mxfp8; + const in_down: experts.Rows = .{ .x = 11, .stride = 1152 }; + const cases = [_]struct { prompt: bool, epi: experts.Epi, want: usize, grid: u32, kg: u64, nb: u64 }{ + .{ .prompt = false, .epi = .up, .want = 41, .grid = (5 * 36 + 3) / 4, .kg = 72, .nb = 36 }, + .{ .prompt = false, .epi = .down_f32, .want = 42, .grid = (5 * 72 + 3) / 4, .kg = 36, .nb = 72 }, + .{ .prompt = false, .epi = .down_bf16, .want = 43, .grid = (5 * 72 + 3) / 4, .kg = 36, .nb = 72 }, + .{ .prompt = true, .epi = .up, .want = 44, .grid = 5 * 18, .kg = 72, .nb = 36 }, + .{ .prompt = true, .epi = .down_bf16, .want = 45, .grid = 5 * 18, .kg = 36, .nb = 72 }, + }; + for (cases) |c| { + const in = if (c.epi == .up) in_up else in_down; + if (c.prompt) try g.prompt(s, c.epi, in, l, plan, 110, 5, 40, 64, -1) else try g.decode(s, c.epi, in, l, plan, 110, 5, 40, 16, -1); + try std.testing.expectEqual(c.want, Mock.selected); + try std.testing.expectEqual(c.grid, Mock.grid); + try std.testing.expectEqual(@as(u64, if (c.epi == .up) 8 else 0), Mock.words[2]); + try std.testing.expectEqual(@as(u64, if (c.epi == .up) 20 else 30), Mock.words[3]); + try std.testing.expectEqual(c.kg, Mock.words[4]); + try std.testing.expectEqual(c.nb, Mock.words[5]); + try std.testing.expectEqual(@as(u32, @bitCast(@as(f32, 25))), @as(u32, @truncate(Mock.words[12]))); + } +} + +test "refusals by name launch nothing: MXFP8 not loaded, caps unbuilt or malformed, shapes, prompt fp32 down" { + var d: Driver = undefined; + const k = kernelsOn(&d); + const s: Stream = .{ .d = &d, .handle = null }; + const none: experts.Grouped = .{}; + const both: experts.Grouped = .{ .nvfp4 = &k.k4, .mxfp8 = &k.k8 }; + Mock.launches = 0; + var l = mini; + l.format = .mxfp8; + try std.testing.expectError(error.FormatNotLoaded, none.decode(s, .up, in_up, l, plan, 0, 1, 8, 16, -1)); + try std.testing.expectError(error.FormatNotLoaded, none.prompt(s, .down_bf16, in_up, l, plan, 0, 1, 8, 64, -1)); + try std.testing.expectError(error.EpilogueNotBuilt, both.prompt(s, .down_f32, in_up, l, plan, 0, 1, 8, 64, -1)); + l.caps = .{ 0, 0 }; // MXFP8's gate-up is built soft-capped only + try std.testing.expectError(error.OptionNotBuilt, both.decode(s, .up, in_up, l, plan, 0, 1, 8, 16, -1)); + for ([_][2]f32{ .{ 4, 0 }, .{ -4, 25 }, .{ 4, std.math.inf(f32) }, .{ std.math.nan(f32), 25 } }) |cp| { + l.caps = cp; + try std.testing.expectError(error.BadSoftcap, both.decode(s, .up, in_up, l, plan, 0, 1, 8, 16, -1)); + } + for (std.enums.values(experts.Format)) |f| if (f != .nvfp4 and f != .mxfp8) { + var o = mini; + o.format = f; + try std.testing.expectError(error.OptionNotBuilt, both.decode(s, .up, in_up, o, plan, 0, 1, 8, 16, -1)); + try std.testing.expectError(error.OptionNotBuilt, both.prompt(s, .up, in_up, o, plan, 0, 1, 8, 64, -1)); + }; + var r = mini; + r.relu2 = true; + try std.testing.expectError(error.OptionNotBuilt, both.decode(s, .up, in_up, r, plan, 0, 1, 8, 16, -1)); + r = mini; + r.limit = 7; + try std.testing.expectError(error.OptionNotBuilt, both.prompt(s, .up, in_up, r, plan, 0, 1, 8, 64, -1)); + r = mini; + r.width = 1144; + try std.testing.expectError(error.UnexpectedShape, both.decode(s, .up, in_up, r, plan, 0, 1, 8, 16, -1)); + r.format = .mxfp8; + r.width = 1152 + 32; // 37 column blocks: the prompt gate-up takes 2 a CTA + try std.testing.expectError(error.UnexpectedShape, both.prompt(s, .up, in_up, r, plan, 0, 1, 8, 64, -1)); + try std.testing.expectEqual(@as(usize, 0), Mock.launches); +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 263fce038dd..f93081e1390 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -55,6 +55,7 @@ pub const kda = @import("kda.zig"); pub const gdn_prep = @import("gdn_prep.zig"); pub const qk_rows = @import("qk_rows.zig"); pub const experts = @import("experts.zig"); +pub const experts_mx = @import("experts_mx.zig"); pub const affine_experts = @import("affine_experts.zig"); pub const experts32 = @import("experts32.zig"); pub const experts_waves = @import("experts_waves.zig"); @@ -116,6 +117,7 @@ test { _ = @import("experts.zig"); _ = @import("experts32.zig"); _ = @import("experts_waves.zig"); + _ = @import("experts_mx.zig"); _ = @import("sample.zig"); _ = @import("roce.zig"); _ = @import("roce_nap.zig"); diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 6b5c4f505f6..6230db3ee8a 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -11,6 +11,7 @@ const Grouped = @import("contract_gb10_many.zig").Registrations; pub const Sets = struct { gpa: std.mem.Allocator, bf16_experts: *@import("contract_experts_bf16.zig").Set, + stored_experts: *@import("contract_stored_experts.zig").Set, pocket: *@import("contract_pocket.zig").Set, minimax: *@import("contract_minimax.zig").Set, inkling2: *@import("contract_inkling2.zig").Set, @@ -31,6 +32,8 @@ pub const Sets = struct { pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel), affine4: *cuda.qlinear.Affine4Kernels, cap: u32) !Sets { const bf16_experts = try @import("contract_experts_bf16.zig").Set.init(gpu, s, a, list); errdefer bf16_experts.deinit(); + const stored_experts = try @import("contract_stored_experts.zig").Set.init(gpu, s, a, list); + errdefer stored_experts.deinit(); const pocket = try @import("contract_pocket.zig").Set.init(gpu, s, a, list); errdefer pocket.deinit(); const minimax = try @import("contract_minimax.zig").Set.init(gpu, s, a, list); @@ -74,6 +77,7 @@ pub const Sets = struct { return .{ .gpa = gpu.gpa, .bf16_experts = bf16_experts, + .stored_experts = stored_experts, .pocket = pocket, .minimax = minimax, .inkling2 = inkling2, @@ -110,6 +114,7 @@ pub const Sets = struct { sets.inkling2.deinit(); sets.minimax.deinit(); sets.pocket.deinit(); + sets.stored_experts.deinit(); sets.bf16_experts.deinit(); } }; diff --git a/zig/tests/cuda/contract_stored_experts.zig b/zig/tests/cuda/contract_stored_experts.zig new file mode 100644 index 00000000000..9c6c8509371 --- /dev/null +++ b/zig/tests/cuda/contract_stored_experts.zig @@ -0,0 +1,422 @@ +//! Inkling 2 Mini's stored experts under the contract: NVFP4 and MXFP8 on Mini's shapes, soft-capped SwiGLU, controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; +const dec = core.expert_decode; + +pub const Format = enum { nvfp4, mxfp8 }; +pub const Kind = enum { up, down_f32, down_bf16 }; + +pub const Entry = struct { name: []const u8, format: Format, kind: Kind, prompt: bool, short: bool = false }; + +/// Every new entry point, the reused NVFP4 downs at Mini's shapes, and a one-group-short control per new entry. +pub const entries = [_]Entry{ + .{ .name = "cuda stored experts nvfp4 tf_nvfp4_softcap (soft-capped SwiGLU)", .format = .nvfp4, .kind = .up, .prompt = false }, + .{ .name = "cuda stored experts nvfp4 tf_nvfp4_prompt_softcap", .format = .nvfp4, .kind = .up, .prompt = true }, + .{ .name = "cuda stored experts nvfp4 decode down f32 (Mini's factor)", .format = .nvfp4, .kind = .down_f32, .prompt = false }, + .{ .name = "cuda stored experts nvfp4 prompt down bf16 (Mini's factor)", .format = .nvfp4, .kind = .down_bf16, .prompt = true }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_softcap", .format = .mxfp8, .kind = .up, .prompt = false }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_down_f32", .format = .mxfp8, .kind = .down_f32, .prompt = false }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_down_bf16", .format = .mxfp8, .kind = .down_bf16, .prompt = false }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_prompt_softcap", .format = .mxfp8, .kind = .up, .prompt = true }, + .{ .name = "cuda stored experts mxfp8 tf_mxfp8_prompt_down", .format = .mxfp8, .kind = .down_bf16, .prompt = true }, + .{ .name = "control: tf_nvfp4_softcap one 32-input group short", .format = .nvfp4, .kind = .up, .prompt = false, .short = true }, + .{ .name = "control: tf_nvfp4_prompt_softcap one 32-input group short", .format = .nvfp4, .kind = .up, .prompt = true, .short = true }, + .{ .name = "control: tf_mxfp8_softcap one 32-input group short", .format = .mxfp8, .kind = .up, .prompt = false, .short = true }, + .{ .name = "control: tf_mxfp8_down_f32 one 32-input group short", .format = .mxfp8, .kind = .down_f32, .prompt = false, .short = true }, + .{ .name = "control: tf_mxfp8_down_bf16 one 32-input group short", .format = .mxfp8, .kind = .down_bf16, .prompt = false, .short = true }, + .{ .name = "control: tf_mxfp8_prompt_softcap one 32-input group short", .format = .mxfp8, .kind = .up, .prompt = true, .short = true }, + .{ .name = "control: tf_mxfp8_prompt_down one 32-input group short", .format = .mxfp8, .kind = .down_bf16, .prompt = true, .short = true }, +}; + +const experts = 4; +const slots = 8; // Mini's top-8 +pub const caps = [2]f32{ 4.0, 25.0 }; // Mini's mlp_gate_softcap, mlp_up_softcap + +/// An mma k16 step a link of each row's chain, its own error (mma_step), and NVFP4's block-scale fma and factor. +fn depth(s: c.Shape) usize { + return s.k / 16 + core.attention_range.mma_step + 2; +} + +/// Mini's experts: 2,304 to 1,152 (gate and up each) and back; decode 1 and 4 tokens, prompt items of 9 and 16 tokens. +const ups = [2][]const c.Shape{ &.{ .{ .rows = 1, .n = 1152, .k = 2304 }, .{ .rows = 4, .n = 1152, .k = 2304 } }, &.{ .{ .rows = 9, .n = 1152, .k = 2304 }, .{ .rows = 16, .n = 1152, .k = 2304 } } }; +const downs = [2][]const c.Shape{ &.{ .{ .rows = 1, .n = 2304, .k = 1152 }, .{ .rows = 4, .n = 2304, .k = 1152 } }, &.{ .{ .rows = 9, .n = 2304, .k = 1152 }, .{ .rows = 16, .n = 2304, .k = 1152 } } }; + +pub fn spec(e: Entry) c.Spec { + const up = e.kind == .up; + const served = (if (up) ups else downs)[@intFromBool(e.prompt)]; + // MXFP8's prompt CTAs take 2 (gate-up) or 4 (down) column blocks of 32 + const n_tile: c.Tile = if (e.format == .mxfp8 and e.prompt) (if (up) .{ .size = 128, .step = 64, .min = 64 } else .{ .size = 256, .step = 128, .min = 128 }) else .{ .size = 64, .step = 32, .min = 32 }; + const tiles = [3]c.Tile{ .{ .size = (if (e.prompt) ex_.promptTile(.nvfp4) else 16) / slots }, n_tile, .{ .size = 64, .step = 32, .min = 32 } }; + return switch (e.kind) { + // fp32 tanhf, expf and the divisions after the sums: a few ulps each + .up => .{ .name = e.name, .accum = .f32, .depth = depth, .ops = 16, .out = .bf16, .tiles = tiles, .served = served, .sums = .{ .f16 = 30, .bf16 = 30, .why = "the caps saturate: a replay's sum far off can land on the same plateau, so only 30x is provable" } }, + .down_f32 => .{ .name = e.name, .accum = .f32, .depth = depth, .out = .f32, .tiles = tiles, .served = served }, + .down_bf16 => .{ .name = e.name, .accum = .f32, .depth = depth, .out = .bf16, .tiles = tiles, .served = served }, + }; +} + +/// gc tanh(g / gc) sigmoid(g) uc tanh(u / uc) in float64, and its partial derivatives in g and u. +pub fn softcap(gs: f64, us: f64) [3]f64 { + const gc: f64 = caps[0]; + const uc: f64 = caps[1]; + const tg = std.math.tanh(gs / gc); + const e = @exp(-@abs(gs)); + const sg = if (gs >= 0) 1 / (1 + e) else e / (1 + e); + const tu = std.math.tanh(us / uc); + const a = gc * tg * sg; + const b = uc * tu; + const da = (1 - tg * tg) * sg + gc * tg * sg * (1 - sg); + return .{ a * b, da * b, a * (1 - tu * tu) }; +} + +/// shape.rows token rows, `slots` pairs each over `experts` experts; up reads a token's row, down a pair's. +pub const Experts = struct { + rig: rig_.Rig, + entry: Entry, + k4: *const ex_.Nvfp4Experts, + k8: *const mx.Mxfp8Experts, + router: grouped.Router, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []f32 = &.{}, // [M][experts][n][k] stored weights decoded, less NVFP4's factor (exact in f32) + factor: [2][experts]f64 = undefined, // NVFP4's per-expert factor by matrix (1 for MXFP8) + picks: []i32 = &.{}, + xd: u64 = 0, + wd: u64 = 0, + sd: u64 = 0, + plan: grouped.Plan = undefined, + out: u64 = 0, + + pub fn deinit(self: *Experts) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Experts) void { + const a = self.rig.gpu.gpa; + a.free(self.x); + a.free(self.w); + a.free(self.picks); + self.x = &.{}; + self.w = &.{}; + self.picks = &.{}; + } + + pub fn kernel(self: *Experts) g.Kernel { + return .{ .spec = spec(self.entry), .ctx = self, .vt = &vt, .control = if (self.entry.short) .shapes else null }; + } + + const vt = g.hooks(Experts); + + fn up(self: *const Experts) bool { + return self.entry.kind == .up; + } + + fn parts(self: *const Experts) usize { + return if (self.up()) 2 else 1; + } + + fn pairs(self: *const Experts) usize { + return self.shape.rows * slots; + } + + fn xRows(self: *const Experts) usize { + return if (self.up()) self.shape.rows else self.pairs(); + } + + fn tile(self: *const Experts) usize { + return if (self.entry.prompt) ex_.promptTile(.nvfp4) else 16; + } + + fn items(self: *const Experts) usize { + return grouped.maxItems(self.pairs(), experts, self.tile()); + } + + fn layer(self: *const Experts) ex_.Layer { + const n = self.shape.n; + const k = self.shape.k; + return .{ .format = if (self.entry.format == .nvfp4) .nvfp4 else .mxfp8, .up = self.wd, .down = self.wd, .up_scale = self.sd, .down_scale = self.sd, .width = if (self.up()) n else k, .dims = if (self.up()) k else n, .experts = experts, .caps = caps }; + } + + /// Random stored codes and scales; non-finite: NaN, +Inf and -Inf in the first rows; stress: mirrored integers. + pub fn prepare(self: *Experts, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 32 != 0 or shape.k == 0 or shape.k % 32 != 0) return false; + if (self.entry.format == .mxfp8 and self.entry.prompt and shape.n % (32 * mx.Mxfp8Experts.prompt_cw[@intFromBool(!self.up())]) != 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + const n = shape.n; + const k = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.x = try a.alloc(u16, self.xRows() * k); + self.w = try a.alloc(f32, self.parts() * experts * n * k); + self.picks = try a.alloc(i32, self.pairs()); + for (self.x) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + for (self.picks, 0..) |*p, i| p.* = @intCast(if (i < experts) i else rng.uintLessThan(usize, experts)); + const stress = fill == .stress; + const nv = self.entry.format == .nvfp4; + const cbytes = if (nv) n * k / 2 else n * k; + const sbytes = if (nv) n * k / 16 else n * k / 32; + const codes = try a.alloc(u8, self.parts() * experts * cbytes); + defer a.free(codes); + const scales = try a.alloc(u8, self.parts() * experts * sbytes); + defer a.free(scales); + for (codes, 0..) |*b, i| b.* = if (stress) (if (nv) @as(u8, if (i % 3 == 0) 0x42 else 0x24) else @as(u8, if (i % 3 == 0) 0x40 else 0x38)) else rng.int(u8); + if (!nv and !stress) for (codes) |*b| if (b.* & 0x7F == 0x7F) { + b.* ^= 1; // no NaN codes + }; + // E4M3 scales 2^-3 .. 2^3, E8M0 2^-11 .. 2^-7: a few units a sum; stress 1, MXFP8 down 8 (fp16 lanes overflow) + for (scales) |*b| b.* = if (stress) (if (nv) 0x38 else if (self.up()) @as(u8, 127) else 130) else if (nv) 0x20 + rng.uintLessThan(u8, 0x30) else 116 + rng.uintLessThan(u8, 5); + for (0..2) |m| for (0..experts) |e| { + const amax: f32 = if (stress) 2688 else 64 + rng.float(f32) * 256; + self.factor[m][e] = if (nv) mx.nvfp4Factor(amax, 2688) else 1; + }; + if (stress) self.mirror(codes, cbytes); + for (0..self.parts() * experts) |me| for (0..n) |row| for (0..k) |i| { + const cs = codes[me * cbytes ..][0..cbytes]; + const ss = scales[me * sbytes ..][0..sbytes]; + self.w[(me * n + row) * k + i] = @floatCast(if (nv) dec.nvfp4(cs, ss, k, row, i, 1) else dec.mxfp8(cs, ss, k, row, i)); + }; + if (fill == .nonfinite) { + // a row holding NaN, one holding +Inf, one holding both infinities + const planted = [_]struct { usize, usize, f32 }{ .{ 0, k / 3, std.math.nan(f32) }, .{ 1, k / 2, std.math.inf(f32) }, .{ 2, 1, std.math.inf(f32) }, .{ 2, k - 1, -std.math.inf(f32) } }; + for (planted) |p| if (p[0] < self.xRows()) { + self.x[p[0] * k + p[1]] = c.toBf16(p[2]); + }; + } + if (stress) self.stressRows(rng); + try self.upload(codes, scales, cbytes, sbytes); + return true; + } + + /// The packed blocks, the factors, the plan and the output. + fn upload(self: *Experts, codes: []const u8, scales: []const u8, cbytes: usize, sbytes: usize) !void { + const a = self.rig.gpu.gpa; + const n = self.shape.n; + const k = self.shape.k; + const nv = self.entry.format == .nvfp4; + const per = (if (nv) ex_.Nvfp4Experts.bytes(1, n, k, self.parts()) else mx.Mxfp8Experts.bytes(1, n, k, self.parts())) / 4; + const blocks = try a.alloc(u32, experts * per); + defer a.free(blocks); + for (0..experts) |e| { + const out = blocks[e * per ..][0..per]; + var cs: [2][]const u8 = undefined; + var ss: [2][]const u8 = undefined; + for (0..self.parts()) |m| { + cs[m] = codes[(m * experts + e) * cbytes ..][0..cbytes]; + ss[m] = scales[(m * experts + e) * sbytes ..][0..sbytes]; + } + if (nv and self.up()) ex_.Nvfp4Experts.packGateUp(out, .{ cs[0], ss[0] }, .{ cs[1], ss[1] }, n, k); + if (nv and !self.up()) ex_.Nvfp4Experts.packOne(out, cs[0], ss[0], n, k); + if (!nv and self.up()) mx.Mxfp8Experts.packGateUp(out, .{ cs[0], ss[0] }, .{ cs[1], ss[1] }, n, k); + if (!nv and !self.up()) mx.Mxfp8Experts.packOne(out, cs[0], ss[0], n, k); + } + self.wd = try self.rig.input(std.mem.sliceAsBytes(blocks)); + var f: [experts * 2]f32 = undefined; + for (0..experts) |e| for (0..self.parts()) |m| { + f[e * self.parts() + m] = @floatCast(self.factor[m][e]); + }; + self.sd = try self.rig.input(std.mem.sliceAsBytes(f[0 .. experts * self.parts()])); + self.xd = try self.rig.input(std.mem.sliceAsBytes(self.x)); + const zeros = try a.alloc(u8, @max(self.pairs() * 4, self.items() * 12, 8)); + defer a.free(zeros); + @memset(zeros, 0); + const ids = try self.rig.input(std.mem.sliceAsBytes(self.picks)); + const hist = (self.pairs() + 1023) / 1024; + self.plan = .{ .members = try self.rig.input(zeros[0 .. self.pairs() * 4]), .items = try self.rig.input(zeros[0 .. self.items() * 12]), .counts = try self.rig.input(zeros[0..8]), .rank = try self.rig.scratch(self.pairs() * 4), .hist = try self.rig.scratch(hist * experts * 4) }; + try self.router.route(self.rig.s, ids, self.pairs(), experts, self.tile(), self.plan); + try self.rig.s.synchronize(); + self.out = try self.rig.output(self.pairs() * n * c.size(spec(self.entry).out)); + } + + /// Gate 4's weights: input k - 1 - i repeats input i (weights 1 and 2; MXFP8 down 8, 16). so twins sit in + /// different 32-input lanes and no replay order cancels them early. + fn mirror(self: *Experts, codes: []u8, cbytes: usize) void { + const k = self.shape.k; + const nv = self.entry.format == .nvfp4; + const row = if (nv) k / 2 else k; + for (0..self.parts() * experts * (cbytes / row)) |r| { + const b = codes[r * row ..][0..row]; + for (0..row / 2) |j| b[row - 1 - j] = if (nv) (b[j] >> 4) | (b[j] << 4) else b[j]; + } + } + + /// Gate 4's rows: input k - 1 - i is minus input i, input k - 1 is 4 - x_0: each sum is 4 w_0, partials under 2^23. + fn stressRows(self: *Experts, rng: std.Random) void { + const k = self.shape.k; + for (0..self.xRows()) |r| for (0..k / 2) |i| { + const v: f32 = @floatFromInt(4 * (1 + 2 * rng.uintLessThan(u32, 64))); + self.x[r * k + i] = c.toBf16(v); + self.x[r * k + k - 1 - i] = c.toBf16(if (i == 0) 4 - v else -v); // a multiple of 8: exact in bf16 + }; + } + + pub fn run(self: *Experts) !void { + const l = self.layer(); + const in: ex_.Rows = .{ .x = self.xd, .stride = self.shape.k, .slots = if (self.up()) slots else 0 }; + if (self.entry.short) return self.short(l, in); + const epi: ex_.Epi = switch (self.entry.kind) { + .up => .up, + .down_f32 => .down_f32, + .down_bf16 => .down_bf16, + }; + const gx: ex_.Grouped = .{ .nvfp4 = self.k4, .mxfp8 = self.k8 }; + if (self.entry.prompt) { + try gx.prompt(self.rig.s, epi, in, l, self.plan, self.out, self.items(), self.pairs(), 64, -1); + } else try gx.decode(self.rig.s, epi, in, l, self.plan, self.out, self.items(), self.pairs(), 16, -1); + try self.rig.s.synchronize(); + } + + /// The control: the entry's own launch with one k32 group fewer than the layer has. + fn short(self: *Experts, l: ex_.Layer, in: ex_.Rows) !void { + const up_ = self.up(); + const n = self.shape.n; + const nb = n / 32; + const kg = self.shape.k / 32 - 1; + const nv = self.entry.format == .nvfp4; + var a = mx.argsOf(in, up_, self.wd, if (nv) self.sd else null, kg, nb, self.plan, self.out, n, l.caps, -1); + var cfg: cuda.Config = .{ .grid = .{ .x = @intCast((self.items() * nb + 3) / 4) }, .block = .{ .x = 128 } }; + const f = if (nv) self.k4.softcap.fns[@intFromBool(self.entry.prompt)] else self.k8.fns[ + try mx.Mxfp8Experts.entry(self.entry.prompt, switch (self.entry.kind) { + .up => .up, + .down_f32 => .down_f32, + .down_bf16 => .down_bf16, + }) + ]; + if (self.entry.prompt and nv) { + cfg.grid.x = @intCast(self.items() * ((nb + 3) / 4)); + cfg.shared = ex_.Nvfp4Experts.promptSmem(2, mx.Softcap.prompt_wn); + } else if (self.entry.prompt) cfg.grid.x = @intCast(self.items() * (nb / mx.Mxfp8Experts.prompt_cw[@intFromBool(!up_)])); + try cuda.launch.launch(f, cfg, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Experts) usize { + return self.pairs() * self.shape.n; + } + + /// Pair p's products with column j of matrix m of its expert, in input order, and that matrix's factor. + fn terms(self: *const Experts, m: usize, p: usize, j: usize, t: []f64) f64 { + const k = self.shape.k; + const xr = (if (self.up()) p / slots else p) * k; + const e: usize = @intCast(self.picks[p]); + const wr = ((m * experts + e) * self.shape.n + j) * k; + for (t, 0..) |*o, i| o.* = c.fromBf16(self.x[xr + i]) * @as(f64, self.w[wr + i]); + return self.factor[m][e]; + } + + pub fn reference(self: *Experts, want: []f64, mag: []f64) !void { + const t = try self.rig.gpu.gpa.alloc(f64, self.shape.k); + defer self.rig.gpu.gpa.free(t); + for (0..self.pairs()) |p| for (0..self.shape.n) |j| { + var sum: [2]f64 = .{ 0, 0 }; + var abs: [2]f64 = .{ 0, 0 }; + for (0..self.parts()) |m| { + const f = self.terms(m, p, j, t); + for (t) |v| { + sum[m] += v; + abs[m] += @abs(v); + } + sum[m] *= f; + abs[m] *= f; + } + const o = p * self.shape.n + j; + if (self.up()) { + const r = softcap(sum[0], sum[1]); + want[o] = r[0]; + mag[o] = @abs(r[1]) * abs[0] + @abs(r[2]) * abs[1]; // the sums' errors through the slopes + } else { + want[o] = sum[0]; + mag[o] = abs[0]; + } + }; + } + + pub fn simulate(self: *Experts, acc: c.Accum, order: g.Order, out: []f64) !void { + const t = try self.rig.gpu.gpa.alloc(f64, self.shape.k); + defer self.rig.gpu.gpa.free(t); + for (0..self.pairs()) |p| for (0..self.shape.n) |j| { + var sum: [2]f64 = .{ 0, 0 }; + for (0..self.parts()) |m| { + const f = self.terms(m, p, j, t); + sum[m] = contract.rows.sumIn(acc, order, t) * f; + } + out[p * self.shape.n + j] = if (self.up()) softcap(sum[0], sum[1])[0] else sum[0]; + }; + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + k4: ex_.Nvfp4Experts, + k8: mx.Mxfp8Experts, + mod: cuda.Module, + items: [entries.len]Experts = undefined, + + /// The set, its kernels appended to `list` (each control after the kernels it breaks). + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + errdefer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + errdefer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + errdefer mod.unload(); + set.* = .{ .gpa = gpu.gpa, .k4 = k4, .k8 = k8, .mod = mod }; + const router = try grouped.Router.resolve(set.mod); + for (&set.items, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .k4 = &set.k4, .k8 = &set.k8, .router = router }; + for (&set.items) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.items) |*x| x.deinit(); + set.mod.unload(); + set.k8.unload(); + set.k4.unload(); + set.gpa.destroy(set); + } +}; + +/// The stored experts' gates 1-4 and their controls alone. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x6d696e69, &t); + std.debug.print("SUMMARY stored experts: {d} kernels, {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed }); + try check.expect(t.problems() == 0, "stored-experts contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} + +test "every control is named one, and only the controls plant a fault" { + for (entries) |e| try std.testing.expectEqual(e.short, std.mem.startsWith(u8, e.name, "control: ")); +} + +test "the soft-capped SwiGLU's slopes are its float64 difference quotients" { + for ([_][2]f64{ .{ 0.3, 1.5 }, .{ -6, 30 }, .{ 9, -2 } }) |gu| { + const r = softcap(gu[0], gu[1]); + const h = 1e-6; + try std.testing.expectApproxEqRel((softcap(gu[0] + h, gu[1])[0] - softcap(gu[0] - h, gu[1])[0]) / (2 * h), r[1], 1e-6); + try std.testing.expectApproxEqRel((softcap(gu[0], gu[1] + h)[0] - softcap(gu[0], gu[1] - h)[0]) / (2 * h), r[2], 1e-6); + } +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index f09b14e3eb1..f1fb75e9b8c 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -234,6 +234,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "nvfp4")) return nvfp4_tests.run(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "nvfp4-experts")) return nvfp4_experts_tests.experts(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "bf16-experts")) return if (rest.len == 0) @import("bf16_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_bf16.zig").run(gpu) else error.UnknownCommand; + if (std.mem.eql(u8, cmd, "stored-experts")) return storedExperts(gpu, rest); if (std.mem.eql(u8, cmd, "projection-f32")) return projection_f32_tests.run(gpu); if (std.mem.eql(u8, cmd, "mxfp8")) return mxfp8_tests.run(gpu); if (std.mem.eql(u8, cmd, "quant-ref")) return quant_ref_tests.run(gpu); @@ -407,3 +408,12 @@ fn hasFlag(flags: []const [:0]const u8, name: []const u8) bool { for (flags) |f| if (std.mem.eql(u8, f, name)) return true; return false; } + +/// Inkling 2 Mini's stored experts: `contract`, `ckpt DIR` (layers 0 and 20) or `bench DIR`. +fn storedExperts(gpu: check.Gpu, rest: []const [:0]const u8) !void { + const what = try arg(rest, 0); + if (std.mem.eql(u8, what, "contract")) return @import("contract_stored_experts.zig").run(gpu); + if (std.mem.eql(u8, what, "ckpt")) return @import("stored_experts_tests.zig").ckpt(gpu, try arg(rest, 1)); + if (std.mem.eql(u8, what, "bench")) return @import("stored_experts_bench.zig").bench(gpu, try arg(rest, 1)); + return error.UnknownCommand; +} diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 7c8b840f518..3a17b244fd0 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -93,6 +93,7 @@ pub const usage = \\ fp8-experts grouped block-FP8 experts against recorded fixture bytes \\ nvfp4-experts grouped NVFP4 experts against recorded fixture bytes \\ bf16-experts [contract] grouped bf16 experts against float64 (repack, up, downs, rows, forms); contract: gates 1-4, controls red + \\ stored-experts contract | ckpt DIR | bench DIR Inkling 2 Mini's NVFP4 and MXFP8 experts: gates, checkpoint, speed \\ projection-f32 FP32 projection outputs against FP64, rounding and row/reduction invariance \\ mxfp8 MXFP8 strided projections against FP64 and row-count invariance \\ quant-ref FP8 and NVFP4 projections and experts against float64 references (synthetic) diff --git a/zig/tests/cuda/stored_experts_bench.zig b/zig/tests/cuda/stored_experts_bench.zig new file mode 100644 index 00000000000..3a2a263ce8b --- /dev/null +++ b/zig/tests/cuda/stored_experts_bench.zig @@ -0,0 +1,99 @@ +//! `stored-experts bench DIR`: one layer's grouped experts (gate-up and down) at 1, 4 and 512 tokens, bytes per time. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const st = @import("stored_experts_tests.zig"); + +const Gpu = check.Gpu; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; + +const peak = 273.0; // GB10's unified memory, GB/s +const reps = 200; +const runs = 5; + +pub fn bench(gpu: Gpu, dir: []const u8) !void { + const a = gpu.gpa; + const path = try std.fmt.allocPrint(a, "{s}/model-00001-of-00001.safetensors", .{dir}); + defer a.free(path); + var f = try core.safetensors.File.openPrefix(a, gpu.io, path, "model.llm.layers."); + defer f.close(gpu.io); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + defer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + const gx: ex_.Grouped = .{ .nvfp4 = &k4, .mxfp8 = &k8 }; + for ([_]usize{ 0, 20 }) |layer| { + const s = try st.Stored.read(&f, layer); + var bufs: [4]cuda.DeviceBuffer = undefined; + const l = try s.upload(gpu, &bufs); + defer for (&bufs) |*b| b.free(); + const per_expert = bufs[0].len / st.experts + bufs[1].len / st.experts; + for ([_]usize{ 1, 4, 512 }) |tokens| { + const prompt = tokens >= 64; + const pairs = tokens * st.top; + const tile: usize = if (prompt) 64 else 16; + const xs = try a.alloc(u16, tokens * st.hidden); + defer a.free(xs); + var prng = std.Random.DefaultPrng.init(tokens); + for (xs) |*v| v.* = core.contract.spec.toBf16(prng.random().float(f32) * 2 - 1); + const ids = try st.picks(a, tokens, 0xbe4c + tokens); + defer a.free(ids); + var used: [st.experts]bool = @splat(false); + for (ids) |e| used[@intCast(e)] = true; + var touched: usize = 0; + for (used) |u| touched += @intFromBool(u); + var dx = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(xs)); + defer dx.free(); + var dids = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(ids)); + defer dids.free(); + var pb = try st.PlanBufs.init(gpu, pairs, tile); + defer pb.deinit(); + var act = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.width * 2); + defer act.free(); + var y = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.hidden * 4); + defer y.free(); + const up_in: ex_.Rows = .{ .x = dx.ptr, .stride = st.hidden, .slots = st.top }; + const down_in: ex_.Rows = .{ .x = act.ptr, .stride = st.width }; + const Step = struct { + fn go(g: ex_.Grouped, sm: cuda.Stream, p: bool, ui: ex_.Rows, di: ex_.Rows, ly: ex_.Layer, pl: *const st.PlanBufs, o1: u64, o2: u64, n: usize, t: usize) !void { + if (p) { + try g.prompt(sm, .up, ui, ly, pl.plan, o1, pl.items, n, t, -1); + try g.prompt(sm, .down_bf16, di, ly, pl.plan, o2, pl.items, n, t, -1); + } else { + try g.decode(sm, .up, ui, ly, pl.plan, o1, pl.items, n, t, -1); + try g.decode(sm, .down_f32, di, ly, pl.plan, o2, pl.items, n, t, -1); + } + } + }; + try router.route(stream, dids.ptr, pairs, st.experts, tile, pb.plan); + for (0..10) |_| try Step.go(gx, stream, prompt, up_in, down_in, l, &pb, act.ptr, y.ptr, pairs, tile); + try stream.synchronize(); + var t0 = try cuda.Event.init(gpu.d, true); + defer t0.deinit(); + var t1 = try cuda.Event.init(gpu.d, true); + defer t1.deinit(); + var us: [runs]f64 = undefined; + for (&us) |*u| { + try t0.record(stream); + for (0..reps) |_| try Step.go(gx, stream, prompt, up_in, down_in, l, &pb, act.ptr, y.ptr, pairs, tile); + try t1.record(stream); + try t1.synchronize(); + u.* = @as(f64, try cuda.Event.elapsedMs(t0, t1)) * 1000 / reps; + } + const med = check.median(&us); + // the weights of every expert the tokens pick, read once; the rows in and out besides + const bytes = touched * per_expert + tokens * st.hidden * 2 + pairs * st.width * 4 + pairs * st.hidden * (if (prompt) @as(usize, 2) else 4); + const gbs = @as(f64, @floatFromInt(bytes)) / med / 1000; + std.debug.print("RESULT stored-experts layer {d} {s} tokens {d} ({s}): {d} experts, {d} bytes, {d:.2} us median of {d}x{d}, {d:.1} GB/s = {d:.0}% of {d:.0}\n", .{ layer, if (s.nv) "NVFP4" else "MXFP8", tokens, if (prompt) "prompt form" else "decode form", touched, bytes, med, runs, reps, gbs, 100 * gbs / peak, peak }); + } + } +} diff --git a/zig/tests/cuda/stored_experts_check.zig b/zig/tests/cuda/stored_experts_check.zig new file mode 100644 index 00000000000..00954ab79f5 --- /dev/null +++ b/zig/tests/cuda/stored_experts_check.zig @@ -0,0 +1,203 @@ +//! The stored experts' two checkpoint checks: one-hot rows read each decoded weight back, random rows the outputs. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const cs = @import("contract_stored_experts.zig"); +const st = @import("stored_experts_tests.zig"); + +const Gpu = check.Gpu; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; +const c = core.contract.spec; + +const chunk = 16; // experts a pass of the one-hot check + +/// Every weight of both matrices of all 128 experts through the fp32 down kernel: x one-hot, so out = w (x factor). +pub fn decoded(gpu: Gpu, s: st.Stored, layer: usize) !void { + const a = gpu.gpa; + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + defer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + for ([_]st.Matrix{ s.w13, s.w2 }, [_][]const u8{ "w13", "w2" }) |m, name| { + const n = m.n; + const k = m.k; + const words = (if (s.nv) ex_.Nvfp4Experts.bytes(1, n, k, 1) else mx.Mxfp8Experts.bytes(1, n, k, 1)) / 4; + const packed_ = try a.alloc(u32, st.experts * words); + defer a.free(packed_); + for (0..st.experts) |e| { + const o = packed_[e * words ..][0..words]; + if (s.nv) ex_.Nvfp4Experts.packOne(o, m.expertCodes(e), m.expertScales(e), n, k) else mx.Mxfp8Experts.packOne(o, m.expertCodes(e), m.expertScales(e), n, k); + } + var w = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(packed_)); + defer w.free(); + var fs = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&m.factor)); + defer fs.free(); + // x: the k x k identity; pair i * chunk + j reads row i (slots = chunk) and expert base + j + const eye = try a.alloc(u16, k * k); + defer a.free(eye); + @memset(eye, 0); + for (0..k) |i| eye[i * k + i] = 0x3F80; + var x = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(eye)); + defer x.free(); + const pairs = k * chunk; + var pb = try st.PlanBufs.init(gpu, pairs, 16); + defer pb.deinit(); + const ids = try a.alloc(i32, pairs); + defer a.free(ids); + var dids = try cuda.DeviceBuffer.alloc(gpu.d, pairs * 4); + defer dids.free(); + var out = try cuda.DeviceBuffer.alloc(gpu.d, pairs * n * 4); + defer out.free(); + const got = try a.alloc(f32, pairs * n); + defer a.free(got); + var differ: usize = 0; + var zeros: usize = 0; + var base: usize = 0; + while (base < st.experts) : (base += chunk) { + for (ids, 0..) |*v, p| v.* = @intCast(base + p % chunk); + try dids.upload(0, std.mem.sliceAsBytes(ids)); + try router.route(stream, dids.ptr, pairs, st.experts, 16, pb.plan); + try out.fill8(0xff, stream.handle); + const in: ex_.Rows = .{ .x = x.ptr, .stride = k, .slots = chunk }; + const nb = n / 32; + if (s.nv) { + // the existing fp32 down (decode form) read with token rows: Nvfp4Experts.run passes slots only to up + var args: cuda.Args = .{}; + args.add(in.x); + for ([_]usize{ k, chunk }) |v| args.add(@as(i32, @intCast(v))); + args.add(w.ptr); + args.add(fs.ptr); + for ([_]usize{ k / 32, nb }) |v| args.add(@as(i32, @intCast(v))); + for ([_]u64{ pb.plan.items, pb.plan.counts, pb.plan.members, out.ptr }) |v| args.add(v); + args.add(@as(i32, @intCast(n))); + args.add(@as(f32, 0)); + args.add(@as(i32, -1)); + const grid = @min((pb.items * nb + k4.warps - 1) / k4.warps, k4.resident[1]); + try cuda.launch.launch(k4.fns[1], .{ .grid = .{ .x = @intCast(grid) }, .block = .{ .x = @intCast(k4.warps * 32) } }, stream, &args); + } else { + var args = mx.argsOf(in, true, w.ptr, null, k / 32, nb, pb.plan, out.ptr, n, .{ 0, 0 }, -1); + const grid = @min((pb.items * nb + 3) / 4, k8.resident[1]); + try cuda.launch.launch(k8.fns[1], .{ .grid = .{ .x = @intCast(grid) }, .block = .{ .x = 128 } }, stream, &args); + } + try stream.synchronize(); + try out.download(0, std.mem.sliceAsBytes(got)); + for (0..k) |i| for (0..chunk) |j| for (0..n) |row| { + const want = m.f32At(s.nv, base + j, row, i); + const v = got[(i * chunk + j) * n + row]; + if (v != want) differ += 1 else if (@as(u32, @bitCast(v)) != @as(u32, @bitCast(want))) zeros += 1; + }; + } + try check.expect(differ == 0, "layer {d} {s}: {d} of {d} decoded weights differ from the host decode", .{ layer, name, differ, st.experts * n * k }); + check.pass("layer {d} {s} ({s}): all {d} weights of 128 experts [{d}, {d}] equal the host decode ({d} zeros differ in sign only)", .{ layer, name, if (s.nv) "NVFP4" else "MXFP8", st.experts * n * k, n, k, zeros }); + } +} + +/// Gate-up then down on 4 tokens (decode form) and 64 (prompt form), each output within the contract's fp32 bound. +pub fn outputs(gpu: Gpu, s: st.Stored, layer: usize) !void { + const a = gpu.gpa; + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k4 = try ex_.Nvfp4Experts.load(gpu.d, sms); + defer k4.unload(); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + var bufs: [4]cuda.DeviceBuffer = undefined; + const l = try s.upload(gpu, &bufs); + defer for (&bufs) |*b| b.free(); + const gx: ex_.Grouped = .{ .nvfp4 = &k4, .mxfp8 = &k8 }; + for ([_]usize{ 4, 64 }) |tokens| { + const prompt = tokens > 4; + const pairs = tokens * st.top; + const tile: usize = if (prompt) 64 else 16; + var prng = std.Random.DefaultPrng.init(0x5eed + tokens + layer); + const xs = try a.alloc(u16, tokens * st.hidden); + defer a.free(xs); + for (xs) |*v| v.* = c.toBf16((prng.random().float(f32) * 2 - 1) * 2); + const ids = try st.picks(a, tokens, 0xc3 + tokens); + defer a.free(ids); + var dx = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(xs)); + defer dx.free(); + var dids = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(ids)); + defer dids.free(); + var pb = try st.PlanBufs.init(gpu, pairs, tile); + defer pb.deinit(); + try router.route(stream, dids.ptr, pairs, st.experts, tile, pb.plan); + var act = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.width * 2); + defer act.free(); + const yw: usize = if (prompt) 2 else 4; + var y = try cuda.DeviceBuffer.alloc(gpu.d, pairs * st.hidden * yw); + defer y.free(); + try act.fill8(0xff, stream.handle); + try y.fill8(0xff, stream.handle); + const up_in: ex_.Rows = .{ .x = dx.ptr, .stride = st.hidden, .slots = st.top }; + const down_in: ex_.Rows = .{ .x = act.ptr, .stride = st.width }; + if (prompt) { + try gx.prompt(stream, .up, up_in, l, pb.plan, act.ptr, pb.items, pairs, tile, -1); + try gx.prompt(stream, .down_bf16, down_in, l, pb.plan, y.ptr, pb.items, pairs, tile, -1); + } else { + try gx.decode(stream, .up, up_in, l, pb.plan, act.ptr, pb.items, pairs, tile, -1); + try gx.decode(stream, .down_f32, down_in, l, pb.plan, y.ptr, pb.items, pairs, tile, -1); + } + try stream.synchronize(); + const ga = try a.alloc(u16, pairs * st.width); + defer a.free(ga); + try act.download(0, std.mem.sliceAsBytes(ga)); + const gy = try a.alloc(u8, pairs * st.hidden * yw); + defer a.free(gy); + try y.download(0, gy); + const fmt = if (s.nv) cs.Format.nvfp4 else cs.Format.mxfp8; + const up_spec = cs.spec(.{ .name = "up", .format = fmt, .kind = .up, .prompt = prompt }); + const down_spec = cs.spec(.{ .name = "down", .format = fmt, .kind = if (prompt) .down_bf16 else .down_f32, .prompt = prompt }); + var worst: [2]f64 = .{ 0, 0 }; + var bad: [2]usize = .{ 0, 0 }; + for (0..pairs) |p| { + const e: usize = @intCast(ids[p]); + const xr = xs[(p / st.top) * st.hidden ..][0..st.hidden]; + for (0..st.width) |j| { + var sum: [2]f64 = .{ 0, 0 }; + var abs: [2]f64 = .{ 0, 0 }; + for (0..2) |m| for (0..st.hidden) |i| { + const t = c.fromBf16(xr[i]) * s.w13.f64At(s.nv, e, m * st.width + j, i); + sum[m] += t; + abs[m] += @abs(t); + }; + const r = cs.softcap(sum[0], sum[1]); + const mag = @abs(r[1]) * abs[0] + @abs(r[2]) * abs[1]; + const err = @abs(@as(f64, c.fromBf16(ga[p * st.width + j])) - r[0]); + const b = c.bound(up_spec, .{ .rows = tokens, .n = st.width, .k = st.hidden }, r[0], mag); + worst[0] = @max(worst[0], err / b); + if (!(err <= b)) bad[0] += 1; + } + const ar = ga[p * st.width ..][0..st.width]; + for (0..st.hidden) |row| { + var sum: f64 = 0; + var abs: f64 = 0; + for (0..st.width) |i| { + const t = c.fromBf16(ar[i]) * s.w2.f64At(s.nv, e, row, i); + sum += t; + abs += @abs(t); + } + const o = p * st.hidden + row; + const v: f64 = if (prompt) c.fromBf16(std.mem.bytesToValue(u16, gy[o * 2 ..][0..2])) else std.mem.bytesToValue(f32, gy[o * 4 ..][0..4]); + const b = c.bound(down_spec, .{ .rows = tokens, .n = st.hidden, .k = st.width }, sum, abs); + worst[1] = @max(worst[1], @abs(v - sum) / b); + if (!(@abs(v - sum) <= b)) bad[1] += 1; + } + } + try check.expect(bad[0] == 0 and bad[1] == 0, "layer {d} {d} tokens: {d} gate-up and {d} down outputs outside the fp32 bound", .{ layer, tokens, bad[0], bad[1] }); + check.pass("layer {d} {s} {d} tokens ({s}): {d} gate-up and {d} down outputs within the fp32 bound; worst err/bound {d:.3} and {d:.3}", .{ layer, if (s.nv) "NVFP4" else "MXFP8", tokens, if (prompt) "prompt form" else "decode form", pairs * st.width, pairs * st.hidden, worst[0], worst[1] }); + } +} diff --git a/zig/tests/cuda/stored_experts_tests.zig b/zig/tests/cuda/stored_experts_tests.zig new file mode 100644 index 00000000000..37c00d2d9ef --- /dev/null +++ b/zig/tests/cuda/stored_experts_tests.zig @@ -0,0 +1,206 @@ +//! Inkling 2 Mini's stored experts from the checkpoint: decoded weights bit for bit, outputs within the fp32 bound. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const cs = @import("contract_stored_experts.zig"); + +const Gpu = check.Gpu; +const grouped = cuda.grouped; +const ex_ = cuda.experts; +const mx = cuda.experts_mx; +const dec = core.expert_decode; +const c = core.contract.spec; + +pub const hidden = 2304; +pub const width = 1152; +pub const experts = 128; +pub const top = 8; + +/// One stored matrix of all experts: codes, scales and (NVFP4) the per-expert factor. +pub const Matrix = struct { + codes: []const u8, + scales: []const u8, + factor: [experts]f32 = @splat(1), + n: usize, + k: usize, + + pub fn expertCodes(m: Matrix, e: usize) []const u8 { + const per = m.codes.len / experts; + return m.codes[e * per ..][0..per]; + } + + pub fn expertScales(m: Matrix, e: usize) []const u8 { + const per = m.scales.len / experts; + return m.scales[e * per ..][0..per]; + } + + /// Weight (row, i) of expert e as the kernels form it in fp32. + pub fn f32At(m: Matrix, nv: bool, e: usize, row: usize, i: usize) f32 { + if (nv) return dec.nvfp4F32(m.expertCodes(e), m.expertScales(e), m.k, row, i, m.factor[e]); + return @floatCast(dec.mxfp8(m.expertCodes(e), m.expertScales(e), m.k, row, i)); + } + + /// Weight (row, i) of expert e in float64 (the reference's). + pub fn f64At(m: Matrix, nv: bool, e: usize, row: usize, i: usize) f64 { + if (nv) return dec.nvfp4(m.expertCodes(e), m.expertScales(e), m.k, row, i, m.factor[e]); + return dec.mxfp8(m.expertCodes(e), m.expertScales(e), m.k, row, i); + } +}; + +/// A layer's w13 (gate rows then up rows) and w2 from the mapped checkpoint. +pub const Stored = struct { + nv: bool, + w13: Matrix, + w2: Matrix, + + pub fn read(f: *const core.safetensors.File, layer: usize) !Stored { + var name: [96]u8 = undefined; + const pre = "model.llm.layers.{d}.mlp.experts."; + const codes13 = f.get(try std.fmt.bufPrint(&name, pre ++ "w13_weight", .{layer})) orelse return error.MissingTensor; + const nv = codes13.dtype == .u8; + var s: Stored = .{ .nv = nv, .w13 = undefined, .w2 = undefined }; + inline for (.{ "w13", "w2" }, .{ &s.w13, &s.w2 }) |w, m| { + const t = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight", .{layer})) orelse return error.MissingTensor; + const sc = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight_scale", .{layer})) orelse return error.MissingTensor; + const k = if (nv) t.dim(2) * 2 else t.dim(2); + m.* = .{ .codes = t.bytes, .scales = sc.bytes, .n = t.dim(1), .k = k }; + if (nv) { + const amax = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight_amax", .{layer})) orelse return error.MissingTensor; + const den = f.get(try std.fmt.bufPrint(&name, pre ++ w ++ "_weight_outer_scale_denominator", .{layer})) orelse return error.MissingTensor; + const d = std.mem.bytesToValue(f32, den.bytes[0..4]); + try check.expect(d == 2688, "layer {d} {s}: outer scale denominator {d}, expected 2688", .{ layer, w, d }); + for (&m.factor, 0..) |*x, e| x.* = mx.nvfp4Factor(std.mem.bytesToValue(f32, amax.bytes[e * 4 ..][0..4]), d); + } + } + try check.expect(s.w13.n == 2 * width and s.w13.k == hidden and s.w2.n == hidden and s.w2.k == width, "layer {d}: expert shapes", .{layer}); + return s; + } + + /// The layer packed for the kernels: w13 as gate-up pairs, w2 alone, and NVFP4's factors per (expert, matrix). + pub fn upload(s: Stored, gpu: Gpu, bufs: *[4]cuda.DeviceBuffer) !ex_.Layer { + const a = gpu.gpa; + const up_words = (if (s.nv) ex_.Nvfp4Experts.bytes(1, width, hidden, 2) else mx.Mxfp8Experts.bytes(1, width, hidden, 2)) / 4; + const down_words = (if (s.nv) ex_.Nvfp4Experts.bytes(1, hidden, width, 1) else mx.Mxfp8Experts.bytes(1, hidden, width, 1)) / 4; + const up = try a.alloc(u32, experts * up_words); + defer a.free(up); + const down = try a.alloc(u32, experts * down_words); + defer a.free(down); + const half_c = s.w13.expertCodes(0).len / 2; + const half_s = s.w13.expertScales(0).len / 2; + for (0..experts) |e| { + const c13 = s.w13.expertCodes(e); + const s13 = s.w13.expertScales(e); + const gate = [2][]const u8{ c13[0..half_c], s13[0..half_s] }; + const upm = [2][]const u8{ c13[half_c..], s13[half_s..] }; + const o = up[e * up_words ..][0..up_words]; + const d = down[e * down_words ..][0..down_words]; + if (s.nv) { + ex_.Nvfp4Experts.packGateUp(o, gate, upm, width, hidden); + ex_.Nvfp4Experts.packOne(d, s.w2.expertCodes(e), s.w2.expertScales(e), hidden, width); + } else { + mx.Mxfp8Experts.packGateUp(o, gate, upm, width, hidden); + mx.Mxfp8Experts.packOne(d, s.w2.expertCodes(e), s.w2.expertScales(e), hidden, width); + } + } + var f13: [experts * 2]f32 = undefined; + for (0..experts) |e| f13[2 * e] = s.w13.factor[e]; + for (0..experts) |e| f13[2 * e + 1] = s.w13.factor[e]; // one amax covers the gate and the up rows + bufs[0] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(up)); + bufs[1] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(down)); + bufs[2] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&f13)); + bufs[3] = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&s.w2.factor)); + return .{ .format = if (s.nv) .nvfp4 else .mxfp8, .up = bufs[0].ptr, .down = bufs[1].ptr, .up_scale = bufs[2].ptr, .down_scale = bufs[3].ptr, .width = width, .dims = hidden, .experts = experts, .caps = cs.caps }; + } +}; + +/// Plan scratch for `pairs` picks over 128 experts in items of `tile`. +pub const PlanBufs = struct { + bufs: [5]cuda.DeviceBuffer, + plan: grouped.Plan, + items: usize, + + pub fn init(gpu: Gpu, pairs: usize, tile: usize) !PlanBufs { + var p: PlanBufs = undefined; + p.items = grouped.maxItems(pairs, experts, tile); + const sizes = [5]usize{ pairs * 4, p.items * 12, 8, pairs * 4, ((pairs + 1023) / 1024) * experts * 4 }; + var made: usize = 0; + errdefer for (p.bufs[0..made]) |*b| b.free(); + for (sizes, &p.bufs) |n, *b| { + b.* = try cuda.DeviceBuffer.alloc(gpu.d, n); + made += 1; + } + p.plan = .{ .members = p.bufs[0].ptr, .items = p.bufs[1].ptr, .counts = p.bufs[2].ptr, .rank = p.bufs[3].ptr, .hist = p.bufs[4].ptr }; + return p; + } + + pub fn deinit(p: *PlanBufs) void { + for (&p.bufs) |*b| b.free(); + } +}; + +/// `tokens` rows' top-8 distinct experts, seeded. +pub fn picks(a: std.mem.Allocator, tokens: usize, seed: u64) ![]i32 { + var prng = std.Random.DefaultPrng.init(seed); + const out = try a.alloc(i32, tokens * top); + for (0..tokens) |t| { + var perm: [experts]i32 = undefined; + for (&perm, 0..) |*v, i| v.* = @intCast(i); + prng.random().shuffle(i32, &perm); + @memcpy(out[t * top ..][0..top], perm[0..top]); + } + return out; +} + +/// `ckpt DIR`: layers 0 (NVFP4) and 20 (MXFP8) of the checkpoint in DIR. +pub fn ckpt(gpu: Gpu, dir: []const u8) !void { + const path = try std.fmt.allocPrint(gpu.gpa, "{s}/model-00001-of-00001.safetensors", .{dir}); + defer gpu.gpa.free(path); + var f = try core.safetensors.File.openPrefix(gpu.gpa, gpu.io, path, "model.llm.layers."); + defer f.close(gpu.io); + for ([_]usize{ 0, 20 }) |layer| { + const s = try Stored.read(&f, layer); + try invariants(s, layer); + try @import("stored_experts_check.zig").decoded(gpu, s, layer); + try @import("stored_experts_check.zig").outputs(gpu, s, layer); + } +} + +/// The stored data as the scale analysis found it: NVFP4's code x block scale peaks at exactly 6 x 448 in every +/// expert (so amax / 2688 is the factor), MXFP8 holds no NaN code and peaks at 448. +fn invariants(s: Stored, layer: usize) !void { + for ([_]Matrix{ s.w13, s.w2 }, 0..) |m, mi| { + var peaks: usize = 0; + for (0..experts) |e| { + var most: f64 = 0; + const codes = m.expertCodes(e); + const scales = m.expertScales(e); + if (s.nv) { + for (0..m.n) |row| for (0..m.k / 16) |b| { + const sv = dec.e4m3(scales[row * (m.k / 16) + b]); + for (0..16) |q| most = @max(most, @abs(dec.e2m1(dec.nibble(codes[row * (m.k / 2) ..][0 .. m.k / 2], b * 16 + q)) * sv)); + }; + try check.expect(most == 2688, "layer {d} matrix {d} expert {d}: peak code x scale {d}, expected 2688", .{ layer, mi, e, most }); + } else { + for (codes) |b| { + try check.expect(b & 0x7F != 0x7F, "layer {d} matrix {d} expert {d}: a NaN code", .{ layer, mi, e }); + most = @max(most, @abs(dec.e4m3(b))); + } + for (scales) |b| try check.expect(b != 255, "layer {d} matrix {d} expert {d}: a NaN scale", .{ layer, mi, e }); + if (most == 448) peaks += 1; + } + } + if (s.nv) check.pass("layer {d} NVFP4 matrix {d}: every expert's code x block scale peaks at 2688 = 6 x 448", .{ layer, mi }); + if (!s.nv) check.pass("layer {d} MXFP8 matrix {d}: no NaN code or scale; {d} of 128 experts peak at 448", .{ layer, mi, peaks }); + } +} + +test "picks are eight distinct experts a token" { + const p = try picks(std.testing.allocator, 3, 7); + defer std.testing.allocator.free(p); + for (0..3) |t| for (0..top) |i| for (0..i) |j| try std.testing.expect(p[t * top + i] != p[t * top + j]); +} + +comptime { + _ = c; +} diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index a4a03686acf..49a2eaaa860 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -6,7 +6,7 @@ zig/kernels/cuda/embed_rows.cu c3cad38db6576728a15e048a45f2c1a571233fc3fedc83d04 zig/kernels/cuda/exlr8.cu 0eb19c8965aeb8188efd2b15a5844da860d9bf75364b12b62dd3a2589a89178c raw zig/kernels/cuda/exlr8_dense.cu 7616e7a3bb35a2bb64b53a1ca84ce8be98442a36394dad945b844219f72ec671 raw zig/kernels/cuda/experts.cu 2a9b3989f3baaef5eadb56abfb8520700449bd910f2b00345703c22dbf758b8c raw -zig/kernels/cuda/experts.cuh 017728fef063d45f06240a88002f80ec931f967edc5fa44c31b10673d43872f9 raw +zig/kernels/cuda/experts.cuh 7a32dc8ee6f4eef59a233b70ad55193342c0ea71cc590ff48d757513f7b10d05 raw Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged zig/kernels/cuda/experts_pack.cu 578e9a607f678f0547aaeb312d18252ea0608bad7fe71bb2d5241d28adf31bac raw zig/kernels/cuda/experts_prefill.cu 5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc raw zig/kernels/cuda/experts_rows.cu 714b76ad72ff45715c5ebf6b57365f0f41789ad301871f07168a016412df13a7 raw @@ -15,7 +15,7 @@ zig/kernels/cuda/flashnext_batch.cu 95260b964fb633d23df28970672d87688f21cdd9073e zig/kernels/cuda/flashnext_gdn.cu c7b9712626778d452e18234e2dfc3b26f8112618cdc492957c4b5f5454d64126 raw zig/kernels/cuda/flashnext_hc.cu 54fa2cfa22e483341835f6349cf0a8f508459ed1b65804728cb1358ac82b24f1 raw main 5c7cf5c117, d88c1ed57d (sum_rn and rms_scale shared; same SASS) zig/kernels/cuda/flashnext_mtp.cu 5d213b1b4a1d0588eea3acb4633a0c8bc4d9bdf6f27485604452a3b603677a09 raw #2927 -zig/kernels/cuda/fp8_experts.cu 156aa7337b41c67d200d8b58a24422cc96cfa032c9fd0711080f09ddc733baee raw +zig/kernels/cuda/fp8_experts.cu b0a4a962aec818b9129b1a3a6f7082ae4b917a47c92ef47d32947a267fdab26c raw Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged zig/kernels/cuda/gdn.cu e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228 raw zig/kernels/cuda/glm_glue.cu 74e69a7c20827d498c190334fffaa896f2a4f05e107fdf9d2d34b09b55a1c75c raw #2722 (one added line, the include of glm_index_decode.cuh: the decode select's scan and merge) zig/kernels/cuda/glm_glue_attn.cuh a8c16ed0c54130689d19386de84217aac232c007effafdb6c7fc149ac7188051 raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) @@ -44,7 +44,7 @@ zig/kernels/cuda/nemotron_mamba.cu dcaba12253d3931ae48c7ebd4e13dfb956f540ae19f4a zig/kernels/cuda/nemotron_ops.cu 2ef87c655b49d33214f8856d2ad775aacf6198ab2ca343f87fde588639ecccd1 raw #3124 zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe3c3557a48bca96f6511 raw commits 739c924de, 8cfdaa739, b77a33b08, 7f6f940eb, 05d0617af, bc76d90d6; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) -zig/kernels/cuda/nvfp4_experts.cu cb54357e2c06252cc594cd1223401170dadefd995b0c67db0cae5edf628719d0 raw #2266 (decode cp.async rings, GB10 SASS unchanged) +zig/kernels/cuda/nvfp4_experts.cu 82e05294fd0f528081ae563098a69d6e204715fb3bf220c989130ad20aa4bddb raw #2266 (decode cp.async rings, GB10 SASS unchanged); Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw zig/kernels/cuda/prefill_attention.cu 905fff2c9018d778557a60ed2c81c24ce220adf5b092c8c32f8a1782963f9f28 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) @@ -89,7 +89,7 @@ zig/src/cuda/cublaslt.zig d87f865fc03cf94bdcbe83504f74a6e569d70c10ca792b675122e9 zig/src/cuda/driver.zig f20856bd06afe9365ab9ca1bc39800ccb260ade2704197c033e1344a0c8dd742 raw commits e9bf05ffd, b923e554c, b2c75a98a; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/embed_rows.zig 3fa5e28ab46b4daef2c820b3ad3f7d331bc77f55ea340a7a3cac64b21584c5f4 raw #3471: Gemma 4 holds its tied embedding once; token rows read the head's 4-bit tiles; replies unchanged zig/src/cuda/exlr8.zig 1e2164096ae949a8a9a4903df82c7c0c184a6f5e1ba5ba4423038a42b0633fc6 raw -zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf5a9fed440 raw main 3768bc0168 (#2843: grouped EXL3 experts launched and sized at the caller's tile and pair count; no kernel source change), #1630 (a bf16 format: its Grouped member, decode and prompt arms and prompt tile; other formats unchanged) +zig/src/cuda/experts.zig d579d5efd53228906ba306f99b6b60221b687a1b2ec071da665238f99f5221c6 raw main 3768bc0168 (#2843: grouped EXL3 experts launched and sized at the caller's tile and pair count; no kernel source change), #1630 (a bf16 format: its Grouped member, decode and prompt arms and prompt tile; other formats unchanged); Inkling 2 Mini C3: additive MXFP8 format and soft-capped dispatch (experts_mx.zig); existing calls unchanged zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate @@ -105,7 +105,7 @@ zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7 zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/qmmf.zig 577b24e8dc1a00e975c75075bf9636af55d2614780d05fcb6ed488cc68d37778 raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig d0d978fc3f6df100e6bcb1c479b567382d5950a9728b8b74a76a188e7cba32b7 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash) +zig/src/cuda/root.zig 26785ffbbf6eb6b7aeb6804a95250316b6fc9860f7f41ad86cda42c4f67aa178 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); Inkling 2 Mini C3: additive MXFP8 format and soft-capped dispatch (experts_mx.zig); existing calls unchanged zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw From eed574b91fcd62d5030f8153294091e8804c014d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:26:48 +0100 Subject: [PATCH 03/84] cuda experts: Inkling's w13 interleaves gate and up rows; E8M0 byte 0 checked on the GPU experts_mx.splitGateUp takes stored row 2j to gate j and 2j + 1 to up j before packGateUp (the kernels are unchanged); a host test plants a code in stored row 1 and requires it in the up part. The checkpoint reference reads row 2j + m. stored-experts ckpt adds E8M0 bytes 0 to 240 through tf_mxfp8_down_f32 against the host decode (byte 0 = 2^-127). --- zig/src/cuda/experts_mx.zig | 34 +++++++++++++++ zig/tests/cuda/stored_experts_check.zig | 55 ++++++++++++++++++++++++- zig/tests/cuda/stored_experts_tests.zig | 17 +++++--- 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/zig/src/cuda/experts_mx.zig b/zig/src/cuda/experts_mx.zig index 448826ec853..9d8f069f740 100644 --- a/zig/src/cuda/experts_mx.zig +++ b/zig/src/cuda/experts_mx.zig @@ -38,6 +38,16 @@ pub fn capsBuilt(l: Layer) !void { if (l.width % 32 != 0 or l.dims % 32 != 0) return error.UnexpectedShape; // whole blocks of 32 both ways } +/// Inkling's w13 interleaves rows (2j gate j, 2j + 1 up j): one expert's rows of `row_bytes` split into gate, up. +pub fn splitGateUp(rows: []const u8, row_bytes: usize, gate: []u8, up: []u8) void { + const pairs = rows.len / (2 * row_bytes); + std.debug.assert(rows.len == 2 * pairs * row_bytes and gate.len == pairs * row_bytes and up.len == gate.len); + for (0..pairs) |j| { + @memcpy(gate[j * row_bytes ..][0..row_bytes], rows[2 * j * row_bytes ..][0..row_bytes]); + @memcpy(up[j * row_bytes ..][0..row_bytes], rows[(2 * j + 1) * row_bytes ..][0..row_bytes]); + } +} + /// An expert call's arguments as the soft-capped and MXFP8 entries take them; `scale` null for MXFP8 (in its blocks). pub fn argsOf(in: Rows, gate: bool, w: u64, scale: ?u64, kg: usize, nb: usize, p: Plan, out: u64, n: usize, caps: [2]f32, skip: i32) launch_.Args { var a: launch_.Args = .{}; @@ -176,6 +186,30 @@ test "the NVFP4 factor rounds amax and the denominator to bf16 before it divides try std.testing.expect(nvfp4Factor(amax, 2688) != amax / 2688); } +test "w13's row 1 is up row 0 and row 2 gate row 1: a code planted in row 1 lands in the up part, never the gate" { + const n = 32; // gate and up rows each + const k = 32; + var rows: [2 * n * k]u8 = @splat(0x00); + var sc: [2 * n]u8 = @splat(127); + rows[1 * k + 5] = 0x38; // stored row 1 (up row 0), input 5 + rows[2 * k + 7] = 0x40; // stored row 2 (gate row 1), input 7 + var g: [n * k]u8 = undefined; + var u: [n * k]u8 = undefined; + var gs: [n]u8 = undefined; + var us: [n]u8 = undefined; + splitGateUp(&rows, k, &g, &u); + splitGateUp(&sc, 1, &gs, &us); + try std.testing.expectEqual(@as(u8, 0x38), u[5]); + try std.testing.expectEqual(@as(u8, 0x40), g[k + 7]); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, &u, &.{0x38}) + std.mem.count(u8, &u, &.{0x40})); + var out: [2 * Mxfp8Experts.words]u32 = undefined; + Mxfp8Experts.packGateUp(&out, .{ &g, &gs }, .{ &u, &us }, n, k); + // row 0, input 5 = lane (gq 0, t 1), half 0, tile j 0, byte 1 of the word; part 1 (up) holds it, part 0 not + const at = ((0 * 4 + 1) * 2 + 0) * 4 + 0; + try std.testing.expectEqual(@as(u32, 0x38), (out[Mxfp8Experts.words + at] >> 8) & 0xFF); + try std.testing.expectEqual(@as(u32, 0), (out[at] >> 8) & 0xFF); +} + test "a packed MXFP8 block holds fp8g's code words and each row's scale at byte 4 gq + j" { const gpa = std.testing.allocator; const n = 64; diff --git a/zig/tests/cuda/stored_experts_check.zig b/zig/tests/cuda/stored_experts_check.zig index 00954ab79f5..e5c8c02b8bf 100644 --- a/zig/tests/cuda/stored_experts_check.zig +++ b/zig/tests/cuda/stored_experts_check.zig @@ -170,7 +170,7 @@ pub fn outputs(gpu: Gpu, s: st.Stored, layer: usize) !void { var sum: [2]f64 = .{ 0, 0 }; var abs: [2]f64 = .{ 0, 0 }; for (0..2) |m| for (0..st.hidden) |i| { - const t = c.fromBf16(xr[i]) * s.w13.f64At(s.nv, e, m * st.width + j, i); + const t = c.fromBf16(xr[i]) * s.w13.f64At(s.nv, e, 2 * j + m, i); sum[m] += t; abs[m] += @abs(t); }; @@ -201,3 +201,56 @@ pub fn outputs(gpu: Gpu, s: st.Stored, layer: usize) !void { check.pass("layer {d} {s} {d} tokens ({s}): {d} gate-up and {d} down outputs within the fp32 bound; worst err/bound {d:.3} and {d:.3}", .{ layer, if (s.nv) "NVFP4" else "MXFP8", tokens, if (prompt) "prompt form" else "decode form", pairs * st.width, pairs * st.hidden, worst[0], worst[1] }); } } + +/// MXFP8's E8M0 edges through tf_mxfp8_down_f32: scale byte 0 is 2^-127 (not 0, not 2^-126). +pub fn e8m0Edges(gpu: Gpu) !void { + const a = gpu.gpa; + const n = 32; + const k = 32; + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var k8 = try mx.Mxfp8Experts.load(gpu.d, sms); + defer k8.unload(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const router = try grouped.Router.resolve(mod); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + const edges = [_]u8{ 0, 1, 2, 126, 127, 128, 200, 240 }; // 448 x 2^113 still fits fp32 + const values = [_]u8{ 0x38, 0x7E, 0x30, 0xB8 }; // 1, 448, 0.5, -1: each times 2^-127 stays a bf16 (>= 2^-133) + var codes: [n * k]u8 = undefined; + var scales: [n]u8 = undefined; + for (0..n) |r| { + scales[r] = edges[r % edges.len]; + for (0..k) |i| codes[r * k + i] = values[(r / edges.len + i) % values.len]; + } + var blocks: [mx.Mxfp8Experts.words]u32 = undefined; + mx.Mxfp8Experts.packOne(&blocks, &codes, &scales, n, k); + var w = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&blocks)); + defer w.free(); + var eye: [k * k]u16 = @splat(0); + for (0..k) |i| eye[i * k + i] = 0x3F80; + var x = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&eye)); + defer x.free(); + var ids: [k]i32 = @splat(0); + var dids = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.sliceAsBytes(&ids)); + defer dids.free(); + var pb = try st.PlanBufs.init(gpu, k, 16); + defer pb.deinit(); + try router.route(stream, dids.ptr, k, st.experts, 16, pb.plan); + var out = try cuda.DeviceBuffer.alloc(gpu.d, k * n * 4); + defer out.free(); + try out.fill8(0xff, stream.handle); + const l: ex_.Layer = .{ .format = .mxfp8, .up = 0, .down = w.ptr, .width = k, .dims = n, .experts = st.experts, .caps = .{ 4, 25 } }; + const gx: ex_.Grouped = .{ .mxfp8 = &k8 }; + try gx.decode(stream, .down_f32, .{ .x = x.ptr, .stride = k }, l, pb.plan, out.ptr, pb.items, k, 16, -1); + try stream.synchronize(); + const got = try a.alloc(f32, k * n); + defer a.free(got); + try out.download(0, std.mem.sliceAsBytes(got)); + for (0..k) |i| for (0..n) |r| { + const want: f32 = @floatCast(core.expert_decode.mxfp8(&codes, &scales, k, r, i)); + try check.expect(got[i * n + r] == want, "E8M0 byte {d}, code {x}: {e}, host {e}", .{ scales[r], codes[r * k + i], got[i * n + r], want }); + }; + try check.expect(core.expert_decode.e8m0(0) == 0x1p-127, "host E8M0 byte 0", .{}); + check.pass("MXFP8 E8M0 bytes {any} decode exactly on the GPU (byte 0 = 2^-127)", .{edges}); +} diff --git a/zig/tests/cuda/stored_experts_tests.zig b/zig/tests/cuda/stored_experts_tests.zig index 37c00d2d9ef..ffd3b283aa4 100644 --- a/zig/tests/cuda/stored_experts_tests.zig +++ b/zig/tests/cuda/stored_experts_tests.zig @@ -86,13 +86,17 @@ pub const Stored = struct { defer a.free(up); const down = try a.alloc(u32, experts * down_words); defer a.free(down); - const half_c = s.w13.expertCodes(0).len / 2; - const half_s = s.w13.expertScales(0).len / 2; + const cb = s.w13.expertCodes(0).len; // w13 rows interleave gate and up (row 2j gate j, 2j + 1 up j) + const sb = s.w13.expertScales(0).len; + const split = try a.alloc(u8, cb + sb); + defer a.free(split); for (0..experts) |e| { - const c13 = s.w13.expertCodes(e); - const s13 = s.w13.expertScales(e); - const gate = [2][]const u8{ c13[0..half_c], s13[0..half_s] }; - const upm = [2][]const u8{ c13[half_c..], s13[half_s..] }; + const rc = cb / (2 * width); + const rs = sb / (2 * width); + mx.splitGateUp(s.w13.expertCodes(e), rc, split[0 .. cb / 2], split[cb / 2 .. cb]); + mx.splitGateUp(s.w13.expertScales(e), rs, split[cb..][0 .. sb / 2], split[cb + sb / 2 ..][0 .. sb / 2]); + const gate = [2][]const u8{ split[0 .. cb / 2], split[cb..][0 .. sb / 2] }; + const upm = [2][]const u8{ split[cb / 2 .. cb], split[cb + sb / 2 ..][0 .. sb / 2] }; const o = up[e * up_words ..][0..up_words]; const d = down[e * down_words ..][0..down_words]; if (s.nv) { @@ -158,6 +162,7 @@ pub fn ckpt(gpu: Gpu, dir: []const u8) !void { defer gpu.gpa.free(path); var f = try core.safetensors.File.openPrefix(gpu.gpa, gpu.io, path, "model.llm.layers."); defer f.close(gpu.io); + try @import("stored_experts_check.zig").e8m0Edges(gpu); for ([_]usize{ 0, 20 }) |layer| { const s = try Stored.read(&f, layer); try invariants(s, layer); From 1e2b326070dd67e4038738fdb6f5665683799941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:52:43 +0100 Subject: [PATCH 04/84] core: visit_plan, a looped stack's steps and state slots; Dory's schedule on it core/visit_plan.zig walks prelude, core x passes and coda, numbering each state kind's slots in run order, with enter/leave per pass and taps as step inputs or the post-norm output. Dory's schedule.build now uses it; its Step, Schedule and tests are unchanged (test-dory-host 43 pass, 3 skip, same as main). --- build.zig | 1 + zig/build/visit_plan_host.zig | 11 ++ zig/src/core/root.zig | 2 + zig/src/core/visit_plan.zig | 165 +++++++++++++++++++++++++++++ zig/src/families/dory/schedule.zig | 47 ++++---- 5 files changed, 208 insertions(+), 18 deletions(-) create mode 100644 zig/build/visit_plan_host.zig create mode 100644 zig/src/core/visit_plan.zig diff --git a/build.zig b/build.zig index 54d7e47382d..3e1ee0effb1 100644 --- a/build.zig +++ b/build.zig @@ -120,6 +120,7 @@ pub fn build(b: *std.Build) void { } @import("zig/build/h3_host.zig").tests(b, target, test_step); @import("zig/build/ling_host.zig").tests(b, target, test_step); + @import("zig/build/visit_plan_host.zig").tests(b, target, test_step); @import("zig/build/inkling2_host.zig").tests(b, target, test_step); @import("zig/build/gpt_oss_host.zig").tests(b, test_step); @import("zig/build/digest.zig").steps(b, test_step, draft_ids, build_options); diff --git a/zig/build/visit_plan_host.zig b/zig/build/visit_plan_host.zig new file mode 100644 index 00000000000..4e9c372db61 --- /dev/null +++ b/zig/build/visit_plan_host.zig @@ -0,0 +1,11 @@ +//! The core visit plan's host tests (no GPU): a looped stack's steps, passes, state slots and taps. +const std = @import("std"); + +pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { + const root = b.path("zig/src/core/visit_plan.zig"); + const m = b.createModule(.{ .root_source_file = root, .target = target, .optimize = .Debug }); + const run = b.addRunArtifact(b.addTest(.{ .root_module = m })); + const about = "Core visit plan: prelude, core passes, coda, state slots by kind and taps"; + b.step("test-visit-plan-host", about).dependOn(&run.step); + test_step.dependOn(&run.step); +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 8ae5fa0a520..799ae92e2eb 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -26,6 +26,7 @@ pub const draft_depth = @import("draft_depth.zig"); pub const prompt_tail = @import("prompt_tail.zig"); pub const CopyIndex = @import("copy_index.zig").CopyIndex; pub const recurrent_workspace = @import("recurrent_workspace.zig"); +pub const visit_plan = @import("visit_plan.zig"); // a looped stack's steps and state slots (Dory, Inkling 2 Mini) pub const tokenizer = @import("tokenizer"); // a module of its own, so the native server shares it pub const proposal_rows = @import("proposal_rows.zig"); pub const torch_pth = @import("torch_pth.zig"); // torch.save archives read without Python: Drama 3's codec @@ -149,6 +150,7 @@ test { _ = kv_pool; _ = kv_prompts; _ = state_walk; + _ = visit_plan; } pub const frame_rounds = @import("frame_rounds.zig"); diff --git a/zig/src/core/visit_plan.zig b/zig/src/core/visit_plan.zig new file mode 100644 index 00000000000..0c1eeec5193 --- /dev/null +++ b/zig/src/core/visit_plan.zig @@ -0,0 +1,165 @@ +//! A looped stack's walk: prelude, core × passes, coda; each step's layer, pass and state slots, numbered in run order. +const std = @import("std"); + +/// Layers [start, end) run `passes` times between the prelude [0, start) and the coda [end, layers). +pub const Loop = struct { start: u32, end: u32, passes: u32 }; + +/// No loop: every layer once. +pub const straight: Loop = .{ .start = 0, .end = 0, .passes = 1 }; + +/// Where a drafter's tap reads: the hidden state entering a step, or the stack's output after the final norm. +pub const Tap = union(enum) { input: u32, output }; + +/// Steps a stack of `layers` runs under `loop`; error.Layout when the core is outside the stack or runs no pass. +pub fn stepCount(layers: u32, loop: Loop) error{Layout}!u64 { + const passes_ok = loop.passes > 0 and loop.passes <= std.math.maxInt(u8) + 1; + if (loop.start > loop.end or loop.end > layers or !passes_ok) return error.Layout; + return @as(u64, layers) + @as(u64, loop.passes - 1) * (loop.end - loop.start); +} + +/// The walk of a stack whose layers keep states of the kinds in enum `Kind`, at most `max` steps. +pub fn Plan(comptime Kind: type, comptime max: usize) type { + const kinds = @typeInfo(Kind).@"enum".field_names.len; + return struct { + const Self = @This(); + + pub const Step = struct { + layer: u16, + pass: u8 = 0, // 0 outside the core + slot: [kinds]?u16 = @splat(null), // the step's state of each kind, numbered in run order within the kind + enter: bool = false, // the core's first layer, at every pass + leave: bool = false, // the core's last layer, at every pass + + pub fn of(s: Step, k: Kind) ?u16 { + return s.slot[@backingInt(k)]; + } + }; + + steps: [max]Step = undefined, + len: u32 = 0, + counts: [kinds]u32 = @splat(0), + loop: Loop = straight, + layers: u32 = 0, // physical layers + + pub fn slice(p: *const Self) []const Step { + return p.steps[0..p.len]; + } + + /// Slots of `k`: one per step whose layer keeps that state. + pub fn count(p: *const Self, k: Kind) u32 { + return p.counts[@backingInt(k)]; + } + + /// The walk of `layers` under `loop`; `holds.keeps(layer, kind)`: the states a layer keeps at every visit. + pub fn build(layers: u32, loop: Loop, holds: anytype) error{ Layout, TooManySteps }!Self { + if (try stepCount(layers, loop) > max) return error.TooManySteps; + var p: Self = .{ .loop = loop, .layers = layers }; + for (0..loop.start) |i| p.add(holds, @intCast(i), 0); + for (0..loop.passes) |pass| { + const first = p.len; + for (loop.start..loop.end) |i| p.add(holds, @intCast(i), @intCast(pass)); + if (p.len == first) continue; + p.steps[first].enter = true; + p.steps[p.len - 1].leave = true; + } + for (loop.end..layers) |i| p.add(holds, @intCast(i), 0); + return p; + } + + fn add(p: *Self, holds: anytype, layer: u16, pass: u8) void { + var s: Step = .{ .layer = layer, .pass = pass }; + inline for (0..kinds) |k| { + if (holds.keeps(layer, @as(Kind, @fromBackingInt(@intCast(k))))) { + s.slot[k] = @intCast(p.counts[k]); + p.counts[k] += 1; + } + } + p.steps[p.len] = s; + p.len += 1; + } + + /// The step `layer` runs at `pass` (pass 0 outside the core), or null when the walk has none. + pub fn visit(p: *const Self, layer: u32, pass: u32) ?u32 { + const l = p.loop; + const core = l.end - l.start; + if (layer < l.start) return if (pass == 0) layer else null; + if (layer < l.end) return if (pass < l.passes) l.start + pass * core + (layer - l.start) else null; + return if (pass == 0 and layer < p.layers) layer + (l.passes - 1) * core else null; + } + + /// Tap t < step count reads the input to step t; t = step count, the output after the final norm. + pub fn tap(p: *const Self, t: u32) error{NoSuchStep}!Tap { + if (t < p.len) return .{ .input = t }; + if (t == p.len) return .output; + return error.NoSuchStep; + } + }; +} + +const testing = std.testing; + +const Two = enum { sliding, full }; + +/// Every third layer keeps a full cache, the others a sliding one; layer 1 keeps none. +const Thirds = struct { + fn keeps(_: Thirds, layer: u16, k: Two) bool { + if (layer == 1) return false; + return (k == .full) == (layer % 3 == 2); + } +}; + +test "a looped walk: prelude once, the core each pass with enter and leave, coda once, slots in run order" { + const P = Plan(Two, 64); + const p = try P.build(8, .{ .start = 2, .end = 5, .passes = 3 }, Thirds{}); + try testing.expectEqual(@as(u32, 8 + 2 * 3), p.len); + const layers = [_]u16{ 0, 1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 5, 6, 7 }; + const passes = [_]u8{ 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0 }; + for (p.slice(), layers, passes, 0..) |s, l, ps, i| { + try testing.expectEqual(l, s.layer); + try testing.expectEqual(ps, s.pass); + try testing.expectEqual(l == 2, s.enter); + try testing.expectEqual(l == 4, s.leave); + try testing.expectEqual(@as(?u32, @intCast(i)), p.visit(l, ps)); + } + // full at layers 2 and 5 (each core pass, then the coda): 4 slots; sliding at the rest but layer 1: 9 + try testing.expectEqual(@as(u32, 4), p.count(.full)); + try testing.expectEqual(@as(u32, 9), p.count(.sliding)); + try testing.expectEqual(@as(?u16, null), p.steps[1].of(.sliding)); + try testing.expectEqual(@as(?u16, null), p.steps[1].of(.full)); + const full = [_]u32{ 2, 5, 8, 11 }; + for (full, 0..) |at, n| try testing.expectEqual(@as(?u16, @intCast(n)), p.steps[at].of(.full)); + var next: u16 = 0; + for (p.slice()) |s| if (s.of(.sliding)) |slot| { + try testing.expectEqual(next, slot); + try testing.expectEqual(@as(?u16, null), s.of(.full)); + next += 1; + }; + try testing.expectEqual(@as(?u32, null), p.visit(2, 3)); + try testing.expectEqual(@as(?u32, null), p.visit(0, 1)); + try testing.expectEqual(@as(?u32, null), p.visit(8, 0)); +} + +test "no loop: every layer once at pass 0, nothing enters or leaves, taps are inputs then the output" { + const P = Plan(Two, 16); + const p = try P.build(6, straight, Thirds{}); + try testing.expectEqual(@as(u32, 6), p.len); + for (p.slice(), 0..) |s, i| { + try testing.expectEqual(@as(u16, @intCast(i)), s.layer); + try testing.expect(s.pass == 0 and !s.enter and !s.leave); + try testing.expectEqual(@as(?u32, @intCast(i)), p.visit(@intCast(i), 0)); + } + try testing.expectEqual(Tap{ .input = 5 }, try p.tap(5)); + try testing.expectEqual(Tap.output, try p.tap(6)); + try testing.expectError(error.NoSuchStep, p.tap(7)); +} + +test "a core outside the stack, no pass, too many passes or too many steps is refused" { + const P = Plan(Two, 16); + try testing.expectError(error.Layout, P.build(6, .{ .start = 4, .end = 3, .passes = 2 }, Thirds{})); + try testing.expectError(error.Layout, P.build(6, .{ .start = 2, .end = 7, .passes = 2 }, Thirds{})); + try testing.expectError(error.Layout, P.build(6, .{ .start = 2, .end = 4, .passes = 0 }, Thirds{})); + try testing.expectError(error.Layout, P.build(6, .{ .start = 2, .end = 4, .passes = 257 }, Thirds{})); + try testing.expectError(error.TooManySteps, P.build(6, .{ .start = 2, .end = 4, .passes = 7 }, Thirds{})); + _ = try P.build(6, .{ .start = 2, .end = 4, .passes = 6 }, Thirds{}); + try testing.expectEqual(@as(u64, 6 + 255 * 2), try stepCount(6, .{ .start = 2, .end = 4, .passes = 256 })); +} diff --git a/zig/src/families/dory/schedule.zig b/zig/src/families/dory/schedule.zig index 935745c9ae7..fb8e7f65796 100644 --- a/zig/src/families/dory/schedule.zig +++ b/zig/src/families/dory/schedule.zig @@ -1,6 +1,7 @@ //! Dory's sublayer order: input, the recurrent block `loops` times, output; per_loop KV caches, one an attention step. const std = @import("std"); const config = @import("config.zig"); +const visit_plan = @import("core").visit_plan; const Config = config.Config; const Kind = config.Kind; @@ -42,28 +43,38 @@ pub const Schedule = struct { } }; +/// Dory's one state kind: an attention sublayer's KV cache (sliding or full by its sublayer's kind). +const State = enum { cache }; +const Walk = visit_plan.Plan(State, max_steps); + +const Holds = struct { + c: *const Config, + pub fn keeps(h: Holds, sub: u16, _: State) bool { + return h.c.kinds[sub] != .mlp; + } +}; + /// The steps of `c` at `c.loops` loops: I + R * loops + O, caches numbered in the order the steps run. pub fn build(c: Config) Schedule { + const core_end: u32 = @intCast(c.input + c.recurrent); + const loop: visit_plan.Loop = .{ .start = @intCast(c.input), .end = core_end, .passes = @intCast(c.loops) }; + // config.parse and withLoops bound sublayers by max_sublayers and loops to 1..max_loops + const w = Walk.build(@intCast(c.sublayers), loop, Holds{ .c = &c }) catch unreachable; var s: Schedule = .{}; - const add = struct { - fn one(sch: *Schedule, cc: Config, sub: usize, loop: usize) void { - var st: Step = .{ .sub = @intCast(sub), .kind = cc.kinds[sub], .loop = @intCast(loop) }; - if (st.kind != .mlp) { - st.cache = @intCast(sch.caches); - sch.cache_kind[sch.caches] = st.kind; - sch.caches += 1; - } - sch.steps[sch.len] = st; - sch.len += 1; - } - }.one; - for (0..c.input) |i| add(&s, c, i, 0); - for (0..c.loops) |l| { - for (c.input..c.input + c.recurrent) |i| add(&s, c, i, l); - s.steps[s.len - c.recurrent].enter = true; - s.steps[s.len - 1].leave = true; + for (w.slice()) |v| { + const st: Step = .{ + .sub = v.layer, + .kind = c.kinds[v.layer], + .loop = v.pass, + .cache = v.of(.cache), + .enter = v.enter, + .leave = v.leave, + }; + if (st.cache) |i| s.cache_kind[i] = st.kind; + s.steps[s.len] = st; + s.len += 1; } - for (c.input + c.recurrent..c.sublayers) |i| add(&s, c, i, 0); + s.caches = w.count(.cache); return s; } From fe7de25ff407e826fa7cba8a7e5d8823243a1613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:49:16 +0100 Subject: [PATCH 05/84] inkling2: Mini's host side (H2): loop_config, visits on core/visit_plan, controller and cross-pass names inkling2_loop parses its loop_config (is_varloop refused, core in whole blocks, passes >= 2, rank <= 128) and counts the drafter's taps by visit. The plan walks the visits through core/visit_plan.zig with a sliding, full and conv slot kind. names.zig adds the four controllers a core layer and the two cross-pass query tables; each layer's expert precision stays read from its w13 dtype. The quantization_config goes through core.modelopt (admitByTensors, std-only modelopt_config.zig split out so host-only tests import it). Fixtures: Mini's config.json and its two headers folded (1244 + 54 tensors, sha256 of the unfolded lines). --- zig/build/inkling2_host.zig | 2 + zig/src/core/modelopt.zig | 113 +++-------- zig/src/core/modelopt_config.zig | 101 ++++++++++ zig/src/families/inkling2/config.zig | 103 ++++++++-- .../inkling2/fixtures/mini_config.json | 122 ++++++++++++ .../inkling2/fixtures/mini_model_header.txt | 86 +++++++++ .../inkling2/fixtures/mini_mtp_header.txt | 25 +++ zig/src/families/inkling2/host_test.zig | 1 + zig/src/families/inkling2/mini_host_test.zig | 180 ++++++++++++++++++ zig/src/families/inkling2/names.zig | 22 ++- zig/src/families/inkling2/plan.zig | 47 ++++- 11 files changed, 696 insertions(+), 106 deletions(-) create mode 100644 zig/src/core/modelopt_config.zig create mode 100644 zig/src/families/inkling2/fixtures/mini_config.json create mode 100644 zig/src/families/inkling2/fixtures/mini_model_header.txt create mode 100644 zig/src/families/inkling2/fixtures/mini_mtp_header.txt create mode 100644 zig/src/families/inkling2/mini_host_test.zig diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 423dd15b0fc..3666ede3614 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -7,6 +7,8 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin m.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path(dir ++ "tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true })); m.addImport("safetensors", b.createModule(.{ .root_source_file = b.path(dir ++ "safetensors.zig"), .target = target, .optimize = optimize, .link_libc = true })); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); + m.addImport("visit_plan", b.createModule(.{ .root_source_file = b.path(dir ++ "visit_plan.zig"), .target = target, .optimize = optimize })); + m.addImport("modelopt", b.createModule(.{ .root_source_file = b.path(dir ++ "modelopt_config.zig"), .target = target, .optimize = optimize, .link_libc = true })); return m; } diff --git a/zig/src/core/modelopt.zig b/zig/src/core/modelopt.zig index 8a3951df906..cac64a57157 100644 --- a/zig/src/core/modelopt.zig +++ b/zig/src/core/modelopt.zig @@ -1,12 +1,23 @@ //! ModelOpt config checks: NVFP4 (groups of 16; tensors, not ignore, say which linears) and MIXED_PRECISION recipes. const std = @import("std"); +const config = @import("modelopt_config.zig"); + +/// The config checks (std only, so host-only family tests can import them without the checkpoint reader). +pub const Why = config.Why; +pub const admit = config.admit; +pub const admitByTensors = config.admitByTensors; +pub const object = config.object; +pub const text = config.text; +pub const int = config.int; +const nvfp4 = config.nvfp4; +const block = config.block; /// One projection's tensors read and checked (weight, block scales, weight_scale_2, input_scale). pub const part = @import("modelopt_part.zig"); /// The NVFP4 group size ModelOpt writes for this format. -pub const nvfp4_group = 16; +pub const nvfp4_group = config.nvfp4_group; /// The group size of csf0_v1, this engine's own: no other reader takes it. pub const csf0_group = 32; @@ -57,35 +68,6 @@ pub const Recipes = struct { } }; -/// Why the check refused the checkpoint, kept for the caller's log line (tests read it instead). -pub const Why = struct { - buf: [320]u8 = undefined, - len: usize = 0, - - /// Keep the reason, cut short if it is long. - pub fn set(self: *Why, comptime fmt: []const u8, args: anytype) void { - var w: std.Io.Writer = .fixed(&self.buf); - w.print(fmt, args) catch {}; - self.len = w.end; - } - - pub fn text(self: *const Why) []const u8 { - return self.buf[0..self.len]; - } -}; - -/// config.json's quantization_config (top level, else text_config's) checked as ModelOpt NVFP4. -pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); - const q = block(root) orelse { - why.set("config.json has no ModelOpt quantization_config", .{}); - return error.NotModelOpt; - }; - try nvfp4(q, why); -} - /// `admit`'s check, with MIXED_PRECISION read: a quantized_layers entry no `Recipe` names is refused by its module. pub fn admitRecipes(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !Recipes { var arena = std.heap.ArenaAllocator.init(gpa); @@ -160,59 +142,6 @@ fn pair(v: ?std.json.Value, rows: i64, cols: i64) bool { return int(x.array.items[0]) == rows and int(x.array.items[1]) == cols; } -/// The quantization_config's NVFP4 check: quant_algo NVFP4, every config group 4-bit floats in groups of 16. -fn nvfp4(q: std.json.ObjectMap, why: *Why) !void { - const algo = text(q.get("quant_algo")) orelse ""; - if (!std.ascii.eqlIgnoreCase(algo, "NVFP4")) { - const named = if (algo.len > 0) algo else "without quant_algo"; - why.set("ModelOpt {s}: this engine reads ModelOpt NVFP4 (nvidia/GLM-5.3-Flash-NVFP4's layout)", .{named}); - return error.UnsupportedQuant; - } - const groups = object(q.get("config_groups")) orelse { - why.set("ModelOpt NVFP4 without config_groups", .{}); - return error.UnsupportedQuant; - }; - var it = groups.iterator(); - while (it.next()) |g| { - const w = if (object(g.value_ptr.*)) |o| object(o.get("weights")) else null; - const bits = if (w) |o| int(o.get("num_bits")) else null; - const size = if (w) |o| int(o.get("group_size")) else null; - const kind = if (w) |o| text(o.get("type")) orelse "" else ""; - if (bits != 4 or size != nvfp4_group or !std.mem.eql(u8, kind, "float")) { - why.set( - "ModelOpt NVFP4 group {s}: weights {?d}-bit {s} in groups of {?d}, " ++ - "expected 4-bit float in groups of 16", - .{ g.key_ptr.*, bits, kind, size }, - ); - return error.UnsupportedQuant; - } - } -} - -fn block(root: std.json.Value) ?std.json.ObjectMap { - const top = object(root) orelse return null; - for ([_]?std.json.ObjectMap{ top, object(top.get("text_config")) }) |source| { - const q = object((source orelse continue).get("quantization_config")) orelse continue; - if (std.ascii.eqlIgnoreCase(text(q.get("quant_method")) orelse "", "modelopt")) return q; - } - return null; -} - -pub fn object(v: ?std.json.Value) ?std.json.ObjectMap { - const x = v orelse return null; - return if (x == .object) x.object else null; -} - -pub fn text(v: ?std.json.Value) ?[]const u8 { - const x = v orelse return null; - return if (x == .string) x.string else null; -} - -pub fn int(v: ?std.json.Value) ?i64 { - const x = v orelse return null; - return if (x == .integer) x.integer else null; -} - test "nvidia/GLM-5.3-Flash-NVFP4's config is admitted" { var why: Why = .{}; try admit(std.testing.allocator, @embedFile("fixtures/glm53_flash_nvfp4/config.json"), &why); @@ -253,6 +182,24 @@ test "other ModelOpt formats, and configs without ModelOpt, are refused by name" , &why); } +test "admitByTensors: NVFP4 without config_groups is admitted; other algos and bad groups are refused by name" { + var why: Why = .{}; + try admitByTensors(std.testing.allocator, "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"NVFP4\"}}", &why); + const fp8 = "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"FP8\"}}"; + try std.testing.expectError(error.UnsupportedQuant, admitByTensors(std.testing.allocator, fp8, &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "ModelOpt FP8") != null); + const g32 = + \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", "config_groups": + \\ {"g": {"weights": {"num_bits": 4, "type": "float", "group_size": 32}}}}} + ; + try std.testing.expectError(error.UnsupportedQuant, admitByTensors(std.testing.allocator, g32, &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "groups of 32") != null); + try std.testing.expectError(error.NotModelOpt, admitByTensors(std.testing.allocator, "{\"text_config\": {}}", &why)); + // admit itself still asks for config_groups + const bare = "{\"quantization_config\": {\"quant_method\": \"modelopt\", \"quant_algo\": \"NVFP4\"}}"; + try std.testing.expectError(error.UnsupportedQuant, admit(std.testing.allocator, bare, &why)); +} + test "nvidia/GLM-5.3-Flash-FP4-Local's recipes: a module's, and its tensors' under it" { var why: Why = .{}; var r = try admitRecipes(std.testing.allocator, @embedFile("fixtures/glm53_flash_fp4_local/config.json"), &why); diff --git a/zig/src/core/modelopt_config.zig b/zig/src/core/modelopt_config.zig new file mode 100644 index 00000000000..4e6b8011028 --- /dev/null +++ b/zig/src/core/modelopt_config.zig @@ -0,0 +1,101 @@ +//! ModelOpt quantization_config checks on config.json alone (std only): NVFP4 in groups of 16, read by modelopt.zig. +const std = @import("std"); + +/// The NVFP4 group size ModelOpt writes for this format. +pub const nvfp4_group = 16; + +/// Why the check refused the checkpoint, kept for the caller's log line (tests read it instead). +pub const Why = struct { + buf: [320]u8 = undefined, + len: usize = 0, + + /// Keep the reason, cut short if it is long. + pub fn set(self: *Why, comptime fmt: []const u8, args: anytype) void { + var w: std.Io.Writer = .fixed(&self.buf); + w.print(fmt, args) catch {}; + self.len = w.end; + } + + pub fn text(self: *const Why) []const u8 { + return self.buf[0..self.len]; + } +}; + +/// config.json's quantization_config (top level, else text_config's) checked as ModelOpt NVFP4. +pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); + const q = block(root) orelse { + why.set("config.json has no ModelOpt quantization_config", .{}); + return error.NotModelOpt; + }; + try nvfp4(q, why); +} + +/// `admit` for a checkpoint whose tensors name each layer's format (Inkling 2 Mini: NVFP4 and MXFP8 experts by dtype): +/// quant_algo NVFP4, and config_groups, when declared, as `admit` checks them. +pub fn admitByTensors(gpa: std.mem.Allocator, config_json: []const u8, why: *Why) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), config_json, .{}); + const q = block(root) orelse { + why.set("config.json has no ModelOpt quantization_config", .{}); + return error.NotModelOpt; + }; + if (q.get("config_groups") == null and std.ascii.eqlIgnoreCase(text(q.get("quant_algo")) orelse "", "NVFP4")) return; + try nvfp4(q, why); +} + +/// The quantization_config's NVFP4 check: quant_algo NVFP4, every config group 4-bit floats in groups of 16. +pub fn nvfp4(q: std.json.ObjectMap, why: *Why) !void { + const algo = text(q.get("quant_algo")) orelse ""; + if (!std.ascii.eqlIgnoreCase(algo, "NVFP4")) { + const named = if (algo.len > 0) algo else "without quant_algo"; + why.set("ModelOpt {s}: this engine reads ModelOpt NVFP4 (nvidia/GLM-5.3-Flash-NVFP4's layout)", .{named}); + return error.UnsupportedQuant; + } + const groups = object(q.get("config_groups")) orelse { + why.set("ModelOpt NVFP4 without config_groups", .{}); + return error.UnsupportedQuant; + }; + var it = groups.iterator(); + while (it.next()) |g| { + const w = if (object(g.value_ptr.*)) |o| object(o.get("weights")) else null; + const bits = if (w) |o| int(o.get("num_bits")) else null; + const size = if (w) |o| int(o.get("group_size")) else null; + const kind = if (w) |o| text(o.get("type")) orelse "" else ""; + if (bits != 4 or size != nvfp4_group or !std.mem.eql(u8, kind, "float")) { + why.set( + "ModelOpt NVFP4 group {s}: weights {?d}-bit {s} in groups of {?d}, " ++ + "expected 4-bit float in groups of 16", + .{ g.key_ptr.*, bits, kind, size }, + ); + return error.UnsupportedQuant; + } + } +} + +pub fn block(root: std.json.Value) ?std.json.ObjectMap { + const top = object(root) orelse return null; + for ([_]?std.json.ObjectMap{ top, object(top.get("text_config")) }) |source| { + const q = object((source orelse continue).get("quantization_config")) orelse continue; + if (std.ascii.eqlIgnoreCase(text(q.get("quant_method")) orelse "", "modelopt")) return q; + } + return null; +} + +pub fn object(v: ?std.json.Value) ?std.json.ObjectMap { + const x = v orelse return null; + return if (x == .object) x.object else null; +} + +pub fn text(v: ?std.json.Value) ?[]const u8 { + const x = v orelse return null; + return if (x == .string) x.string else null; +} + +pub fn int(v: ?std.json.Value) ?i64 { + const x = v orelse return null; + return if (x == .integer) x.integer else null; +} diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index b4143603140..fbe9178b579 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -1,9 +1,16 @@ -//! Inkling 2 Small's shape from config.json (inkling2), refusing every layout the engine does not run. +//! Inkling 2's shape from config.json: Small (inkling2) and the looped Mini (inkling2_loop); other layouts refused. const std = @import("std"); +const modelopt = @import("modelopt"); -/// The most backbone layers the plan tables hold (Inkling 2 Small has 48). +/// The most backbone layers the plan tables hold (Inkling 2 Small has 48, Mini 24). pub const max_layers = 128; +/// The most layer visits a token makes (Mini: 24 layers, layers 6..17 three times, so 48). +pub const max_visits = 256; + +/// The widest gate rank the loop kernels hold (loop.cu kMaxRank; Mini's gate_rank is 64). +pub const max_gate_rank = 128; + /// Every sixth layer attends over the whole context; the reference derives its layer types the same way. pub const global_every = 6; @@ -37,6 +44,10 @@ pub const Why = struct { /// One attention geometry: sliding layers read the `swa_*` keys, global layers the plain ones. pub const Heads = struct { q: u32, kv: u32, dim: u32 }; +/// loop_config: layers [start, end) run `passes` times; passes after the first restart from the core's entry state +/// and take gated messages (rank `rank`) from the pass before. +pub const Loop = struct { start: u32, end: u32, passes: u32, rank: u32 }; + pub const Text = struct { hidden: u32, layers: u32, @@ -61,6 +72,13 @@ pub const Text = struct { up_cap: f32, logit_cap: f32, max_context: u32, + loop: ?Loop = null, // inkling2_loop only + + /// Layer visits a token makes: every layer once, the core's layers once a pass. + pub fn visits(c: *const Text) u32 { + const l = c.loop orelse return c.layers; + return c.layers + (l.passes - 1) * (l.end - l.start); + } pub fn heads(c: *const Text, i: u32) Heads { return if (isGlobal(i)) c.global else c.local; @@ -72,7 +90,7 @@ pub const Text = struct { } }; -/// The draft head's shape (mtp_config); the target taps are indices into the backbone, `layers` meaning the final norm. +/// The draft head's shape (mtp_config); taps are layer visits (`Text.visits()`: the output after the final norm). pub const Mtp = struct { layers: u32, q_heads: u32, @@ -192,7 +210,7 @@ fn layerTypes(o: std.json.ObjectMap, layers: u32, why: *Why) !void { } } -fn parseText(o: std.json.ObjectMap, why: *Why) !Text { +fn parseText(o: std.json.ObjectMap, looped: bool, why: *Why) !Text { var t: Text = undefined; t.hidden = try int(o, "hidden_size", why); t.layers = try int(o, "num_hidden_layers", why); @@ -261,9 +279,45 @@ fn parseText(o: std.json.ObjectMap, why: *Why) !Text { return error.Unsupported; }; try layerTypes(o, t.layers, why); + t.loop = null; + if (looped) { + try fixed(o, "attn_res_normalize_values", true, why); + t.loop = try parseLoop(try object(o, "loop_config", why), &t, why); + } else if (o.get("loop_config") != null) { + why.set("loop_config needs model_type inkling2_loop", .{}); + return error.Unsupported; + } return t; } +/// loop_config: a fixed pass count (is_varloop refused) over a core of whole attention-residual blocks. +fn parseLoop(o: std.json.ObjectMap, t: *const Text, why: *Why) !Loop { + if (o.get("is_varloop")) |v| if (v != .bool or v.bool) { + why.set("loop_config.is_varloop must be false: the engine runs a fixed number of passes", .{}); + return error.Unsupported; + }; + const l: Loop = .{ + .start = try int(o, "core_start", why), + .end = try int(o, "core_end", why), + .passes = try int(o, "num_passes", why), + .rank = try int(o, "gate_rank", why), + }; + if (l.start >= l.end or l.end > t.layers or l.start % t.block != 0 or l.end % t.block != 0) { + why.set("loop_config core [{d}, {d}) is not whole blocks of {d} inside the {d} layers", .{ l.start, l.end, t.block, t.layers }); + return error.Layout; + } + if (l.passes < 2 or l.rank > max_gate_rank) { + why.set("loop_config: num_passes {d} must be at least 2 and gate_rank {d} at most {d}", .{ l.passes, l.rank, max_gate_rank }); + return error.Layout; + } + const visits = @as(u64, t.layers) + @as(u64, l.passes - 1) * (l.end - l.start); + if (visits > max_visits) { + why.set("{d} layer visits: the plan tables hold {d}", .{ visits, max_visits }); + return error.Layout; + } + return l; +} + fn parseVision(o: std.json.ObjectMap, text_hidden: u32, why: *Why) !Vision { var v: Vision = undefined; v.hidden = try int(o, "hidden_size", why); @@ -311,29 +365,35 @@ fn parseMtp(o: std.json.ObjectMap, t: *const Text, why: *Why) !Mtp { m.local[@intCast(e.integer)] = true; } for (taps.array.items) |e| { - if (e != .integer or e.integer < 0 or e.integer > t.layers) { + if (e != .integer or e.integer < 0 or e.integer > t.visits()) { why.set("mtp_config's target_layer_ids names a layer the backbone does not have", .{}); return error.Layout; } + if (t.loop != null and m.taps_n > 0 and e.integer <= m.taps[m.taps_n - 1]) { + why.set("mtp_config's target_layer_ids must rise: they name visits in run order", .{}); + return error.Layout; + } m.taps[m.taps_n] = @intCast(e.integer); m.taps_n += 1; } return m; } -/// A quantization_config in config.json must be ModelOpt NVFP4, which the experts' header dtype refines per layer. -fn quantization(o: std.json.ObjectMap, why: *Why) !void { +/// A quantization_config must be ModelOpt NVFP4 (core.modelopt); each layer's expert format is its tensors' dtype. +fn quantization(gpa: std.mem.Allocator, o: std.json.ObjectMap, json: []const u8, why: *Why) !void { const v = o.get("quantization_config") orelse return; - const q = if (v == .object) v.object else { + if (v != .object) { why.set("quantization_config is not an object", .{}); return error.Quant; - }; - const ok = std.ascii.eqlIgnoreCase(text(q, "quant_method") orelse "", "modelopt") and - std.ascii.eqlIgnoreCase(text(q, "quant_algo") orelse "", "NVFP4"); - if (!ok) { - why.set("quantization_config: the loader reads ModelOpt NVFP4 experts (MXFP8 layers follow from their tensors)", .{}); - return error.Quant; } + var core_why: modelopt.Why = .{}; + modelopt.admitByTensors(gpa, json, &core_why) catch |e| switch (e) { + error.NotModelOpt, error.UnsupportedQuant => { + why.set("quantization_config: the loader reads ModelOpt NVFP4 experts (MXFP8 layers follow from their tensors): {s}", .{core_why.text()}); + return error.Quant; + }, + else => return e, + }; } /// config.json as the reference (configuration_inkling2.py) and the checkpoint read it; a refusal is in `why`. @@ -349,15 +409,18 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, why: *Why) !Config { } const o = parsed.value.object; const arch = o.get("architectures"); - const ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string and - std.mem.eql(u8, arch.?.array.items[0].string, "Inkling2ForConditionalGeneration"); - if (!ok or !std.mem.eql(u8, text(o, "model_type") orelse "", "inkling2")) { - why.set("not an Inkling 2 checkpoint: architectures Inkling2ForConditionalGeneration, model_type inkling2", .{}); + const one = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string; + const name = if (one) arch.?.array.items[0].string else ""; + const kind = text(o, "model_type") orelse ""; + const small = std.mem.eql(u8, name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, kind, "inkling2"); + const looped = std.mem.eql(u8, name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, kind, "inkling2_loop"); + if (!small and !looped) { + why.set("not an Inkling 2 checkpoint: Inkling2ForConditionalGeneration (inkling2) or Inkling2LoopForConditionalGeneration (inkling2_loop)", .{}); return error.NotInkling2; } try fixed(o, "tie_word_embeddings", false, why); - try quantization(o, why); - const t = try parseText(try object(o, "text_config", why), why); + try quantization(gpa, o, json, why); + const t = try parseText(try object(o, "text_config", why), looped, why); const eos = try int(o, "eos_token_id", why); if (eos >= t.vocab) { why.set("eos_token_id is not a token of the {d}-token vocabulary", .{t.vocab}); diff --git a/zig/src/families/inkling2/fixtures/mini_config.json b/zig/src/families/inkling2/fixtures/mini_config.json new file mode 100644 index 00000000000..e6c170c3fb6 --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_config.json @@ -0,0 +1,122 @@ +{ + "dtype": "bfloat16", + "architectures": [ + "Inkling2LoopForConditionalGeneration" + ], + "model_type": "inkling2_loop", + "eos_token_id": 200006, + "text_config": { + "model_type": "inkling2_loop_text", + "model_max_length": 1048576, + "torch_dtype": "bfloat16", + "hidden_size": 2304, + "num_hidden_layers": 24, + "vocab_size": 201024, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "d_rel": 16, + "rel_extent": 1024, + "q_bias": false, + "o_bias": false, + "log_scaling_n_floor": 8192, + "log_scaling_alpha": 0.1, + "rms_norm_eps": 1e-06, + "use_value_norm_no_gamma": true, + "qk_l2_clip_threshold": 22.627416997969522, + "rel_l2_clip_threshold": 8.0, + "local_layer_ids": [ + 0, + 1, + 2, + 3, + 4, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22 + ], + "sconv_kernel_size": 4, + "unpadded_vocab_size": 200058, + "final_logit_softcapping": 30.0, + "swa_head_dim": 128, + "swa_num_attention_heads": 24, + "swa_num_key_value_heads": 8, + "sliding_window_size": 1024, + "n_layers_per_attn_res_block": 6, + "attn_res_normalize_values": true, + "n_routed_experts": 128, + "num_experts_per_tok": 8, + "n_shared_experts": 0, + "intermediate_size": 1152, + "mlp_gate_softcap": 4.0, + "mlp_up_softcap": 25.0, + "route_scale": 8.0, + "use_gate_bias": true, + "loop_config": { + "core_start": 6, + "core_end": 18, + "num_passes": 3, + "gate_rank": 64, + "is_varloop": false + } + }, + "vision_config": { + "model_type": "inkling2_vision", + "text_hidden_size": 2304, + "temporal_patch_size": 2, + "native_patch_size": 20, + "adapter_merge_size": 2, + "projection_hidden_dim": 4096, + "projector_bias": false, + "hidden_size": 1024, + "num_hidden_layers": 23, + "num_attention_heads": 16, + "mlp_ratio": 4.0, + "posemb_grid_size": 32, + "layer_norm_eps": 1e-05 + }, + "mtp_config": { + "hidden_size": 2304, + "num_hidden_layers": 3, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "intermediate_size": 9216, + "max_position_embeddings": 1048576, + "torch_dtype": "bfloat16", + "q_bias": false, + "o_bias": false, + "rms_norm_eps": 1e-06, + "rope_theta": 1000000.0, + "local_layer_ids": [ + 0, + 2 + ], + "sliding_window_size": 1024, + "block_size": 8, + "markov_rank": 256, + "markov_head_type": "rnn_hidden", + "target_layer_ids": [ + 5, + 23, + 41, + 48 + ] + }, + "quantization_config": { + "quant_method": "modelopt", + "quant_algo": "NVFP4" + } +} diff --git a/zig/src/families/inkling2/fixtures/mini_model_header.txt b/zig/src/families/inkling2/fixtures/mini_model_header.txt new file mode 100644 index 00000000000..bf0d2f5f1d1 --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_model_header.txt @@ -0,0 +1,86 @@ +inkling2-mini-model 1244 dfcec4225659aceabe432e4daadb4e6291f3718e2015d412f97f60200de32141 +model.llm.attn_res.attn_queries.{L} F32 2304 0-3,5-9,11-15,17-21 +model.llm.attn_res.attn_queries.{L} F32 3x2304 4,10,16,22 +model.llm.attn_res.mlp_queries.{L} F32 2304 0-23 +model.llm.attn_res.output_query F32 2304 +model.llm.embed.weight BF16 201024x2304 +model.llm.embed_norm.weight BF16 2304 +model.llm.layers.{L}.attn.attn_sink_proj.weight BF16 24x2304 0-23 +model.llm.layers.{L}.attn.gate_attn.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.k_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.k_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.k_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.q_l2_clip.scale BF16 24x128 0-23 +model.llm.layers.{L}.attn.rel_l2_clip.scale BF16 24x16 0-23 +model.llm.layers.{L}.attn.rel_logits_proj.proj BF16 16x1024 0-23 +model.llm.layers.{L}.attn.v_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.v_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.v_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.wk_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn.wo_ud.weight BF16 2304x3072 0-23 +model.llm.layers.{L}.attn.wq_du.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.wr_du.weight BF16 384x2304 0-23 +model.llm.layers.{L}.attn.wv_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn_norm.weight BF16 2304 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.controllers.attn.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.attn.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.attn.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.k.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.mlp.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.v.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.k_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.mlp.experts.w13_weight F8_E4M3 128x2304x2304 20-23 +model.llm.layers.{L}.mlp.experts.w13_weight U8 128x2304x1152 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale F8_E4M3 128x2304x144 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale U8 128x2304x72 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight F8_E4M3 128x2304x1152 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight U8 128x2304x576 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale F8_E4M3 128x2304x72 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale U8 128x2304x36 20-23 +model.llm.layers.{L}.mlp.gate.bias F32 128 0-23 +model.llm.layers.{L}.mlp.gate.weight BF16 128x2304 0-23 +model.llm.layers.{L}.mlp_norm.weight BF16 2304 0-23 +model.llm.layers.{L}.mlp_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.q_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.v_input_norm.weight BF16 2304 5,11,17,23 +model.llm.middle_cycle_cross_pass_kv_queries F32 24x2304 +model.llm.middle_cycle_cross_pass_queries F32 24x2304 +model.llm.norm.weight BF16 2304 +model.llm.unembed.weight BF16 201024x2304 +model.visual.backbone.embeddings.class_embedding BF16 1024 +model.visual.backbone.embeddings.cls_position_embedding BF16 1024 +model.visual.backbone.embeddings.patch_embedding.weight BF16 1024x1200 +model.visual.backbone.embeddings.position_embedding BF16 1024x1024 +model.visual.backbone.layers.{L}.ln_1.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_1.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_1.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_2.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.bias BF16 4096 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.weight BF16 4096x1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.weight BF16 1024x4096 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.ln_pre.bias BF16 1024 +model.visual.backbone.ln_pre.weight BF16 1024 +model.visual.proj_in.weight BF16 4096x4096 +model.visual.proj_out.weight BF16 2304x4096 diff --git a/zig/src/families/inkling2/fixtures/mini_mtp_header.txt b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt new file mode 100644 index 00000000000..618bdca1e6e --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt @@ -0,0 +1,25 @@ +inkling2-mini-mtp 54 f962cd87735ebbd1af0639f7513f99eed98b61d8a30b083fb33fc1bb1c3a70d1 +fuse_weight BF16 4x4 +layers.{L}.dflare_norm.weight BF16 2304 0-2 +layers.{L}.input_layernorm.weight BF16 2304 0-2 +layers.{L}.mlp.down_proj.weight BF16 2304x9216 0-2 +layers.{L}.mlp.gate_proj.weight BF16 9216x2304 0-2 +layers.{L}.mlp.up_proj.weight BF16 9216x2304 0-2 +layers.{L}.post_attention_layernorm.weight BF16 2304 0-2 +layers.{L}.self_attn.k_norm.weight BF16 128 0-2 +layers.{L}.self_attn.k_norm_ctx.weight BF16 128 0-2 +layers.{L}.self_attn.k_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.k_proj_ctx.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.o_proj.weight BF16 2304x3072 0-2 +layers.{L}.self_attn.q_norm.weight BF16 128 0-2 +layers.{L}.self_attn.q_proj.weight BF16 3072x2304 0-2 +layers.{L}.self_attn.v_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.v_proj_ctx.weight BF16 1024x2304 0-2 +markov_head.dflare_norm.weight BF16 2304 +markov_head.hidden_out.bias BF16 2304 +markov_head.hidden_out.weight BF16 2304x256 +markov_head.markov_w1.weight BF16 201024x256 +markov_head.rnn_proj.bias BF16 768 +markov_head.rnn_proj.weight BF16 768x5120 +mask_embed BF16 2304 +norm.weight BF16 2304 diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 4f8b47e83b3..a7de0022d12 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -4,6 +4,7 @@ test { _ = @import("config_test.zig"); _ = @import("names.zig"); _ = @import("names_test.zig"); + _ = @import("mini_host_test.zig"); _ = @import("plan.zig"); _ = @import("prompt.zig"); _ = @import("template_test.zig"); diff --git a/zig/src/families/inkling2/mini_host_test.zig b/zig/src/families/inkling2/mini_host_test.zig new file mode 100644 index 00000000000..d86c3aad2ed --- /dev/null +++ b/zig/src/families/inkling2/mini_host_test.zig @@ -0,0 +1,180 @@ +//! Inkling 2 Mini (inkling2_loop) on the host: its config.json, the loop's visits and slots, the weight map against +//! the published headers (folded fixtures), each layer's expert precision and what the loop parse refuses. +const std = @import("std"); +const config = @import("config.zig"); +const names = @import("names.zig"); +const plan = @import("plan.zig"); +const st = @import("safetensors"); +const unfold = @import("names_test.zig").unfold; + +const t = std.testing; +pub const mini = @embedFile("fixtures/mini_config.json"); +const model_fixture = @embedFile("fixtures/mini_model_header.txt"); +const mtp_fixture = @embedFile("fixtures/mini_mtp_header.txt"); + +fn parse(a: std.mem.Allocator) !config.Config { + var why: config.Why = .{}; + return config.parse(a, mini, &why); +} + +fn refused(from: []const u8, to: []const u8, want: anyerror, says: []const u8) !void { + if (std.mem.count(u8, mini, from) != 1) return error.EditAnchor; + const edited = try std.mem.replaceOwned(u8, t.allocator, mini, from, to); + defer t.allocator.free(edited); + var why: config.Why = .{}; + try t.expectError(want, config.parse(t.allocator, edited, &why)); + if (std.mem.indexOf(u8, why.text(), says) == null) { + std.debug.print("refusal \"{s}\" does not name \"{s}\"\n", .{ why.text(), says }); + return error.TestUnexpectedResult; + } +} + +test "Mini's config.json parses: 24 layers, a core of 6..17 three times (48 visits), rank 64, taps by visit" { + const c = try parse(t.allocator); + try t.expectEqual(@as(u32, 2304), c.text.hidden); + try t.expectEqual(@as(u32, 24), c.text.layers); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.global); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.local); + try t.expectEqual(@as(u32, 128), c.text.experts); + try t.expectEqual(@as(u32, 1152), c.text.expert_inter); + try t.expectEqual(@as(u32, 8192), c.text.log_floor); + try t.expectEqual(config.Loop{ .start = 6, .end = 18, .passes = 3, .rank = 64 }, c.text.loop.?); + try t.expectEqual(@as(u32, 48), c.text.visits()); + const m = c.mtp.?; + try t.expectEqual(@as(u32, 3), m.layers); + try t.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, m.taps[0..m.taps_n]); +} + +test "Mini's visits: prelude 0..5, the core three passes, coda 18..23; 40 sliding, 8 full and 48 conv slots" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + var prec: [24]plan.Precision = undefined; + try names.precisions(try unfold(a, model_fixture, "inkling2-mini-model"), 24, &prec); + const p = try plan.build(&c.text, &prec); + const v = &p.visits; + try t.expectEqual(@as(u32, 48), v.len); + try t.expectEqual(@as(u32, 40), v.count(.sliding)); + try t.expectEqual(@as(u32, 8), v.count(.full)); + try t.expectEqual(@as(u32, 48), v.count(.conv)); + try t.expectEqual(@as(u32, 1), p.pre_blocks); + try t.expectEqual(@as(u32, 1), p.bank_blocks); + for (v.slice(), 0..) |s, k| { + const want: u32 = if (k < 6) @intCast(k) else if (k < 42) 6 + @as(u32, @intCast(k - 6)) % 12 else @intCast(k - 24); + try t.expectEqual(want, s.layer); + try t.expectEqual(@as(u8, if (k < 6 or k >= 42) 0 else @intCast((k - 6) / 12)), s.pass); + try t.expectEqual(k >= 18 and k < 42, p.messages(@intCast(k))); + try t.expectEqual(k == 18 or k == 30, p.restarts(@intCast(k))); + try t.expectEqual(@as(?u16, @intCast(k)), s.of(.conv)); + } + // the taps' visits: 5 is L5 pass 0, 23 is L11 pass 1, 41 is L17 pass 2 (global slots 0, 3 and 6); 48 the output + for ([_]u32{ 5, 23, 41 }, [_]u32{ 5, 11, 17 }, [_]u16{ 0, 3, 6 }) |tap, layer, full| { + const s = v.steps[(try v.tap(tap)).input]; + try t.expectEqual(layer, s.layer); + try t.expectEqual(@as(?u16, full), s.of(.full)); + } + try t.expectEqual(@as(@TypeOf(try v.tap(48)), .output), try v.tap(48)); + try t.expectEqual(@as(u32, 5), p.coreIndex(23)); + try t.expectEqual(@as(u32, 0), p.coreIndex(3)); +} + +test "Mini's folded headers unfold to its 1244 and 54 tensors, digests equal" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + try t.expectEqual(@as(usize, 1244), (try unfold(arena.allocator(), model_fixture, "inkling2-mini-model")).count()); + try t.expectEqual(@as(usize, 54), (try unfold(arena.allocator(), mtp_fixture, "inkling2-mini-mtp")).count()); +} + +test "the map names exactly Mini's tensors: controllers, cross-pass queries, NVFP4 L0-19 and MXFP8 L20-23" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + const entries = try unfold(a, model_fixture, "inkling2-mini-model"); + const r = try names.check(a, &c, entries, .model); + try t.expectEqual(@as(usize, 1244), r.expected); + try t.expect(r.clean()); + var prec: [24]plan.Precision = undefined; + try names.precisions(entries, 24, &prec); + for (prec, 0..) |p, i| try t.expectEqual(if (i < 20) plan.Precision.nvfp4 else plan.Precision.mxfp8, p); + const mtp = try names.check(a, &c, try unfold(a, mtp_fixture, "inkling2-mini-mtp"), .mtp); + try t.expectEqual(@as(usize, 54), mtp.expected); + try t.expect(mtp.clean()); +} + +test "a missing controller and a wrong cross-pass shape are reported by name" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + const all = try unfold(a, model_fixture, "inkling2-mini-model"); + var kept: st.Header = .empty; + for (all.keys(), all.values()) |name, e| { + var x = e; + if (std.mem.eql(u8, name, "model.llm.layers.9.controllers.v.gain_weight")) continue; + if (std.mem.eql(u8, name, "model.llm.middle_cycle_cross_pass_kv_queries")) x.shape[0] = 12; + try kept.put(a, name, x); + } + const r = try names.check(a, &c, kept, .model); + try t.expectEqual(@as(usize, 1), r.missing.items.len); + try t.expectEqualStrings("model.llm.layers.9.controllers.v.gain_weight", r.missing.items[0]); + try t.expectEqual(@as(usize, 1), r.wrong.items.len); + try t.expectEqualStrings("model.llm.middle_cycle_cross_pass_kv_queries", r.wrong.items[0]); +} + +test "the loop parse refuses is_varloop, a core off the blocks, one pass, a wide rank and a loop on Small by name" { + try refused("\"is_varloop\": false", "\"is_varloop\": true", error.Unsupported, "is_varloop must be false"); + try refused("\"core_end\": 18", "\"core_end\": 17", error.Layout, "not whole blocks of 6"); + try refused("\"core_end\": 18", "\"core_end\": 30", error.Layout, "not whole blocks of 6"); + try refused("\"num_passes\": 3", "\"num_passes\": 1", error.Layout, "at least 2"); + try refused("\"gate_rank\": 64", "\"gate_rank\": 129", error.Layout, "gate_rank 129 at most 128"); + try refused("\"num_passes\": 3", "\"num_passes\": 40", error.Layout, "the plan tables hold 256"); + try refused("\"loop_config\"", "\"loop_cfg\"", error.BadConfig, "no loop_config"); + try refused("\"attn_res_normalize_values\": true", "\"attn_res_normalize_values\": false", error.Unsupported, "attn_res_normalize_values"); + try refused("\"model_type\": \"inkling2_loop\"", "\"model_type\": \"inkling2\"", error.NotInkling2, "inkling2_loop"); + try refused("23,\n 41,", "41,\n 23,", error.Layout, "must rise"); + try refused("23,\n 41,", "23,\n 49,", error.Layout, "a layer the backbone does not have"); +} + +test "Small with a loop_config is refused: the loop needs model_type inkling2_loop" { + const tiny = @import("config_test.zig").tiny; + const from = "\"n_layers_per_attn_res_block\": 6,"; + const to = from ++ " \"loop_config\": {\"core_start\": 6, \"core_end\": 12, \"num_passes\": 2, \"gate_rank\": 8},"; + const edited = try std.mem.replaceOwned(u8, t.allocator, tiny, from, to); + defer t.allocator.free(edited); + var why: config.Why = .{}; + try t.expectError(error.Unsupported, config.parse(t.allocator, edited, &why)); + try t.expectEqualStrings("loop_config needs model_type inkling2_loop", why.text()); +} + +test "Mini's quantization_config goes through core.modelopt: NVFP4 without config_groups, FP8 refused" { + try refused("\"quant_algo\": \"NVFP4\"", "\"quant_algo\": \"FP8\"", error.Quant, "ModelOpt FP8"); + try refused("\"quant_method\": \"modelopt\"", "\"quant_method\": \"awq\"", error.Quant, "no ModelOpt quantization_config"); +} + +/// A file's header read from disk (the shard holds data too; only the header is read). +fn headerOf(a: std.mem.Allocator, dir: []const u8, file: []const u8) !st.Header { + const path = try std.fmt.allocPrint(a, "{s}/{s}", .{ dir, file }); + const f = try std.Io.Dir.cwd().openFile(t.io, path, .{}); + defer f.close(t.io); + var prefix: [8]u8 = undefined; + if (try f.readPositionalAll(t.io, &prefix, 0) != 8) return error.BadSafetensors; + const size = std.math.cast(usize, try f.length(t.io)) orelse return error.BadSafetensors; + const json = try a.alloc(u8, try st.headerSize(std.mem.readInt(u64, &prefix, .little), size)); + if (try f.readPositionalAll(t.io, json, 8) != json.len) return error.BadSafetensors; + return st.parseHeader(a, json, std.math.maxInt(usize)); +} + +test "the released Mini's model and mtp headers and config match the map (TF_INKLING2_MINI=)" { + const dir = std.mem.span(std.c.getenv("TF_INKLING2_MINI") orelse return error.SkipZigTest); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try parse(a); + const model = try names.check(a, &c, try headerOf(a, dir, "model-00001-of-00001.safetensors"), .model); + try t.expectEqual(@as(usize, 1244), model.expected); + try t.expect(model.clean()); + const mtp = try names.check(a, &c, try headerOf(a, dir, "mtp.safetensors"), .mtp); + try t.expect(mtp.clean()); +} diff --git a/zig/src/families/inkling2/names.zig b/zig/src/families/inkling2/names.zig index 3c75db572bf..360d7aa88a7 100644 --- a/zig/src/families/inkling2/names.zig +++ b/zig/src/families/inkling2/names.zig @@ -1,4 +1,4 @@ -//! Inkling 2 Small's weight map: each tensor the config implies, with dtype and shape, checked against headers. +//! Inkling 2's weight map (Small and the looped Mini): each tensor the config implies, dtype and shape, vs headers. const std = @import("std"); const st = @import("safetensors"); const config = @import("config.zig"); @@ -77,6 +77,25 @@ fn experts(c: *const Text, i: u32, prec: plan.Precision, sink: anytype) !void { } } +/// The loop's tensors: four controllers a core layer (attention q, k, v inputs and the MLP input: a rank-r down +/// projection of [state, message] and two [hidden, r] gates) and the cross-pass queries, two rows a core layer each. +fn loop(c: *const Text, l: config.Loop, sink: anytype) !void { + const h: u64 = c.hidden; + const r: u64 = l.rank; + const rows: u64 = 2 * @as(u64, l.end - l.start); + try put(sink, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ rows, h }); + try put(sink, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ rows, h }); + for (l.start..l.end) |i| inline for (controllers) |gate| { + const pre = "model.llm.layers.{d}.controllers." ++ gate; + try put(sink, pre ++ ".down_weight", .{i}, .bf16, &.{ r, 2 * h }); + try put(sink, pre ++ ".forget_weight", .{i}, .bf16, &.{ h, r }); + try put(sink, pre ++ ".gain_weight", .{i}, .bf16, &.{ h, r }); + }; +} + +/// A core layer's controllers in the order the engine holds them: the attention's q, k and v inputs, then the MLP's. +pub const controllers = [_][]const u8{ "attn", "k", "v", "mlp" }; + fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { const h: u64 = c.hidden; try put(sink, "model.llm.embed.weight", .{}, .bf16, &.{ c.vocab, h }); @@ -98,6 +117,7 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.layers.{d}.mlp_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); try experts(c, i, prec[i], sink); } + if (c.loop) |l| try loop(c, l, sink); } fn vision(v: config.Vision, sink: anytype) !void { diff --git a/zig/src/families/inkling2/plan.zig b/zig/src/families/inkling2/plan.zig index c2327d26bef..769ad238f3d 100644 --- a/zig/src/families/inkling2/plan.zig +++ b/zig/src/families/inkling2/plan.zig @@ -1,6 +1,24 @@ -//! The layer plan: which layers slide or see everything, where attention-residual blocks end, what layers sum over. +//! The layer plan: which layers slide or see everything, where attention-residual blocks end, what layers sum over, +//! and a looped model's visits (core/visit_plan.zig): each visit's layer, pass and state slots. const std = @import("std"); const config = @import("config.zig"); +const visit_plan = @import("visit_plan"); + +/// The states a visit keeps: a sliding layer's key/value ring, a global layer's whole cache, every visit's conv state. +pub const Slot = enum { sliding, full, conv }; + +/// Layer visits in run order with their slots (Small: every layer once). +pub const Visits = visit_plan.Plan(Slot, config.max_visits); + +const Holds = struct { + pub fn keeps(_: Holds, layer: u16, k: Slot) bool { + return switch (k) { + .conv => true, + .full => config.isGlobal(layer), + .sliding => !config.isGlobal(layer), + }; + } +}; /// A routed-expert layer's stored format, read from its tensors: ModelOpt NVFP4 (groups of 16) or MXFP8 (groups of 32). pub const Precision = enum { nvfp4, mxfp8 }; @@ -23,6 +41,27 @@ pub const Plan = struct { layers: [config.max_layers]Layer, n: u32, final_sources: u32, // the output query's states: every finished block and the last layer's output + visits: Visits, + pre_blocks: u32, // looped: finished blocks entering the core + bank_blocks: u32, // looped: blocks a pass finishes past its entry block, the next pass's message sources + + /// Visit k takes the previous pass's messages: a core layer at pass 1 or later. + pub fn messages(p: *const Plan, k: u32) bool { + return p.visits.steps[k].pass > 0; + } + + /// Visit k starts a pass after the first: the running state restarts from the core's entry block. + pub fn restarts(p: *const Plan, k: u32) bool { + const s = p.visits.steps[k]; + return s.enter and s.pass > 0; + } + + /// The row of the cross-pass queries a core visit reads (its layer's place in the core), 0 outside the core. + pub fn coreIndex(p: *const Plan, k: u32) u32 { + const s = p.visits.steps[k]; + const l = p.visits.loop; + return if (s.layer >= l.start and s.layer < l.end) s.layer - l.start else 0; + } pub fn at(p: *const Plan, i: u32) *const Layer { return &p.layers[i]; @@ -36,10 +75,14 @@ pub const Plan = struct { }; /// The plan for a parsed config and each layer's expert precision (`prec` holds one entry per layer). -pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCount}!Plan { +pub fn build(c: *const config.Text, prec: []const Precision) error{ PrecisionCount, Layout, TooManySteps }!Plan { if (prec.len != c.layers) return error.PrecisionCount; var p: Plan = undefined; p.n = c.layers; + const l: visit_plan.Loop = if (c.loop) |x| .{ .start = x.start, .end = x.end, .passes = x.passes } else visit_plan.straight; + p.visits = try Visits.build(c.layers, l, Holds{}); + p.pre_blocks = l.start / c.block; + p.bank_blocks = if (c.loop != null) (l.end - l.start) / c.block - 1 else 0; for (0..c.layers) |k| { const i: u32 = @intCast(k); const boundary = i % c.block == 0; From 80278719615e43d76443c89b4c201d3db628e37a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:10:36 +0100 Subject: [PATCH 06/84] inkling2: Mini's forward at one rank on CUDA (C4a): 48 visits, loop gates, core experts Weights load layer by layer through core.checkpoint (ModelOpt admitted by core.modelopt). Experts run as core cuda.experts: NVFP4 in L0-19 and MXFP8 in L20-23. Each stream holds 48 visit slots (40 sliding, 8 full, 48 conv). The loop mix and controller gates (loop.cu) stand in for C2/H3 and use #4337's arithmetic. A float64 host reference (mini_ref.zig) checks the greedy tokens. tf-cuda-test inkling2-mini runs on the real checkpoint: - greedy output is coherent; - a prompt cut into chunks of 1 or 7 gives bit-equal last-row logits and equal tokens; - 4 streams together give the same tokens as each alone. --- zig/build/cuda_kernels.zig | 1 + zig/build/inkling2.zig | 4 + zig/kernels/cuda/inkling2/loop.cu | 173 ++++++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/inkling2/core_parts.zig | 15 + zig/src/families/inkling2/inkling2.zig | 18 +- zig/src/families/inkling2/loop.zig | 122 ++++++ zig/src/families/inkling2/mini_model.zig | 330 ++++++++++++++ zig/src/families/inkling2/mini_ref.zig | 481 +++++++++++++++++++++ zig/src/families/inkling2/mini_visit.zig | 241 +++++++++++ zig/src/families/inkling2/mini_weights.zig | 284 ++++++++++++ zig/tests/cuda/inkling2_mini_tests.zig | 218 ++++++++++ zig/tests/cuda/main.zig | 2 + zig/tests/cuda/main_usage.zig | 2 + 14 files changed, 1891 insertions(+), 1 deletion(-) create mode 100644 zig/kernels/cuda/inkling2/loop.cu create mode 100644 zig/src/families/inkling2/core_parts.zig create mode 100644 zig/src/families/inkling2/loop.zig create mode 100644 zig/src/families/inkling2/mini_model.zig create mode 100644 zig/src/families/inkling2/mini_ref.zig create mode 100644 zig/src/families/inkling2/mini_visit.zig create mode 100644 zig/src/families/inkling2/mini_weights.zig create mode 100644 zig/tests/cuda/inkling2_mini_tests.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 4ddb07b7e23..ae45152b916 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -164,6 +164,7 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_pattn", .src = "inkling2/prompt_attention", .flags = &.{"-O3"} }, // ours: Inkling 2's global-layer prompt attention .{ .name = "inkling2_ops", .src = "inkling2/ops", .flags = glue }, // ours: Inkling 2's residual mix, convs, router, SwiGLU .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows + .{ .name = "inkling2_loop", .src = "inkling2/loop", .flags = glue }, // ours: Inkling 2 Mini's loop messages and gates .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family .{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5 .{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts diff --git a/zig/build/inkling2.zig b/zig/build/inkling2.zig index ad9d1ba52f7..98b9150dafb 100644 --- a/zig/build/inkling2.zig +++ b/zig/build/inkling2.zig @@ -7,6 +7,10 @@ pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui m.addImport("cuda", cuda); m.addImport("core", core); m.addImport("lanes", lanes); + // the host files' imports by name (config, plan, names), here through core + const parts = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/core_parts.zig"), .target = target, .optimize = optimize, .link_libc = true }); + parts.addImport("core", core); + for ([_][]const u8{ "safetensors", "visit_plan", "modelopt" }) |name| m.addImport(name, parts); return m; } diff --git a/zig/kernels/cuda/inkling2/loop.cu b/zig/kernels/cuda/inkling2/loop.cu new file mode 100644 index 00000000000..a0c992f928f --- /dev/null +++ b/zig/kernels/cuda/inkling2/loop.cu @@ -0,0 +1,173 @@ +// Inkling 2 Mini's loop (inkling2_loop): the cross-pass message mixes and the rank-r gates on the core's inputs. +// C2 stand-in: the arithmetic #4337's Metal loop.metal runs (H3/C2 are other slices); fp32 sums, fixed orders. +#include +#include + +namespace ink2l { + +constexpr int kMaxBlocks = 8; // finished blocks a mix reads beside the partial state +constexpr int kMaxQueries = 4; // queries of one mix: a message's q, k, v and mlp, or an input's 1 or 3 +constexpr int kMaxGates = 3; // gates one launch runs: the attention's q, k and v inputs +constexpr int kMaxRank = 128; // gate rank (config.max_gate_rank) +constexpr int kThreads = 256; +constexpr int kWarps = kThreads / 32; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } +__device__ __forceinline__ float warpSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// The block's sum of v in one order: warp shuffles, then the warps' partials in warp order; every thread gets it. +__device__ __forceinline__ float blockSum(float v, float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warpSum(v); + __syncthreads(); + if (lane == 0) sh[w] = v; + __syncthreads(); + float t = 0.0f; + for (int i = 0; i < kWarps; ++i) t += sh[i]; + return t; +} + +} // namespace ink2l + +using namespace ink2l; + +// An attention-residual mix without the norm: sources are the blocks then the partial; queries attend over them. +struct LoopMixArgs { + const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, H] each + const void* partial; // [rows, H]: fp32 when partial_f32, else bf16 + const float* query[kMaxQueries]; // fp32 [H] each + float* out; // fp32 [nq][rows, H], planes out_stride elements apart + long long out_stride; + int n_blocks, partial_f32, nq, rows, H; + float eps, scale; // eps: the sources' rms; scale: H^-0.5 on the scores +}; + +// Per row: each source's 1/rms, each query's softmax over (q . source) / rms * scale, then the fp32 mixes. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_mix(const LoopMixArgs a) { + __shared__ float sh[kWarps]; + __shared__ float inv[kMaxBlocks + 1]; + __shared__ float coef[kMaxQueries][kMaxBlocks + 1]; + const size_t row = blockIdx.x; + const int H = a.H, S = a.n_blocks + 1; + auto src = [&](int s, int i) -> float { + if (s < a.n_blocks) return bf(a.blocks[s][row * H + i]); + if (a.partial_f32) return static_cast(a.partial)[row * H + i]; + return bf(static_cast(a.partial)[row * H + i]); + }; + for (int s = 0; s < S; ++s) { + float acc = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) { + const float v = src(s, i); + acc = fmaf(v, v, acc); + } + const float t = blockSum(acc, sh); + if (threadIdx.x == 0) inv[s] = rsqrtf(t / static_cast(H) + a.eps); + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float score[kMaxBlocks + 1]; + for (int s = 0; s < S; ++s) { + float acc = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) acc = fmaf(a.query[q][i], src(s, i), acc); + score[s] = blockSum(acc, sh) * inv[s] * a.scale; + } + if (threadIdx.x == 0) { + float m = -INFINITY, l = 0.0f; + for (int s = 0; s < S; ++s) m = fmaxf(m, score[s]); + for (int s = 0; s < S; ++s) { + score[s] = expf(score[s] - m); + l += score[s]; + } + for (int s = 0; s < S; ++s) coef[q][s] = (score[s] / l) * inv[s]; + } + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float* dst = a.out + q * a.out_stride + row * H; + for (int i = threadIdx.x; i < H; i += kThreads) { + float u = 0.0f; + for (int s = 0; s < S; ++s) u = fmaf(coef[q][s], src(s, i), u); + dst[i] = u; + } + } +} + +// The gates of one launch: gate g reads state h[g] (fp32 [rows, H]) and message plane slot[g] of msg. +struct LoopGateArgs { + const float* h[kMaxGates]; + const float* msg; // fp32 [planes][rows, H] + long long msg_stride; // elements between the message planes + int slot[kMaxGates]; + const uint16_t* down_w[kMaxGates]; // bf16 [rank][2 H]: [state, message] + const uint16_t* forget[kMaxGates]; // bf16 [H][rank] + const uint16_t* gain[kMaxGates]; // bf16 [H][rank] + const uint16_t* norm[kMaxGates]; // bf16 [H] + uint16_t* down; // bf16 [gates][rows][rank] + uint16_t* out; // bf16 [gates][rows, H], planes out_stride elements apart + long long out_stride; + int rows, H, rank; + float eps_unit, eps; // eps_unit: the unweighted norms of state and message; eps: the gated output's norm +}; + +// down[g][row] = bf16(W_down [unit(h) bf16, unit(m) bf16]) for gate blockIdx.y of row blockIdx.x. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_down(const LoopGateArgs a) { + extern __shared__ float xs[]; // [2 H]: the normed state, then the normed message, each rounded to bf16 + __shared__ float sh[kWarps]; + const size_t row = blockIdx.x; + const int g = blockIdx.y, H = a.H; + const float* h = a.h[g] + row * H; + const float* m = a.msg + a.slot[g] * a.msg_stride + row * H; + float sh_acc = 0.0f, sm_acc = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) { + sh_acc = fmaf(h[i], h[i], sh_acc); + sm_acc = fmaf(m[i], m[i], sm_acc); + } + const float ih = rsqrtf(blockSum(sh_acc, sh) / static_cast(H) + a.eps_unit); + const float im = rsqrtf(blockSum(sm_acc, sh) / static_cast(H) + a.eps_unit); + for (int i = threadIdx.x; i < H; i += kThreads) { + xs[i] = bf(tobf(h[i] * ih)); + xs[H + i] = bf(tobf(m[i] * im)); + } + __syncthreads(); + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + for (int r = w; r < a.rank; r += kWarps) { + const uint16_t* wr = a.down_w[g] + static_cast(r) * 2 * H; + float acc = 0.0f; + for (int i = lane; i < 2 * H; i += 32) acc = fmaf(bf(wr[i]), xs[i], acc); + acc = warpSum(acc); + if (lane == 0) a.down[(static_cast(g) * a.rows + row) * a.rank + r] = tobf(acc); + } +} + +// out[g][row] = norm * rms((1 - tanh(Wf d)) h + tanh(Wg d) m), d the gate's bf16 down row. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_mix(const LoopGateArgs a) { + extern __shared__ float ys[]; // [H]: the gated row before its norm + __shared__ float sh[kWarps]; + __shared__ float dn[kMaxRank]; + const size_t row = blockIdx.x; + const int g = blockIdx.y, H = a.H, R = a.rank; + const float* h = a.h[g] + row * H; + const float* m = a.msg + a.slot[g] * a.msg_stride + row * H; + if (threadIdx.x < R) dn[threadIdx.x] = bf(a.down[(static_cast(g) * a.rows + row) * R + threadIdx.x]); + __syncthreads(); + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) { + const uint16_t* wf = a.forget[g] + static_cast(i) * R; + const uint16_t* wg = a.gain[g] + static_cast(i) * R; + float f = 0.0f, gn = 0.0f; + for (int r = 0; r < R; ++r) { + f = fmaf(bf(wf[r]), dn[r], f); + gn = fmaf(bf(wg[r]), dn[r], gn); + } + const float v = (1.0f - tanhf(f)) * h[i] + tanhf(gn) * m[i]; + ys[i] = v; + ss = fmaf(v, v, ss); + } + const float inv = rsqrtf(blockSum(ss, sh) / static_cast(H) + a.eps); + uint16_t* dst = a.out + g * a.out_stride + row * H; + for (int i = threadIdx.x; i < H; i += kThreads) dst[i] = tobf(bf(a.norm[g][i]) * (ys[i] * inv)); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 68f917f8362..efd78cc3b86 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -114,6 +114,7 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; +pub const inkling2_loop: []const u8 = if (available) &Blob("fatbin_inkling2_loop").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; diff --git a/zig/src/families/inkling2/core_parts.zig b/zig/src/families/inkling2/core_parts.zig new file mode 100644 index 00000000000..589419cb361 --- /dev/null +++ b/zig/src/families/inkling2/core_parts.zig @@ -0,0 +1,15 @@ +//! The core parts the family's host files import by name (safetensors, visit_plan, modelopt), as the CUDA family +//! module reaches them through core; the host-only tests import the core files themselves (build/inkling2_host.zig). +const core = @import("core"); + +pub const DType = core.safetensors.DType; +pub const Header = core.safetensors.Header; +pub const Entry = core.safetensors.Entry; + +pub const Plan = core.visit_plan.Plan; +pub const Loop = core.visit_plan.Loop; +pub const Tap = core.visit_plan.Tap; +pub const straight = core.visit_plan.straight; + +pub const Why = core.modelopt.Why; +pub const admitByTensors = core.modelopt.admitByTensors; diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 556bca61b13..41f23e45c22 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -1,7 +1,16 @@ -//! Inkling 2 Small (model_type inkling2) on CUDA: config, chat, reply split, admission, kernels, EXL3 weights, forward. +//! Inkling 2 on CUDA: Small's kernels (attention, glue) and Mini (inkling2_loop) at one rank: config, plan, weights, +//! the loop's gates and messages, the forward over 48 visit slots a stream. pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); +pub const config = @import("config.zig"); +pub const plan = @import("plan.zig"); +pub const names = @import("names.zig"); +pub const loop = @import("loop.zig"); +pub const mini_weights = @import("mini_weights.zig"); +pub const mini_model = @import("mini_model.zig"); +/// The float64 reference the CUDA forward's greedy tokens are checked against. +pub const mini_ref = @import("mini_ref.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -9,4 +18,11 @@ pub const model_type = "inkling2"; test { _ = kernels; _ = ops; + _ = loop; + _ = config; + _ = plan; + _ = mini_model; + _ = @import("mini_visit.zig"); + _ = mini_weights; + _ = mini_ref; } diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig new file mode 100644 index 00000000000..a0b8bd486fe --- /dev/null +++ b/zig/src/families/inkling2/loop.zig @@ -0,0 +1,122 @@ +//! Inkling 2 Mini's loop launches (inkling2/loop.cu): cross-pass message mixes and the core inputs' rank-r gates. +//! C2 stand-in: the arithmetic #4337's Metal implementation runs; the kernel contract for these is C2's slice. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const max_blocks = 8; +pub const max_queries = 4; +pub const max_gates = 3; +pub const max_rank = 128; +const threads = 256; + +/// loop.cu's LoopMixArgs, field for field. +pub const MixArgs = extern struct { + blocks: [max_blocks]u64 = @splat(0), + partial: u64, + query: [max_queries]u64 = @splat(0), + out: u64, + out_stride: i64, + n_blocks: i32, + partial_f32: i32, + nq: i32, + rows: i32, + h: i32, + eps: f32, + scale: f32, +}; + +/// loop.cu's LoopGateArgs, field for field. +pub const GateArgs = extern struct { + h: [max_gates]u64 = @splat(0), + msg: u64, + msg_stride: i64, + slot: [max_gates]i32 = @splat(0), + down_w: [max_gates]u64 = @splat(0), + forget: [max_gates]u64 = @splat(0), + gain: [max_gates]u64 = @splat(0), + norm: [max_gates]u64 = @splat(0), + down: u64, + out: u64, + out_stride: i64, + rows: i32, + h_dim: i32, + rank: i32, + eps_unit: f32, + eps: f32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + mix: cuda.Function, + gate_down: cuda.Function, + gate_mix: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop); + errdefer mod.unload(); + return .{ + .mod = mod, + .mix = try mod.function("tf_ink2_loop_mix"), + .gate_down = try mod.function("tf_ink2_loop_gate_down"), + .gate_mix = try mod.function("tf_ink2_loop_gate_mix"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// The shapes the kernels hold: blocks, queries, gates and rank in their arrays; a refusal names the bound. +pub fn mixFits(a: MixArgs) error{Inkling2LoopShape}!void { + if (a.rows <= 0 or a.h <= 0 or a.nq <= 0 or a.nq > max_queries or a.n_blocks < 0 or a.n_blocks > max_blocks) + return error.Inkling2LoopShape; +} + +pub fn gateFits(a: GateArgs, count: usize) error{Inkling2LoopShape}!void { + if (a.rows <= 0 or a.h_dim <= 0 or a.rank <= 0 or a.rank > max_rank or count == 0 or count > max_gates) + return error.Inkling2LoopShape; +} + +/// fp32 mixes of `nq` queries over a row's blocks and partial (no norm): a block a row. +pub fn mix(k: *const Kernels, s: cuda.Stream, a: MixArgs) !void { + try mixFits(a); + var args: cuda.Args = .{}; + args.add(a); + try cuda.launch.launch(k.mix, .{ .grid = .{ .x = @intCast(a.rows) }, .block = .{ .x = threads } }, s, &args); +} + +/// The gates' rank-r down rows, then the gated, normed inputs: a block a (row, gate) each. +pub fn gates(k: *const Kernels, s: cuda.Stream, a: GateArgs, n: usize) !void { + try gateFits(a, n); + var args: cuda.Args = .{}; + args.add(a); + const grid: cuda.Dim3 = .{ .x = @intCast(a.rows), .y = @intCast(n) }; + const h: u32 = @intCast(a.h_dim); + try cuda.launch.launch(k.gate_down, .{ .grid = grid, .block = .{ .x = threads }, .shared = 2 * h * 4 }, s, &args); + try cuda.launch.launch(k.gate_mix, .{ .grid = grid, .block = .{ .x = threads }, .shared = h * 4 }, s, &args); +} + +test "loop: the argument structs keep loop.cu's layouts" { + try std.testing.expectEqual(@as(usize, 8 * 8 + 8 + 4 * 8 + 8 + 8 + 5 * 4 + 2 * 4 + 4), @sizeOf(MixArgs)); + try std.testing.expectEqual(@as(usize, 3 * 8 + 8 + 8 + 3 * 4 + 4 + 4 * 3 * 8 + 3 * 8 + 3 * 4 + 2 * 4 + 4), @sizeOf(GateArgs)); +} + +test "loop: shapes past the kernels' arrays are refused by name" { + const ok: MixArgs = .{ .partial = 1, .out = 1, .out_stride = 0, .n_blocks = 1, .partial_f32 = 0, .nq = 4, .rows = 1, .h = 2304, .eps = 1e-6, .scale = 1 }; + try mixFits(ok); + var bad = ok; + bad.nq = 5; + try std.testing.expectError(error.Inkling2LoopShape, mixFits(bad)); + bad = ok; + bad.n_blocks = 9; + try std.testing.expectError(error.Inkling2LoopShape, mixFits(bad)); + const g: GateArgs = .{ .msg = 1, .msg_stride = 0, .down = 1, .out = 1, .out_stride = 0, .rows = 1, .h_dim = 2304, .rank = 64, .eps_unit = 1e-6, .eps = 1e-6 }; + try gateFits(g, 3); + try std.testing.expectError(error.Inkling2LoopShape, gateFits(g, 4)); + var wide = g; + wide.rank = 129; + try std.testing.expectError(error.Inkling2LoopShape, gateFits(wide, 1)); +} diff --git a/zig/src/families/inkling2/mini_model.zig b/zig/src/families/inkling2/mini_model.zig new file mode 100644 index 00000000000..6ff25a1318f --- /dev/null +++ b/zig/src/families/inkling2/mini_model.zig @@ -0,0 +1,330 @@ +//! Inkling 2 Mini's forward on one GPU over cache slots: 48 visit slots a stream (40 sliding rings, 8 whole caches, +//! 48 conv states), prompt chunks of one stream and decode rows of many, embedding to soft-capped logits. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const wts = @import("mini_weights.zig"); +const attn = @import("kernels.zig"); +const ops = @import("ops.zig"); +const loop = @import("loop.zig"); +const visit = @import("mini_visit.zig"); + +const DeviceBuffer = cuda.DeviceBuffer; + +/// Prompt rows a forward takes at most: one stream's chunk. +pub const prompt_rows = 512; +/// Decode rows a forward takes over every stream. +pub const round_rows = 64; +/// The widest window one stream verifies in a decode forward. +pub const window_rows = 16; +/// Conv sites a visit keeps state for: the key and value convs, after attention, after the MLP. +pub const Site = enum { k, v, attn, mlp }; + +/// A stream's rows in one forward: its cache slot, first position and tokens. +pub const Chain = struct { slot: usize, p0: usize, tokens: []const u32 }; + +pub const Kernels = struct { + attn: attn.Kernels, + ops: ops.Kernels, + loop: loop.Kernels, + lane: cuda.qmmf.Lane, + dense: cuda.dense_rows.DenseRows, + nv: cuda.experts.Nvfp4Experts, + mx: cuda.experts_mx.Mxfp8Experts, + glue: cuda.moe_glue.MoeGlue, + plan_mod: cuda.Module, + router: cuda.grouped.Router, + + pub fn load(ctx: *const cuda.Context) !Kernels { + const d = ctx.d; + var k: Kernels = undefined; + k.attn = try attn.Kernels.load(d); + errdefer k.attn.unload(); + k.ops = try ops.Kernels.load(d); + errdefer k.ops.unload(); + k.loop = try loop.Kernels.load(d); + errdefer k.loop.unload(); + k.lane = try cuda.qmmf.Lane.load(d, (try ctx.capability()) / 10); + errdefer k.lane.unload(); + k.dense = try cuda.dense_rows.DenseRows.load(d); + errdefer k.dense.unload(); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + k.nv = try cuda.experts.Nvfp4Experts.load(d, sms); + errdefer k.nv.unload(); + k.mx = try cuda.experts_mx.Mxfp8Experts.load(d, sms); + errdefer k.mx.unload(); + k.glue = try cuda.moe_glue.MoeGlue.load(d); + errdefer k.glue.unload(); + k.plan_mod = try cuda.Module.load(d, cuda.kernels.experts); + errdefer k.plan_mod.unload(); + k.router = try cuda.grouped.Router.resolve(k.plan_mod); + return k; + } + + pub fn deinit(k: *Kernels) void { + k.plan_mod.unload(); + k.glue.unload(); + k.mx.unload(); + k.nv.unload(); + k.dense.unload(); + k.lane.unload(); + k.loop.unload(); + k.ops.unload(); + k.attn.unload(); + } + + pub fn experts(k: *const Kernels) cuda.experts.Grouped { + return .{ .nvfp4 = &k.nv, .mxfp8 = &k.mx }; + } +}; + +/// The forward's device scratch, sized for `prompt_rows` rows (decode rounds use the first `round_rows`). +pub const Scratch = struct { + ids: u64, // int32 [R] + pos: u64, // int32 [R] + seg_of: u64, // int32 [R]: the row's stream in the call + segs: [2]u64, // attention Seg [streams]: sliding, then full caches (offsets differ by cache length) + conv_segs: u64, // int4 [streams]: row0, rows, slot + tiles: u64, // attention Tile [max tiles] + h: [2]u64, // bf16 [R, H]: the running state in, the next visit's out + blocks: u64, // bf16 [max blocks][R, H] + bank: u64, // bf16 [bank blocks][R, H]: the previous pass's blocks past its entry + bank_h: u64, // bf16 [R, H]: the previous pass's output + msg: u64, // fp32 [4][R, H] + mixf: u64, // fp32 [3][R, H] + gdown: u64, // bf16 [3][R][rank] + xin: u64, // bf16 [3][R, H] + q: u64, + kraw: u64, + vraw: u64, + rel: u64, + gate: u64, + sink: u64, + dyn: [2]u64, // fp32 [R, kv * 4] + kc: u64, + vc: u64, + qp: u64, + relp: u64, + tab: u64, + part_o: u64, + part_ml: u64, + att: u64, + o: u64, + h32: u64, // fp32 [R, H] + xm: u64, + scores: u64, + pick: u64, + rw: u64, + plan: cuda.grouped.Plan, + act: u64, + y: u64, + moe: u64, + xf: u64, + logits: u64, // fp32 [round_rows, unpadded vocab] + lane_part: u64, + entries: usize, // (row, head, partial) slots part_o and part_ml hold +}; + +pub const Model = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + w: *const wts.Weights, + c: *const config.Text, + context: usize, // positions a slot holds + slots: usize, + sliding: attn.Layer, + full: attn.Layer, + kv: [2][config.max_visits]u64 = undefined, // a visit's K and V: [slots][kv][len][128] bf16 + conv: [config.max_visits][4]u64 = undefined, // a visit's conv states: fp32 [slots][3][C] by Site + s: Scratch = undefined, + buffers: std.ArrayList(DeviceBuffer) = .empty, + planned: ?usize = null, // a plan: the bytes counted, nothing allocated + + fn alloc(m: *Model, bytes: usize) !u64 { + if (m.planned) |*p| { + p.* += std.mem.alignForward(usize, @max(bytes, 256), 256); + return 0; + } + var b = try DeviceBuffer.alloc(m.d, @max(bytes, 256)); + errdefer b.free(); + try m.buffers.append(m.gpa, b); + return b.ptr; + } + + fn zeros(m: *Model, s: cuda.Stream, bytes: usize) !u64 { + const p = try m.alloc(bytes); + if (m.planned == null) try m.d.check(m.d.api.cuMemsetD8Async(p, 0, bytes, s.handle), "cuMemsetD8Async"); + return p; + } + + fn blank(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const wts.Weights, context: usize, slots: usize) Model { + return .{ + .gpa = gpa, + .d = d, + .w = w, + .c = &w.config.text, + .context = context, + .slots = slots, + .sliding = attn.Layer.sliding(w.config.text.window, prompt_rows), + .full = attn.Layer.global(@intCast(context)), + }; + } + + /// The caches and scratch of `slots` streams at `context` positions. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, k: *const Kernels, context: usize, slots: usize) !Model { + var m = blank(gpa, d, w, context, slots); + errdefer m.deinit(); + try m.build(s, k); + try s.synchronize(); + return m; + } + + /// The device bytes init would allocate. + pub fn openBytes(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, k: *const Kernels, context: usize, slots: usize) !usize { + var m = blank(gpa, d, w, context, slots); + m.planned = 0; + try m.build(s, k); + return m.planned.?; + } + + /// One stream's caches: 40 sliding rings, 8 whole caches and 48 conv states (Mini). + pub fn streamBytes(m: *const Model) usize { + const t = m.c; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + const v = &m.w.plan.visits; + const caches = v.count(.sliding) * m.sliding.ring + v.count(.full) * m.full.ring; + return caches * kvw * 2 * 2 + v.count(.conv) * 3 * (2 * kvw + 2 * @as(usize, t.hidden)) * 4; + } + + pub fn deinit(m: *Model) void { + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + } + + fn build(m: *Model, s: cuda.Stream, k: *const Kernels) !void { + const t = m.c; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + for (m.w.plan.visits.slice(), 0..) |step, i| { + const len: usize = if (step.of(.full) != null) m.full.ring else m.sliding.ring; + for (0..2) |side| m.kv[side][i] = try m.alloc(m.slots * len * kvw * 2); + for (std.enums.values(Site)) |site| { + const width: usize = if (site == .k or site == .v) kvw else t.hidden; + m.conv[i][@intFromEnum(site)] = try m.zeros(s, m.slots * 3 * width * 4); + } + } + try m.scratch(k); + } + + fn scratch(m: *Model, k: *const Kernels) !void { + const t = m.c; + const r: usize = prompt_rows; + const h: usize = t.hidden; + const q: usize = @as(usize, t.local.q) * t.local.dim; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + const heads: usize = t.local.q; + const rank: usize = t.loop.?.rank; + const pairs = r * t.topk; + const blocks = (t.layers + t.block - 1) / t.block; + // partials: every prompt row's sliding or full chunks, or a split decode call's sub-chunks + const stride_full = attn.slotsFor(m.full, m.context); + const entries = @max(r * heads * @max(attn.slotsFor(m.sliding, m.context), stride_full), attn.split_rows * heads * stride_full * attn.subs); + var part: usize = 0; + for (m.w.layers) |l| for ([_]cuda.qmmf.Weight{ l.attn.wq, l.attn.wk, l.attn.wv, l.attn.wr, l.attn.gate, l.attn.sink, l.attn.wo }) |w| { + for (1..r + 1) |rows| part = @max(part, k.lane.partBytes(rows, w)); + }; + for (1..round_rows + 1) |rows| part = @max(part, k.lane.partBytes(rows, m.w.unembed)); + const items = cuda.grouped.maxItems(pairs, t.experts, 64); + m.s = .{ + .ids = try m.alloc(r * 4), + .pos = try m.alloc(r * 4), + .seg_of = try m.alloc(r * 4), + .segs = .{ try m.alloc(round_rows * @sizeOf(attn.Seg)), try m.alloc(round_rows * @sizeOf(attn.Seg)) }, + .conv_segs = try m.alloc(round_rows * 16), + .tiles = try m.alloc((attn.tileCount(r, 3) + round_rows) * @sizeOf(attn.Tile)), + .h = .{ try m.alloc(r * h * 2), try m.alloc(r * h * 2) }, + .blocks = try m.alloc(blocks * r * h * 2), + .bank = try m.alloc(@max(1, m.w.plan.bank_blocks) * r * h * 2), + .bank_h = try m.alloc(r * h * 2), + .msg = try m.alloc(4 * r * h * 4), + .mixf = try m.alloc(3 * r * h * 4), + .gdown = try m.alloc(3 * r * rank * 2), + .xin = try m.alloc(3 * r * h * 2), + .q = try m.alloc(r * q * 2), + .kraw = try m.alloc(r * kvw * 2), + .vraw = try m.alloc(r * kvw * 2), + .rel = try m.alloc(r * heads * t.d_rel * 2), + .gate = try m.alloc(r * q * 2), + .sink = try m.alloc(r * heads * 2), + .dyn = .{ try m.alloc(r * t.global.kv * config.conv_taps * 4), try m.alloc(r * t.global.kv * config.conv_taps * 4) }, + .kc = try m.alloc(r * kvw * 2), + .vc = try m.alloc(r * kvw * 2), + .qp = try m.alloc(r * q * 2), + .relp = try m.alloc(r * heads * t.d_rel * 2), + .tab = try m.alloc(attn.tableBytes(r, @intCast(heads))), + .part_o = try m.alloc(entries * attn.head_dim * 4), + .part_ml = try m.alloc(entries * 8), + .att = try m.alloc(r * q * 2), + .o = try m.alloc(r * h * 2), + .h32 = try m.alloc(r * h * 4), + .xm = try m.alloc(r * h * 2), + .scores = try m.alloc(r * t.experts * 4), + .pick = try m.alloc(pairs * 4), + .rw = try m.alloc(pairs * 4), + .plan = .{ + .members = try m.alloc(pairs * 4), + .items = try m.alloc(items * 12), + .counts = try m.alloc(8), + .rank = try m.alloc(pairs * 4), + .hist = try m.alloc(((pairs + 1023) / 1024) * t.experts * 4), + }, + .act = try m.alloc(pairs * t.expert_inter * 2), + .y = try m.alloc(pairs * h * 4), + .moe = try m.alloc(r * h * 2), + .xf = try m.alloc(r * h * 2), + .logits = try m.alloc(round_rows * t.unpadded_vocab * 4), + .lane_part = try m.alloc(part), + .entries = entries, + }; + } + + pub fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(m.d, dst, bytes, s); + } + + pub fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); + } + + /// A slot's conv states to zero: a stream starting at position 0 has no inputs before it. + pub fn clear(m: *Model, s: cuda.Stream, slot: usize) !void { + const t = m.c; + const kvw: usize = @as(usize, t.local.kv) * t.local.dim; + for (0..m.w.plan.visits.len) |v| for (std.enums.values(Site)) |site| { + const width: usize = if (site == .k or site == .v) kvw else t.hidden; + const at = m.conv[v][@intFromEnum(site)] + slot * 3 * width * 4; + try m.d.check(m.d.api.cuMemsetD8Async(at, 0, 3 * width * 4, s.handle), "cuMemsetD8Async"); + }; + } + + /// Every chain's rows (one prompt chunk, or decode windows); rows [head0, head0 + heads)'s fp32 logits at s.logits. + pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, chains: []const Chain, prompt: bool, head0: usize, heads: usize) !void { + var rows: usize = 0; + for (chains, 0..) |ch, i| { + if (ch.tokens.len == 0 or ch.slot >= m.slots or ch.p0 + ch.tokens.len > m.context) return error.BadChain; + if (!prompt and ch.tokens.len > window_rows) return error.WindowTooWide; + for (chains[0..i]) |o| if (o.slot == ch.slot) return error.BadChain; + for (ch.tokens) |id| if (id >= m.c.vocab) return error.InvalidToken; + rows += ch.tokens.len; + } + if (rows == 0 or rows > @as(usize, if (prompt) prompt_rows else round_rows) or (prompt and chains.len != 1)) return error.TooManyRows; + if (chains.len > round_rows or heads > round_rows or head0 + heads > rows) return error.TooManyRows; + for (chains) |ch| if (ch.p0 == 0) try m.clear(s, ch.slot); + var r = try visit.Rows.stage(m, s, chains, rows, prompt); + try visit.run(m, k, s, &r, head0, heads); + } +}; + +test "the forward's launches type-check against the shared operators" { + std.testing.refAllDecls(Model); + std.testing.refAllDecls(Kernels); +} diff --git a/zig/src/families/inkling2/mini_ref.zig b/zig/src/families/inkling2/mini_ref.zig new file mode 100644 index 00000000000..24eba024369 --- /dev/null +++ b/zig/src/families/inkling2/mini_ref.zig @@ -0,0 +1,481 @@ +//! Inkling 2 Mini's forward in float64 on the host over a whole token sequence: the reference the CUDA engine's greedy +//! tokens are checked against (teacher-forced: each position's argmax and its margin). No intermediate rounding; the +//! stored weights decoded exactly (NVFP4 factor as experts_mx.nvfp4Factor). Slow: tiny checkpoint, short runs. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const names = @import("names.zig"); + +const Tensor = core.checkpoint.Tensor; +const Checkpoint = core.checkpoint.Checkpoint; + +/// Each position's top token, its margin over the runner-up and the top logit (soft-capped). +pub const Pick = struct { id: u32, margin: f64, top: f64 }; + +const e4m3_table = blk: { + @setEvalBranchQuota(100000); + var t: [256]f64 = undefined; + for (0..256) |i| t[i] = core.expert_decode.e4m3(@intCast(i)); + break :blk t; +}; + +fn bf(bytes: []const u8, i: usize) f64 { + const u: u32 = std.mem.readInt(u16, bytes[2 * i ..][0..2], .little); + return @as(f32, @bitCast(u << 16)); +} + +fn f32At(bytes: []const u8, i: usize) f64 { + return std.mem.bytesToValue(f32, bytes[4 * i ..][0..4]); +} + +fn dotBf(w: []const u8, row: usize, k: usize, x: []const f64) f64 { + var s: f64 = 0; + const base = row * k; + for (0..k) |i| s += bf(w, base + i) * x[i]; + return s; +} + +/// y[n] = W[n, k] (bf16) x. +fn matvec(w: Tensor, x: []const f64, y: []f64) void { + const k = x.len; + for (y, 0..) |*o, j| o.* = dotBf(w.bytes, j, k, x); +} + +fn rmsInv(x: []const f64, eps: f64) f64 { + var s: f64 = 0; + for (x) |v| s += v * v; + return 1.0 / @sqrt(s / @as(f64, @floatFromInt(x.len)) + eps); +} + +fn sigmoid(x: f64) f64 { + return 1.0 / (1.0 + @exp(-x)); +} + +fn mat2(a: std.mem.Allocator, n: usize, w: usize) ![][]f64 { + const x = try a.alloc([]f64, n); + for (x) |*row| row.* = try a.alloc(f64, w); + return x; +} + +/// x * scale (bf16 [.], from `at`), clipped to L2 norm `thr`, times tau. +fn clipScaled(x: []f64, scale: ?[]const u8, at: usize, thr: f64, tau: f64) void { + if (scale) |sb| for (x, 0..) |*v, i| { + v.* *= bf(sb, at + i); + }; + var s: f64 = 0; + for (x) |v| s += v * v; + const f = @min(thr / (@sqrt(s) + 1e-6), 1); + for (x) |*v| v.* *= f * tau; +} + +/// A causal short conv over positions, in place: static [C][4] taps (oldest first, the newest times x) over +/// sqrt(5), or with `dyn` ([n][heads * 4] input-dependent taps) the static_w [4][C] form over 3; a residual x each. +fn convTime(x: [][]f64, w: Tensor, dyn: ?[][]f64, heads: usize) !void { + const n = x.len; + if (n == 0) return; + const c = x[0].len; + var prev: [3][]f64 = undefined; + var buf: [3][8192]f64 = undefined; + if (c > 8192) return error.Inkling2RefWidth; + for (0..3) |k| { + prev[k] = buf[k][0..c]; + @memset(prev[k], 0); + } + for (0..n) |t| { + const cur = x[t]; + for (0..c) |ch| { + const h0 = prev[0][ch]; + const h1 = prev[1][ch]; + const h2 = prev[2][ch]; + const xi = cur[ch]; + var y: f64 = undefined; + if (dyn) |d| { + const hd = ch / (c / heads); + const dd = d[t][hd * 4 ..][0..4]; + y = (bf(w.bytes, ch) + dd[0]) * xi + (bf(w.bytes, c + ch) + dd[1]) * h2 + (bf(w.bytes, 2 * c + ch) + dd[2]) * h1 + (bf(w.bytes, 3 * c + ch) + dd[3]) * h0; + y = (y + xi) / 3.0; + } else { + y = bf(w.bytes, ch * 4) * h0 + bf(w.bytes, ch * 4 + 1) * h1 + bf(w.bytes, ch * 4 + 2) * h2 + bf(w.bytes, ch * 4 + 3) * xi; + y = (y + xi) / @sqrt(5.0); + } + prev[0][ch] = h1; + prev[1][ch] = h2; + prev[2][ch] = xi; + cur[ch] = y; + } + } +} + +/// Row `row` of one expert's stored matrix (k inputs) dotted with x: NVFP4 codes x E4M3 block scales, or MXFP8. +fn expertDot(nv: bool, codes: []const u8, scales: []const u8, k: usize, row: usize, x: []const f64) f64 { + var s: f64 = 0; + if (nv) { + const cr = codes[row * (k / 2) ..][0 .. k / 2]; + const sr = scales[row * (k / 16) ..][0 .. k / 16]; + for (0..k) |i| s += core.expert_decode.e2m1(core.expert_decode.nibble(cr, i)) * e4m3_table[sr[i / 16]] * x[i]; + } else { + const cr = codes[row * k ..][0..k]; + const sr = scales[row * (k / 32) ..][0 .. k / 32]; + for (0..k) |i| s += e4m3_table[cr[i]] * core.expert_decode.e8m0(sr[i / 32]) * x[i]; + } + return s; +} + +pub const Ref = struct { + gpa: std.mem.Allocator, + c: config.Config, + p: plan_.Plan, + ck: *Checkpoint, + + fn get(r: *Ref, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [128]u8 = undefined; + return r.ck.get(try std.fmt.bufPrint(&buf, fmt, args)); + } + + /// The residual mix of `query` (fp32 rows) over sources (blocks then the partial) at one position, no norm. + fn mixOne(h: usize, sources: []const []const f64, query: []const u8, qrow: usize, out: []f64) void { + var w: [16]f64 = undefined; + var inv: [16]f64 = undefined; + var m: f64 = -std.math.inf(f64); + for (sources, 0..) |s, j| { + inv[j] = rmsInv(s, 1e-6); + var d: f64 = 0; + for (0..h) |i| d += f32At(query, qrow * h + i) * s[i]; + w[j] = d * inv[j] / @sqrt(@as(f64, @floatFromInt(h))); + m = @max(m, w[j]); + } + var l: f64 = 0; + for (sources, 0..) |_, j| { + w[j] = @exp(w[j] - m); + l += w[j]; + } + @memset(out, 0); + for (sources, 0..) |s, j| for (0..h) |i| { + out[i] += w[j] / l * inv[j] * s[i]; + }; + } + + fn normInto(x: []f64, gamma: Tensor, eps: f64) void { + const r = rmsInv(x, eps); + for (x, 0..) |*v, i| v.* = v.* * r * bf(gamma.bytes, i); + } + + /// A gate: (1 - tanh(Wf d)) h + tanh(Wg d) m with d = Wdown [unit(h), unit(m)], then normed by `gamma`. + fn gate(r: *Ref, h: []const f64, msg: []const f64, ctl_layer: u32, comptime name: []const u8, gamma: Tensor, out: []f64) !void { + const hd = h.len; + const rank: usize = r.c.text.loop.?.rank; + const eps: f64 = r.c.text.eps; + const down = try r.get("model.llm.layers.{d}.controllers." ++ name ++ ".down_weight", .{ctl_layer}); + const forget = try r.get("model.llm.layers.{d}.controllers." ++ name ++ ".forget_weight", .{ctl_layer}); + const gain = try r.get("model.llm.layers.{d}.controllers." ++ name ++ ".gain_weight", .{ctl_layer}); + const cat = try r.gpa.alloc(f64, 2 * hd); + defer r.gpa.free(cat); + const ih = rmsInv(h, eps); + const im = rmsInv(msg, eps); + for (0..hd) |i| { + cat[i] = h[i] * ih; + cat[hd + i] = msg[i] * im; + } + var d: [config.max_gate_rank]f64 = undefined; + for (0..rank) |j| d[j] = dotBf(down.bytes, j, 2 * hd, cat); + for (0..hd) |i| { + const f = dotBf(forget.bytes, i, rank, d[0..rank]); + const g = dotBf(gain.bytes, i, rank, d[0..rank]); + out[i] = (1 - std.math.tanh(f)) * h[i] + std.math.tanh(g) * msg[i]; + } + normInto(out, gamma, eps); + } + + /// Teacher-forced picks of every position of `ids` (`out.len == ids.len`). + pub fn run(r: *Ref, ids: []const u32, out: []Pick) !void { + var arena = std.heap.ArenaAllocator.init(r.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const t = &r.c.text; + const n = ids.len; + const h: usize = t.hidden; + const nblocks = (t.layers + t.block - 1) / t.block; + var hcur = try mat2(a, n, h); + var hnext = try mat2(a, n, h); + var blocks: [16][][]f64 = undefined; + for (0..nblocks) |b| blocks[b] = try mat2(a, n, h); + const bank = try mat2(a, n, h); + const bank_h = try mat2(a, n, h); + const embed = try r.get("model.llm.embed.weight", .{}); + const enorm = try r.get("model.llm.embed_norm.weight", .{}); + for (ids, 0..) |id, i| { + for (0..h) |c| hcur[i][c] = bf(embed.bytes, @as(usize, id) * h + c); + normInto(hcur[i], enorm, t.eps); + } + for (r.p.visits.slice(), 0..) |_, v| { + try r.visit(a, @intCast(v), ids.len, hcur, hnext, &blocks, bank, bank_h); + std.mem.swap([][]f64, &hcur, &hnext); + } + const oq = try r.get("model.llm.attn_res.output_query", .{}); + const norm = try r.get("model.llm.norm.weight", .{}); + const unembed = try r.get("model.llm.unembed.weight", .{}); + const xf = try a.alloc(f64, h); + var src: [17][]const f64 = undefined; + for (0..n) |i| { + const nb = r.p.final_sources - 1; + for (0..nb) |b| src[b] = blocks[b][i]; + src[nb] = hcur[i]; + mixOne(h, src[0 .. nb + 1], oq.bytes, 0, xf); + normInto(xf, norm, t.eps); + var best: Pick = .{ .id = 0, .margin = 0, .top = -std.math.inf(f64) }; + var second = -std.math.inf(f64); + for (0..t.unpadded_vocab) |vid| { + const l = t.logit_cap * std.math.tanh(dotBf(unembed.bytes, vid, h, xf) / t.logit_cap); + if (l > best.top) { + second = best.top; + best = .{ .id = @intCast(vid), .margin = 0, .top = l }; + } else if (l > second) second = l; + } + best.margin = best.top - second; + out[i] = best; + } + } + + fn visit(r: *Ref, a: std.mem.Allocator, v: u32, n: usize, hin: [][]f64, hout: [][]f64, blocks: *[16][][]f64, bank: [][]f64, bank_h: [][]f64) !void { + const t = &r.c.text; + const p = &r.p; + const i = p.visits.steps[v].layer; + const spec = p.at(i); + const h: usize = t.hidden; + const global = spec.kind == .global; + const msgs = p.messages(v); + const L = .{i}; + if (p.bank_blocks > 1) return error.Inkling2RefBank; // one banked block (Mini), or none (the tiny checkpoint) + if (p.restarts(v)) for (0..n) |row| { + for (0..p.bank_blocks) |b| @memcpy(bank[row], blocks[p.pre_blocks + 1 + b][row]); + @memcpy(bank_h[row], hin[row]); + @memcpy(hin[row], blocks[p.pre_blocks][row]); + }; + const xin = [3][][]f64{ try a.alloc([]f64, n), try a.alloc([]f64, n), try a.alloc([]f64, n) }; + const msg = [4][][]f64{ try a.alloc([]f64, n), try a.alloc([]f64, n), try a.alloc([]f64, n), try a.alloc([]f64, n) }; + var norms: [3]Tensor = undefined; + if (global) { + norms = .{ try r.get("model.llm.layers.{d}.q_input_norm.weight", L), try r.get("model.llm.layers.{d}.k_input_norm.weight", L), try r.get("model.llm.layers.{d}.v_input_norm.weight", L) }; + } else { + const one = try r.get("model.llm.layers.{d}.attn_norm.weight", L); + norms = .{ one, one, one }; + } + const aq: ?Tensor = if (i > 0) try r.get("model.llm.attn_res.attn_queries.{d}", .{i - 1}) else null; + const core_j = p.coreIndex(v); + const cross = .{ try r.get("model.llm.middle_cycle_cross_pass_queries", .{}), try r.get("model.llm.middle_cycle_cross_pass_kv_queries", .{}) }; + var src: [17][]const f64 = undefined; + for (0..n) |row| { + for (0..3) |q| xin[q][row] = try a.alloc(f64, h); + if (msgs) { + for (0..4) |q| msg[q][row] = try a.alloc(f64, h); + for (0..p.bank_blocks) |b| src[b] = bank[row]; + src[p.bank_blocks] = bank_h[row]; + const sources = src[0 .. p.bank_blocks + 1]; + // the message queries: main 2j (q), kv 2j (k), kv 2j + 1 (v), main 2j + 1 (mlp) + mixOne(h, sources, cross[0].bytes, 2 * core_j, msg[0][row]); + mixOne(h, sources, cross[1].bytes, 2 * core_j, msg[1][row]); + mixOne(h, sources, cross[1].bytes, 2 * core_j + 1, msg[2][row]); + mixOne(h, sources, cross[0].bytes, 2 * core_j + 1, msg[3][row]); + } + const nq: usize = spec.attn_queries; + for (0..spec.blocks_in) |b| src[b] = blocks[b][row]; + src[spec.blocks_in] = hin[row]; + for (0..@max(nq, 1)) |q| { + if (i == 0) { + @memcpy(xin[q][row], hin[row]); + } else mixOne(h, src[0 .. spec.blocks_in + 1], aq.?.bytes, q, xin[q][row]); + } + if (msgs) { + var y: [3][]f64 = undefined; + inline for (.{ "attn", "k", "v" }, 0..) |name, g| { + y[g] = try a.alloc(f64, h); + try r.gate(xin[if (nq == 3) g else 0][row], msg[g][row], i, name, norms[g], y[g]); + } + for (0..3) |g| @memcpy(xin[g][row], y[g]); + } else for (0..@max(nq, 1)) |q| normInto(xin[q][row], norms[q], t.eps); + if (!global and !msgs) for (1..3) |q| @memcpy(xin[q][row], xin[0][row]); + } + // the attention, its conv into the residual, the block boundary, the MLP input, experts and the MLP conv + const h32 = try mat2(a, n, h); + try r.attention(a, v, n, xin, h32); + try convTime(h32, try r.get("model.llm.layers.{d}.attn_sconv.weight", L), null, 1); + for (0..n) |row| if (!spec.boundary) for (0..h) |c| { + h32[row][c] += hin[row][c]; + }; + if (spec.boundary and !p.restarts(v)) for (0..n) |row| @memcpy(blocks[i / t.block][row], hin[row]); + const nb = spec.blocks_in + @intFromBool(spec.boundary); + const mq = try r.get("model.llm.attn_res.mlp_queries.{d}", L); + const mnorm = try r.get("model.llm.layers.{d}.mlp_norm.weight", L); + const moe = try mat2(a, n, h); + const xm = try a.alloc(f64, h); + for (0..n) |row| { + for (0..nb) |b| src[b] = blocks[b][row]; + src[nb] = h32[row]; + mixOne(h, src[0 .. nb + 1], mq.bytes, 0, xm); + if (msgs) { + const y = try a.alloc(f64, h); + try r.gate(xm, msg[3][row], i, "mlp", mnorm, y); + @memcpy(xm, y); + } else normInto(xm, mnorm, t.eps); + try r.experts(a, i, xm, moe[row]); + } + try convTime(moe, try r.get("model.llm.layers.{d}.mlp_sconv.weight", L), null, 1); + for (0..n) |row| for (0..h) |c| { + hout[row][c] = h32[row][c] + moe[row][c]; + }; + } + + /// The routed experts at one position: sigmoid scores, top-k by score + bias, the soft-capped SwiGLU, weighted sum. + fn experts(r: *Ref, a: std.mem.Allocator, i: u32, x: []const f64, out: []f64) !void { + const t = &r.c.text; + const h: usize = t.hidden; + const m: usize = t.expert_inter; + const L = .{i}; + const router = try r.get("model.llm.layers.{d}.mlp.gate.weight", L); + const bias = try r.get("model.llm.layers.{d}.mlp.gate.bias", L); + var score: [512]f64 = undefined; + var sel: [512]f64 = undefined; + for (0..t.experts) |e| { + score[e] = sigmoid(dotBf(router.bytes, e, h, x)); + sel[e] = score[e] + f32At(bias.bytes, e); + } + var pick: [32]usize = undefined; + var total: f64 = 0; + for (0..t.topk) |k| { + var best: usize = 0; + var bv = -std.math.inf(f64); + for (0..t.experts) |e| if (sel[e] > bv) { + bv = sel[e]; + best = e; + }; + pick[k] = best; + sel[best] = -std.math.inf(f64); + total += score[best]; + } + const pre = "model.llm.layers.{d}.mlp.experts."; + const w13 = try r.get(pre ++ "w13_weight", L); + const s13 = try r.get(pre ++ "w13_weight_scale", L); + const w2 = try r.get(pre ++ "w2_weight", L); + const s2 = try r.get(pre ++ "w2_weight_scale", L); + const nv = w13.dtype == .u8; + var f13: f64 = 1; + var f2: f64 = 1; + const act = try a.alloc(f64, m); + @memset(out, 0); + for (pick[0..t.topk]) |e| { + if (nv) { + const den: f32 = @floatCast(f32At((try r.get(pre ++ "w13_weight_outer_scale_denominator", L)).bytes, 0)); + f13 = @import("cuda").experts_mx.nvfp4Factor(@floatCast(f32At((try r.get(pre ++ "w13_weight_amax", L)).bytes, e)), den); + f2 = @import("cuda").experts_mx.nvfp4Factor(@floatCast(f32At((try r.get(pre ++ "w2_weight_amax", L)).bytes, e)), den); + } + const c13 = w13.bytes[e * (w13.bytes.len / t.experts) ..][0 .. w13.bytes.len / t.experts]; + const sc13 = s13.bytes[e * (s13.bytes.len / t.experts) ..][0 .. s13.bytes.len / t.experts]; + for (0..m) |j| { + var gu: [2]f64 = .{ 0, 0 }; + for (0..2) |half| gu[half] = expertDot(nv, c13, sc13, h, 2 * j + half, x) * f13; // rows interleave gate, up + act[j] = sigmoid(gu[0]) * t.gate_cap * std.math.tanh(gu[0] / t.gate_cap) * t.up_cap * std.math.tanh(gu[1] / t.up_cap); + } + const c2 = w2.bytes[e * (w2.bytes.len / t.experts) ..][0 .. w2.bytes.len / t.experts]; + const sc2 = s2.bytes[e * (s2.bytes.len / t.experts) ..][0 .. s2.bytes.len / t.experts]; + const w = score[e] / (total + 1e-20) * t.route_scale; + for (0..h) |row| out[row] += w * expertDot(nv, c2, sc2, m, row, act) * f2; + } + } + + /// The attention of every position at visit `v` from its inputs (q from plane 0, k from 1, v from 2) into `y`. + fn attention(r: *Ref, a: std.mem.Allocator, v: u32, n: usize, xin: [3][][]f64, y: [][]f64) !void { + const t = &r.c.text; + const p = &r.p; + const i = p.visits.steps[v].layer; + const global = p.at(i).kind == .global; + const L = .{i}; + const hd = t.local; + const qw: usize = @as(usize, hd.q) * hd.dim; + const kvw: usize = @as(usize, hd.kv) * hd.dim; + const dr: usize = t.d_rel; + const q = try mat2(a, n, qw); + const k = try mat2(a, n, kvw); + const vv = try mat2(a, n, kvw); + const rel = try mat2(a, n, hd.q * dr); + const gate_ = try mat2(a, n, qw); + const sink = try mat2(a, n, hd.q); + const w = .{ + try r.get("model.llm.layers.{d}.attn.wq_du.weight", L), try r.get("model.llm.layers.{d}.attn.wk_dv.weight", L), + try r.get("model.llm.layers.{d}.attn.wv_dv.weight", L), try r.get("model.llm.layers.{d}.attn.wr_du.weight", L), + try r.get("model.llm.layers.{d}.attn.gate_attn.weight", L), try r.get("model.llm.layers.{d}.attn.attn_sink_proj.weight", L), + }; + for (0..n) |row| { + matvec(w[0], xin[0][row], q[row]); + matvec(w[1], xin[1][row], k[row]); + matvec(w[2], xin[2][row], vv[row]); + matvec(w[3], xin[0][row], rel[row]); + matvec(w[4], xin[0][row], gate_[row]); + matvec(w[5], xin[0][row], sink[row]); + } + if (global) { + const taps = kvw / hd.dim * 4; + const dk = try mat2(a, n, taps); + const dv = try mat2(a, n, taps); + const pk = try r.get("model.llm.layers.{d}.attn.k_sconv.weight_proj", L); + const pv = try r.get("model.llm.layers.{d}.attn.v_sconv.weight_proj", L); + for (0..n) |row| { + matvec(pk, xin[1][row], dk[row]); + matvec(pv, xin[2][row], dv[row]); + } + try convTime(k, try r.get("model.llm.layers.{d}.attn.k_sconv.static_w", L), dk, hd.kv); + try convTime(vv, try r.get("model.llm.layers.{d}.attn.v_sconv.static_w", L), dv, hd.kv); + } else { + try convTime(k, try r.get("model.llm.layers.{d}.attn.k_sconv.weight", L), null, 1); + try convTime(vv, try r.get("model.llm.layers.{d}.attn.v_sconv.weight", L), null, 1); + } + const qs = try r.get("model.llm.layers.{d}.attn.q_l2_clip.scale", L); + const rs = try r.get("model.llm.layers.{d}.attn.rel_l2_clip.scale", L); + const proj = try r.get("model.llm.layers.{d}.attn.rel_logits_proj.proj", L); + const extent: usize = proj.dim(1); + for (0..n) |row| { + const tau: f64 = if (global) 1 + t.log_alpha * @log(@max(@as(f64, @floatFromInt(row + 1)) / @as(f64, @floatFromInt(t.log_floor)), 1)) else 1; + for (0..hd.q) |hh| { + clipScaled(q[row][hh * hd.dim ..][0..hd.dim], qs.bytes, hh * hd.dim, t.qk_clip, tau); + clipScaled(rel[row][hh * dr ..][0..dr], rs.bytes, hh * dr, t.rel_clip, tau); + } + for (0..hd.kv) |hh| { + clipScaled(k[row][hh * hd.dim ..][0..hd.dim], null, 0, t.qk_clip, 1); + const vr = vv[row][hh * hd.dim ..][0..hd.dim]; + const inv = rmsInv(vr, t.eps); + for (vr) |*x| x.* *= inv; + } + } + const att = try mat2(a, n, qw); + const scale = 1.0 / @sqrt(@as(f64, @floatFromInt(hd.dim))); + const group = hd.q / hd.kv; + const sc = try a.alloc(f64, n); + for (0..n) |row| for (0..hd.q) |hh| { + const kh = hh / group; + const lo = if (global) 0 else (row + 1) -| t.window; + var mx: f64 = sink[row][hh]; + for (lo..row + 1) |j| { + var s: f64 = 0; + for (0..hd.dim) |d| s += q[row][hh * hd.dim + d] * k[j][kh * hd.dim + d]; + const dist = row - j; + var bias: f64 = 0; + if (dist < extent) for (0..dr) |d| { + bias += rel[row][hh * dr + d] * bf(proj.bytes, d * extent + dist); + }; + sc[j] = s * scale + bias; + mx = @max(mx, sc[j]); + } + var l: f64 = @exp(sink[row][hh] - mx); + const o = att[row][hh * hd.dim ..][0..hd.dim]; + @memset(o, 0); + for (lo..row + 1) |j| { + const e = @exp(sc[j] - mx); + l += e; + for (0..hd.dim) |d| o[d] += e * vv[j][kh * hd.dim + d]; + } + for (o, 0..) |*x, d| x.* = x.* / l * sigmoid(gate_[row][hh * hd.dim + d]); + }; + const wo = try r.get("model.llm.layers.{d}.attn.wo_ud.weight", L); + for (0..n) |row| matvec(wo, att[row], y[row]); + } +}; diff --git a/zig/src/families/inkling2/mini_visit.zig b/zig/src/families/inkling2/mini_visit.zig new file mode 100644 index 00000000000..83e2befc8df --- /dev/null +++ b/zig/src/families/inkling2/mini_visit.zig @@ -0,0 +1,241 @@ +//! One Mini forward's launches: the embedding, each visit (its input mix or gates, attention, convs, router, experts), +//! and the head. Visits, slots and passes come from the plan (core/visit_plan.zig); the loop math is loop.cu's. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const attn = @import("kernels.zig"); +const ops = @import("ops.zig"); +const loop = @import("loop.zig"); +const mm = @import("mini_model.zig"); + +const Model = mm.Model; +const Kernels = mm.Kernels; +const Site = mm.Site; + +/// A forward's rows as staged on the device: counts, the call's attention rows and its streams. +pub const Rows = struct { + n: usize, + streams: usize, + prompt: bool, + last_pos: u32, + n_tiles: u32, + + /// Ids, positions, segments and tiles of `chains` uploaded on `s`. + pub fn stage(m: *Model, s: cuda.Stream, chains: []const mm.Chain, rows: usize, prompt: bool) !Rows { + const gpa = m.gpa; + const ints = try gpa.alloc(i32, 3 * rows); + defer gpa.free(ints); + var segs: [2][mm.round_rows]attn.Seg = undefined; + var cs: [mm.round_rows][4]i32 = undefined; + const kvw: i64 = @as(i64, m.c.local.kv) * m.c.local.dim; + var at: usize = 0; + var last: u32 = 0; + for (chains, 0..) |ch, i| { + for (ch.tokens, 0..) |tok, j| { + ints[at + j] = @intCast(tok); + ints[rows + at + j] = @intCast(ch.p0 + j); + ints[2 * rows + at + j] = @intCast(i); + } + const slot: i64 = @intCast(ch.slot); + for ([_]attn.Layer{ m.sliding, m.full }, 0..) |l, side| { + segs[side][i] = .{ .row0 = @intCast(at), .n = @intCast(ch.tokens.len), .p0 = @intCast(ch.p0), .off = slot * kvw * l.ring }; + } + cs[i] = .{ @intCast(at), @intCast(ch.tokens.len), @intCast(ch.slot), 0 }; + last = @max(last, @as(u32, @intCast(ch.p0 + ch.tokens.len - 1))); + at += ch.tokens.len; + } + const group = m.c.local.q / m.c.local.kv; + var tiles: [attn.tileCount(mm.prompt_rows, 3) + mm.round_rows]attn.Tile = undefined; + const n_tiles = try attn.tiles(segs[0][0..chains.len], group, &tiles); + try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ints[0..rows])); + try m.upload(s, m.s.pos, std.mem.sliceAsBytes(ints[rows .. 2 * rows])); + try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(ints[2 * rows ..])); + for (0..2) |side| try m.upload(s, m.s.segs[side], std.mem.sliceAsBytes(segs[side][0..chains.len])); + try m.upload(s, m.s.conv_segs, std.mem.sliceAsBytes(cs[0..chains.len])); + try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); + return .{ .n = rows, .streams = chains.len, .prompt = prompt, .last_pos = last, .n_tiles = @intCast(n_tiles) }; + } +}; + +fn kvWidth(m: *const Model) usize { + return @as(usize, m.c.local.kv) * m.c.local.dim; +} + +/// The whole forward: embedding, every visit, then the head's rows [head0, head0 + heads). +pub fn run(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, head0: usize, heads: usize) !void { + const t = m.c; + const h: usize = t.hidden; + try ops.embed(&k.ops, s, m.s.ids, r.n, m.w.embed, m.w.embed_norm, m.s.h[0], h, t.eps); + var cur: usize = 0; + for (0..m.w.plan.visits.len) |v| { + try visitOne(m, k, s, r, @intCast(v), m.s.h[cur], m.s.h[1 - cur]); + cur = 1 - cur; + } + if (heads == 0) return; + const plane = r.n * h * 2; + const nb = m.w.plan.final_sources - 1; + var mix: ops.MixArgs = .{ .partial = m.s.h[cur], .query = m.w.output_query, .out = m.s.xf, .n_blocks = @intCast(nb), .partial_bf16 = 1, .nq = 1, .rows = @intCast(r.n), .c = @intCast(h), .eps = t.eps }; + for (0..nb) |j| mix.blocks[j] = m.s.blocks + j * plane; + mix.norm[0] = m.w.norm; + try ops.mix(&k.ops, s, mix); + const v: usize = t.unpadded_vocab; + try k.lane.matmulOut(s, m.s.xf + head0 * h * 2, h, heads, m.w.unembed, m.s.logits, .f32, m.s.lane_part); + try ops.softcap(&k.ops, s, m.s.logits, heads * v, t.logit_cap); +} + +fn proj(m: *const Model, k: *const Kernels, s: cuda.Stream, w: cuda.qmmf.Weight, x: u64, out: u64, n: usize) !void { + try k.lane.matmulOut(s, x, w.k, n, w, out, .bf16, m.s.lane_part); +} + +/// Bank the previous pass before a restart: its blocks past the entry, its output; the state restarts from the entry. +fn restart(m: *Model, s: cuda.Stream, r: *const Rows, hin: u64) !void { + const p = &m.w.plan; + const plane = r.n * m.c.hidden * 2; + for (0..p.bank_blocks) |j| try m.copy(s, m.s.bank + j * plane, m.s.blocks + (p.pre_blocks + 1 + j) * plane, plane); + try m.copy(s, m.s.bank_h, hin, plane); + try m.copy(s, hin, m.s.blocks + p.pre_blocks * plane, plane); +} + +/// The previous pass's messages for core layer `j`: four fp32 mixes over its banked blocks and output (q, k, v, mlp). +fn messages(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, j: u32) !void { + const h: usize = m.c.hidden; + const plane = r.n * h; + var a: loop.MixArgs = .{ .partial = m.s.bank_h, .out = m.s.msg, .out_stride = @intCast(plane), .n_blocks = @intCast(m.w.plan.bank_blocks), .partial_f32 = 0, .nq = 4, .rows = @intCast(r.n), .h = @intCast(h), .eps = m.c.eps, .scale = scale(h) }; + for (0..m.w.plan.bank_blocks) |b| a.blocks[b] = m.s.bank + b * plane * 2; + const row = @as(usize, j) * 2 * h * 4; + a.query = .{ m.w.cross_main + row, m.w.cross_kv + row, m.w.cross_kv + row + h * 4, m.w.cross_main + row + h * 4 }; + try loop.mix(&k.loop, s, a); +} + +fn scale(h: usize) f32 { + return @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(h)))); +} + +/// A core input through its gates: the residual mix of `nq` queries over `nb` blocks and the partial, then each gate +/// (controllers[g], message plane slots[g]) and its norm into `out` planes. +fn gated(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, nb: usize, partial: u64, f32_partial: bool, query: u64, nq: usize, ctl: []const @import("mini_weights.zig").Controller, slots: [3]i32, norms: [3]u64, out: u64) !void { + const h: usize = m.c.hidden; + const plane = r.n * h; + var a: loop.MixArgs = .{ .partial = partial, .out = m.s.mixf, .out_stride = @intCast(plane), .n_blocks = @intCast(nb), .partial_f32 = @intFromBool(f32_partial), .nq = @intCast(nq), .rows = @intCast(r.n), .h = @intCast(h), .eps = m.c.eps, .scale = scale(h) }; + for (0..nb) |b| a.blocks[b] = m.s.blocks + b * plane * 2; + for (0..nq) |q| a.query[q] = query + q * h * 4; + try loop.mix(&k.loop, s, a); + var g: loop.GateArgs = .{ .msg = m.s.msg, .msg_stride = @intCast(plane), .down = m.s.gdown, .out = out, .out_stride = @intCast(plane), .rows = @intCast(r.n), .h_dim = @intCast(h), .rank = @intCast(m.c.loop.?.rank), .eps_unit = m.c.eps, .eps = m.c.eps }; + for (0..ctl.len) |i| { + g.h[i] = m.s.mixf + (if (nq == 3) i else 0) * plane * 4; + g.slot[i] = slots[i]; + g.down_w[i] = ctl[i].down; + g.forget[i] = ctl[i].forget; + g.gain[i] = ctl[i].gain; + g.norm[i] = norms[i]; + } + try loop.gates(&k.loop, s, g, ctl.len); +} + +/// A short conv at `site` of visit `v` over the call's streams (their states by slot). +fn conv(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32, site: Site, a: ops.ConvArgs) !void { + var c = a; + c.state = m.conv[v][@intFromEnum(site)]; + c.segs = m.s.conv_segs; + c.state_stride = 3 * @as(i64, c.c); + c.rows = @intCast(r.n); + try ops.conv(&k.ops, s, c, r.streams); +} + +fn visitOne(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32, hin: u64, hout: u64) !void { + const t = m.c; + const p = &m.w.plan; + const step = p.visits.steps[v]; + const i: u32 = step.layer; + const spec = p.at(i); + const L = &m.w.layers[i]; + const a = &L.attn; + const h: usize = t.hidden; + const n = r.n; + const plane = n * h; + const global = spec.kind == .global; + const msgs = p.messages(v); + if (p.restarts(v)) try restart(m, s, r, hin); + // the attention's inputs: layer 0 norms the embedding; later layers mix blocks; core passes after the first gate + if (msgs) { + try messages(m, k, s, r, p.coreIndex(v)); + try gated(m, k, s, r, spec.blocks_in, hin, false, L.attn_query, spec.attn_queries, L.controllers.?[0..3], .{ 0, 1, 2 }, a.norms, m.s.xin); + } else { + var mix: ops.MixArgs = .{ .partial = hin, .query = if (i == 0) 0 else L.attn_query, .out = m.s.xin, .n_blocks = @intCast(if (i == 0) 0 else spec.blocks_in), .partial_bf16 = 1, .nq = if (i == 0) 1 else spec.attn_queries, .rows = @intCast(n), .c = @intCast(h), .eps = t.eps }; + for (0..spec.blocks_in) |j| mix.blocks[j] = m.s.blocks + j * plane * 2; + mix.norm = a.norms; + try ops.mix(&k.ops, s, mix); + } + const separate = global or msgs; + const xq = m.s.xin; + const xk = if (separate) m.s.xin + plane * 2 else xq; + const xv = if (separate) m.s.xin + 2 * plane * 2 else xq; + try proj(m, k, s, a.wq, xq, m.s.q, n); + try proj(m, k, s, a.wk, xk, m.s.kraw, n); + try proj(m, k, s, a.wv, xv, m.s.vraw, n); + try proj(m, k, s, a.wr, xq, m.s.rel, n); + try proj(m, k, s, a.gate, xq, m.s.gate, n); + try proj(m, k, s, a.sink, xq, m.s.sink, n); + const kvw = kvWidth(m); + const kvh: usize = t.local.kv; + const taps = kvh * config.conv_taps; + if (global) for ([_]u64{ xk, xv }, [_]u64{ a.k_taps, a.v_taps }, 0..) |x, w, side| { + // the taps as torch's bf16 linear leaves them: float(bf16(sum)) times 1 + try k.dense.rowsScaled(s, x, h, w, m.w.ones, m.s.dyn[side], taps, n, taps, h); + }; + for ([_]Site{ .k, .v }, [_]u64{ m.s.kraw, m.s.vraw }, [_]u64{ m.s.kc, m.s.vc }, [_]u64{ a.k_conv, a.v_conv }, 0..) |site, x, out, w, side| { + try conv(m, k, s, r, v, site, .{ .x = x, .state = 0, .w = w, .dyn = if (global) m.s.dyn[side] else 0, .out = out, .x_bf16 = 1, .heads = @intCast(kvh), .c = @intCast(kvw), .rows = 0, .mode = 0 }); + } + // q, rel and the caches' new K and V rows, the bias table, then attention through the sink and the output gate + const l = if (global) m.full else m.sliding; + const rows: attn.Rows = .{ .rows = @intCast(n), .heads = t.local.q, .kv_heads = t.local.kv, .pos = m.s.pos, .seg_of = m.s.seg_of, .segs = m.s.segs[@intFromBool(global)], .tiles = m.s.tiles, .n_tiles = r.n_tiles, .last_pos = r.last_pos, .streams = @intCast(r.streams) }; + const cache: attn.Cache = .{ .k = m.kv[0][v], .v = m.kv[1][v] }; + const prep: attn.Prep = .{ .qk_clip = t.qk_clip, .rel_clip = t.rel_clip, .floor = @floatFromInt(t.log_floor), .alpha = t.log_alpha, .eps = t.eps }; + try attn.prep(&k.attn, s, rows, l, prep, .{ m.s.q, m.s.kc, m.s.vc, m.s.rel }, .{ a.q_scale, a.rel_scale }, m.s.qp, m.s.relp, cache); + try attn.relTable(&k.attn, s, rows, m.s.relp, a.rel_proj, m.s.tab); + const stride = attn.slotsFor(l, m.context); + try attn.attend(&k.attn, s, rows, l, stride, m.s.entries, m.s.qp, cache, m.s.tab, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.att); + try proj(m, k, s, a.wo, m.s.att, m.s.o, n); + // the attention conv into the fp32 residual: a block boundary keeps only the attention output as the partial + try conv(m, k, s, r, v, .attn, .{ .x = m.s.o, .state = 0, .w = L.attn_conv, .base = if (spec.boundary) 0 else hin, .resid = m.s.h32, .x_bf16 = 1, .c = @intCast(h), .rows = 0, .mode = 1 }); + if (spec.boundary and !p.restarts(v)) try m.copy(s, m.s.blocks + @as(usize, i / t.block) * plane * 2, hin, plane * 2); + const nb = spec.blocks_in + @intFromBool(spec.boundary); + if (msgs) { + const mn = [3]u64{ L.mlp_norm, L.mlp_norm, L.mlp_norm }; + try gated(m, k, s, r, nb, m.s.h32, true, L.mlp_query, 1, L.controllers.?[3..4], .{ 3, 3, 3 }, mn, m.s.xm); + } else { + var mix: ops.MixArgs = .{ .partial = m.s.h32, .query = L.mlp_query, .out = m.s.xm, .n_blocks = @intCast(nb), .partial_bf16 = 0, .nq = 1, .rows = @intCast(n), .c = @intCast(h), .eps = t.eps }; + for (0..nb) |j| mix.blocks[j] = m.s.blocks + j * plane * 2; + mix.norm[0] = L.mlp_norm; + try ops.mix(&k.ops, s, mix); + } + try moe(m, k, s, r, L); + // the MLP conv: the next visit's state is bf16(h32 + bf16(conv(moe))) + try conv(m, k, s, r, v, .mlp, .{ .x = m.s.moe, .state = 0, .w = L.mlp_conv, .resid = m.s.h32, .out = hout, .x_bf16 = 1, .c = @intCast(h), .rows = 0, .mode = 2 }); +} + +/// The router's picks over sigmoid scores, the routed experts as stored (core experts), their weighted sum in bf16. +fn moe(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, L: *const @import("mini_weights.zig").Layer) !void { + const t = m.c; + const h: usize = t.hidden; + const n = r.n; + const pairs = n * t.topk; + try ops.rowdot(&k.ops, s, m.s.xm, L.router, m.s.scores, n, t.experts, h, false, true); + try ops.topk(&k.ops, s, m.s.scores, L.router_bias, m.s.pick, m.s.rw, n, t.experts, t.topk, t.route_scale); + const tile: usize = if (r.prompt) cuda.experts.promptTile(L.experts.format) else 16; + const items = cuda.grouped.maxItems(pairs, t.experts, tile); + try k.router.route(s, m.s.pick, pairs, t.experts, tile, m.s.plan); + const gx = k.experts(); + const up_in: cuda.experts.Rows = .{ .x = m.s.xm, .stride = h, .slots = t.topk }; + const down_in: cuda.experts.Rows = .{ .x = m.s.act, .stride = t.expert_inter }; + if (r.prompt) { + try gx.prompt(s, .up, up_in, L.experts, m.s.plan, m.s.act, items, pairs, tile, -1); + try gx.prompt(s, .down_bf16, down_in, L.experts, m.s.plan, m.s.y, items, pairs, tile, -1); + try k.glue.combine(s, m.s.y, .bf16, m.s.rw, m.s.moe, .bf16, n, t.topk, h); + } else { + try gx.decode(s, .up, up_in, L.experts, m.s.plan, m.s.act, items, pairs, tile, -1); + try gx.decode(s, .down_f32, down_in, L.experts, m.s.plan, m.s.y, items, pairs, tile, -1); + try k.glue.combine(s, m.s.y, .f32, m.s.rw, m.s.moe, .bf16, n, t.topk, h); + } +} diff --git a/zig/src/families/inkling2/mini_weights.zig b/zig/src/families/inkling2/mini_weights.zig new file mode 100644 index 00000000000..3799e7c51b8 --- /dev/null +++ b/zig/src/families/inkling2/mini_weights.zig @@ -0,0 +1,284 @@ +//! Inkling 2 Mini's weights on one GPU: bf16 projections packed for the core lane matmul, the stored NVFP4 and MXFP8 +//! experts packed for core experts (C3), and the small tensors (norms, convs, queries, gates) as the kernels read them. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const names = @import("names.zig"); +const plan_ = @import("plan.zig"); + +const DeviceBuffer = cuda.DeviceBuffer; +const Lane = cuda.qmmf.Weight; +const ex = cuda.experts; +const mx = cuda.experts_mx; +const Tensor = core.checkpoint.Tensor; + +/// NVFP4's outer scale denominator as Mini ships it (scales/RESULTS.md); another value is refused. +pub const nvfp4_denominator = 2688; + +pub const Attn = struct { + wq: Lane, + wk: Lane, + wv: Lane, + wr: Lane, // relative-bias queries [heads * d_rel, H] + gate: Lane, + sink: Lane, + wo: Lane, + k_taps: u64 = 0, // global: bf16 [kv * 4, H] (dense rows), the input-dependent conv taps + v_taps: u64 = 0, + q_scale: u64, // bf16 [heads, 128] + rel_scale: u64, // bf16 [heads, d_rel] + rel_proj: u64, // bf16 [d_rel, extent] + k_conv: u64, // sliding: bf16 [kv * 128][4]; global: static_w bf16 [4][kv * 128] + v_conv: u64, + norms: [3]u64, // sliding: attn_norm three times; global: the q, k and v input norms +}; + +pub const Controller = struct { down: u64, forget: u64, gain: u64 }; + +pub const Layer = struct { + attn: Attn, + attn_conv: u64, // bf16 [H][4] + mlp_conv: u64, + mlp_norm: u64, + router: u64, // bf16 [E, H] + router_bias: u64, // fp32 [E] + attn_query: u64 = 0, // fp32 [1 or 3, H]; 0 for layer 0 + mlp_query: u64, // fp32 [H] + controllers: ?[4]Controller = null, // core layers: attn (q), k, v inputs, then the MLP input + experts: ex.Layer, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + config: config.Config, + plan: plan_.Plan, + layers: []Layer = &.{}, + embed: u64 = 0, // bf16 [V, H] + embed_norm: u64 = 0, + norm: u64 = 0, + unembed: Lane = undefined, // the first unpadded_vocab rows + output_query: u64 = 0, // fp32 [H] + cross_main: u64 = 0, // fp32 [2 core, H] + cross_kv: u64 = 0, + ones: u64 = 0, // fp32 [max taps] of 1.0: dense rows' scaled form rounds the dynamic taps to bf16 + buffers: std.ArrayList(DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.* = undefined; + } + + fn upload(w: *Weights, d: *const cuda.Driver, bytes: []const u8) !u64 { + var b = try DeviceBuffer.fromHost(d, bytes); + errdefer b.free(); + try w.buffers.append(w.gpa, b); + w.bytes += bytes.len; + return b.ptr; + } + + /// A bf16 [n, k] projection (its first `rows` rows) in the lane's order, padded to 128 rows. + fn lane(w: *Weights, d: *const cuda.Driver, t: Tensor, rows: usize) !Lane { + const k = t.dim(t.rank - 1); + const n = rows; + const npad = cuda.modelopt.padded(n); + const out = try w.gpa.alloc(u16, npad * k); + defer w.gpa.free(out); + const src = try w.gpa.alloc(u16, n * k); + defer w.gpa.free(src); + @memcpy(std.mem.sliceAsBytes(src), t.bytes[0 .. n * k * 2]); + cuda.qmmf.packBf16(out, src, n, k); + return cuda.modelopt.bf16Weight(try w.upload(d, std.mem.sliceAsBytes(out)), n, k); + } +}; + +fn get(ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [128]u8 = undefined; + return ck.get(try std.fmt.bufPrint(&buf, fmt, args)); +} + +fn raw(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !u64 { + return w.upload(d, (try get(ck, fmt, args)).bytes); +} + +fn proj(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !Lane { + const t = try get(ck, fmt, args); + return w.lane(d, t, t.dim(0)); +} + +/// The header of every shard against the weight map: a missing, extra or misshapen tensor refuses the load by name. +fn admit(gpa: std.mem.Allocator, ck: *core.checkpoint.Checkpoint, c: *const config.Config, prec: []plan_.Precision) !void { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var all: core.safetensors.Header = .empty; + for (ck.files.items) |*f| try names.merge(a, &all, f.names); + try names.precisions(all, c.text.layers, prec); + const r = try names.check(a, c, all, .model); + if (r.clean()) return; + for (r.missing.items) |n| std.log.err("inkling2 mini: the checkpoint has no {s}", .{n}); + for (r.wrong.items) |n| std.log.err("inkling2 mini: {s} has another dtype or shape than the config implies", .{n}); + for (r.unknown.items) |n| std.log.err("inkling2 mini: {s} is not a tensor the config implies", .{n}); + return error.Inkling2WeightMap; +} + +/// config.json read and admitted (inkling2_loop, ModelOpt via core), the map checked, then layer by layer to the GPU. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8) !Weights { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const json = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(json); + var why: config.Why = .{}; + const c = config.parse(gpa, json, &why) catch |e| { + std.log.err("inkling2: {s}", .{why.text()}); + return e; + }; + if (c.text.loop == null) return error.Inkling2NotLooped; // Small serves on its own engine + var ck = try core.checkpoint.Checkpoint.openModel(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var prec: [config.max_layers]plan_.Precision = undefined; + try admit(gpa, &ck, &c, prec[0..c.text.layers]); + var w: Weights = .{ .gpa = gpa, .config = c, .plan = try plan_.build(&c.text, prec[0..c.text.layers]) }; + errdefer w.deinit(); + const t = &c.text; + w.layers = try gpa.alloc(Layer, t.layers); + w.embed = try raw(&w, d, &ck, "model.llm.embed.weight", .{}); + w.embed_norm = try raw(&w, d, &ck, "model.llm.embed_norm.weight", .{}); + w.norm = try raw(&w, d, &ck, "model.llm.norm.weight", .{}); + w.output_query = try raw(&w, d, &ck, "model.llm.attn_res.output_query", .{}); + w.cross_main = try raw(&w, d, &ck, "model.llm.middle_cycle_cross_pass_queries", .{}); + w.cross_kv = try raw(&w, d, &ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}); + w.unembed = try w.lane(d, try ck.get("model.llm.unembed.weight"), t.unpadded_vocab); + w.ones = try w.upload(d, std.mem.sliceAsBytes(&@as([64]f32, @splat(1.0)))); + for (w.layers, 0..) |*l, i| { + l.* = try layer(&w, d, &ck, @intCast(i), prec[i]); + ck.release(); // the mapped pages already copied: drop them from the page cache's working set + } + return w; +} + +fn layer(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, i: u32, prec: plan_.Precision) !Layer { + const c = &w.config.text; + const L = .{i}; + const global = config.isGlobal(i); + var a: Attn = .{ + .wq = try proj(w, d, ck, "model.llm.layers.{d}.attn.wq_du.weight", L), + .wk = try proj(w, d, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L), + .wv = try proj(w, d, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L), + .wr = try proj(w, d, ck, "model.llm.layers.{d}.attn.wr_du.weight", L), + .gate = try proj(w, d, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L), + .sink = try proj(w, d, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L), + .wo = try proj(w, d, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L), + .q_scale = try raw(w, d, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L), + .rel_scale = try raw(w, d, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L), + .rel_proj = try raw(w, d, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L), + .k_conv = undefined, + .v_conv = undefined, + .norms = undefined, + }; + if (global) { + a.k_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.static_w", L); + a.v_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.static_w", L); + a.k_taps = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.weight_proj", L); + a.v_taps = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.weight_proj", L); + a.norms = .{ + try raw(w, d, ck, "model.llm.layers.{d}.q_input_norm.weight", L), + try raw(w, d, ck, "model.llm.layers.{d}.k_input_norm.weight", L), + try raw(w, d, ck, "model.llm.layers.{d}.v_input_norm.weight", L), + }; + } else { + a.k_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.weight", L); + a.v_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.weight", L); + const n = try raw(w, d, ck, "model.llm.layers.{d}.attn_norm.weight", L); + a.norms = .{ n, n, n }; + } + var l: Layer = .{ + .attn = a, + .attn_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn_sconv.weight", L), + .mlp_conv = try raw(w, d, ck, "model.llm.layers.{d}.mlp_sconv.weight", L), + .mlp_norm = try raw(w, d, ck, "model.llm.layers.{d}.mlp_norm.weight", L), + .router = try raw(w, d, ck, "model.llm.layers.{d}.mlp.gate.weight", L), + .router_bias = try raw(w, d, ck, "model.llm.layers.{d}.mlp.gate.bias", L), + .mlp_query = try raw(w, d, ck, "model.llm.attn_res.mlp_queries.{d}", L), + .experts = try experts(w, d, ck, i, prec), + }; + // attn_queries.j feeds layer j + 1's attention input; layer 0 norms the embedding alone + if (i > 0) l.attn_query = try raw(w, d, ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}); + if (c.loop) |lp| if (i >= lp.start and i < lp.end) { + var cs: [4]Controller = undefined; + inline for (names.controllers, 0..) |g, k| cs[k] = .{ + .down = try raw(w, d, ck, "model.llm.layers.{d}.controllers." ++ g ++ ".down_weight", L), + .forget = try raw(w, d, ck, "model.llm.layers.{d}.controllers." ++ g ++ ".forget_weight", L), + .gain = try raw(w, d, ck, "model.llm.layers.{d}.controllers." ++ g ++ ".gain_weight", L), + }; + l.controllers = cs; + }; + return l; +} + +/// A layer's experts as stored, packed for core experts: w13's interleaved rows split into gate and up first. +fn experts(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, i: u32, prec: plan_.Precision) !ex.Layer { + const c = &w.config.text; + const e: usize = c.experts; + const h: usize = c.hidden; + const m: usize = c.expert_inter; + const nv = prec == .nvfp4; + const pre = "model.llm.layers.{d}.mlp.experts."; + const L = .{i}; + const w13 = try get(ck, pre ++ "w13_weight", L); + const s13 = try get(ck, pre ++ "w13_weight_scale", L); + const w2 = try get(ck, pre ++ "w2_weight", L); + const s2 = try get(ck, pre ++ "w2_weight_scale", L); + const up_words = (if (nv) ex.Nvfp4Experts.bytes(1, m, h, 2) else mx.Mxfp8Experts.bytes(1, m, h, 2)) / 4; + const down_words = (if (nv) ex.Nvfp4Experts.bytes(1, h, m, 1) else mx.Mxfp8Experts.bytes(1, h, m, 1)) / 4; + const up = try w.gpa.alloc(u32, e * up_words); + defer w.gpa.free(up); + const down = try w.gpa.alloc(u32, e * down_words); + defer w.gpa.free(down); + const cb = w13.bytes.len / e; + const sb = s13.bytes.len / e; + const split = try w.gpa.alloc(u8, cb + sb); + defer w.gpa.free(split); + const c2 = w2.bytes.len / e; + const sc2 = s2.bytes.len / e; + for (0..e) |x| { + mx.splitGateUp(w13.bytes[x * cb ..][0..cb], cb / (2 * m), split[0 .. cb / 2], split[cb / 2 .. cb]); + mx.splitGateUp(s13.bytes[x * sb ..][0..sb], sb / (2 * m), split[cb..][0 .. sb / 2], split[cb + sb / 2 ..][0 .. sb / 2]); + const gate = [2][]const u8{ split[0 .. cb / 2], split[cb..][0 .. sb / 2] }; + const upm = [2][]const u8{ split[cb / 2 .. cb], split[cb + sb / 2 ..][0 .. sb / 2] }; + const o = up[x * up_words ..][0..up_words]; + const dn = down[x * down_words ..][0..down_words]; + if (nv) { + ex.Nvfp4Experts.packGateUp(o, gate, upm, m, h); + ex.Nvfp4Experts.packOne(dn, w2.bytes[x * c2 ..][0..c2], s2.bytes[x * sc2 ..][0..sc2], h, m); + } else { + mx.Mxfp8Experts.packGateUp(o, gate, upm, m, h); + mx.Mxfp8Experts.packOne(dn, w2.bytes[x * c2 ..][0..c2], s2.bytes[x * sc2 ..][0..sc2], h, m); + } + } + var l: ex.Layer = .{ .format = if (nv) .nvfp4 else .mxfp8, .up = try w.upload(d, std.mem.sliceAsBytes(up)), .down = try w.upload(d, std.mem.sliceAsBytes(down)), .width = m, .dims = h, .experts = e, .caps = .{ c.gate_cap, c.up_cap } }; + if (nv) { + var f13 = try w.gpa.alloc(f32, 2 * e); + defer w.gpa.free(f13); + var f2 = try w.gpa.alloc(f32, e); + defer w.gpa.free(f2); + inline for (.{ "w13", "w2" }, 0..) |name, k| { + const amax = try get(ck, pre ++ name ++ "_weight_amax", L); + const den = std.mem.bytesToValue(f32, (try get(ck, pre ++ name ++ "_weight_outer_scale_denominator", L)).bytes[0..4]); + if (den != nvfp4_denominator) return error.Inkling2Nvfp4Denominator; + for (0..e) |x| { + const f = mx.nvfp4Factor(std.mem.bytesToValue(f32, amax.bytes[x * 4 ..][0..4]), den); + if (k == 0) { + f13[2 * x] = f; // one amax covers the gate and the up rows + f13[2 * x + 1] = f; + } else f2[x] = f; + } + } + l.up_scale = try w.upload(d, std.mem.sliceAsBytes(f13)); + l.down_scale = try w.upload(d, std.mem.sliceAsBytes(f2)); + } + return l; +} diff --git a/zig/tests/cuda/inkling2_mini_tests.zig b/zig/tests/cuda/inkling2_mini_tests.zig new file mode 100644 index 00000000000..0b28f0ce75e --- /dev/null +++ b/zig/tests/cuda/inkling2_mini_tests.zig @@ -0,0 +1,218 @@ +//! Inkling 2 Mini on the released checkpoint at one rank: greedy tokens, a prompt cut in chunks against one chunk +//! (resumed == fresh), and four streams decoding together against each alone (concurrent == solo). +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const Gpu = check.Gpu; + +const mm = ink.mini_model; + +pub const Rig = struct { + gpu: Gpu, + w: ink.mini_weights.Weights, + k: mm.Kernels, + s: cuda.Stream, + m: mm.Model, + + pub fn init(r: *Rig, gpu: Gpu, model: []const u8, context: usize, slots: usize) !void { + r.gpu = gpu; + r.w = try ink.mini_weights.load(gpu.gpa, gpu.io, gpu.d, model); + errdefer r.w.deinit(); + r.k = try mm.Kernels.load(gpu.ctx); + errdefer r.k.deinit(); + r.s = try cuda.Stream.init(gpu.d, false); + errdefer r.s.deinit(); + r.m = try mm.Model.init(gpu.gpa, gpu.d, r.s, &r.w, &r.k, context, slots); + } + + pub fn deinit(r: *Rig) void { + r.m.deinit(); + r.s.deinit(); + r.k.deinit(); + r.w.deinit(); + } + + fn vocab(r: *const Rig) usize { + return r.w.config.text.unpadded_vocab; + } + + /// The host copy of the logits of `heads` rows the last forward kept. + fn logits(r: *Rig, heads: usize) ![]f32 { + try r.s.synchronize(); + const out = try r.gpu.gpa.alloc(f32, heads * r.vocab()); + try (cuda.DeviceBuffer{ .d = r.gpu.d, .ptr = r.m.s.logits, .len = out.len * 4, .borrowed = true }).download(0, std.mem.sliceAsBytes(out)); + return out; + } + + /// A prompt into `slot` in chunks of `chunk` rows; the last row's logits. + pub fn prompt(r: *Rig, slot: usize, tokens: []const u32, p0: usize, chunk: usize) ![]f32 { + var at: usize = 0; + while (at < tokens.len) { + const n = @min(chunk, tokens.len - at); + const last = at + n == tokens.len; + try r.m.forward(&r.k, r.s, &.{.{ .slot = slot, .p0 = p0 + at, .tokens = tokens[at..][0..n] }}, true, if (last) n - 1 else 0, @intFromBool(last)); + at += n; + } + return r.logits(1); + } + + /// One decode row a stream, the streams in one forward: each row's logits. + pub fn step(r: *Rig, chains: []const mm.Chain) ![]f32 { + try r.m.forward(&r.k, r.s, chains, false, 0, chains.len); + return r.logits(chains.len); + } +}; + +pub fn argmax(x: []const f32) u32 { + var best: usize = 0; + for (x, 0..) |v, i| if (v > x[best]) { + best = i; + }; + return @intCast(best); +} + +fn ms(a: i96, b: i96) f64 { + return @as(f64, @floatFromInt(b - a)) / 1e6; +} + +/// Greedy tokens of `slot` from its prompt's logits, one decode row at a time. +fn decode(r: *Rig, slot: usize, first: []const f32, p0: usize, out: []u32) !void { + out[0] = argmax(first); + for (1..out.len) |i| { + const row = try r.step(&.{.{ .slot = slot, .p0 = p0 + i - 1, .tokens = out[i - 1 .. i] }}); + defer r.gpu.gpa.free(row); + out[i] = argmax(row); + } +} + +/// tf-cuda-test inkling2-mini DIR N TEXT: greedy, resumed == fresh, concurrent == solo, decode speed at 1 and 4. +pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8, text: []const u8) !void { + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(usize, count_text, 10); + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, model); + defer tok.deinit(); + const ids = try tok.encode(gpa, text); + defer gpa.free(ids); + var rig: Rig = undefined; + const t_load = check.now(gpu.io); + try rig.init(gpu, model, 4096, 4); + defer rig.deinit(); + std.debug.print("INFO inkling2 mini: {d} prompt tokens, {d:.2} GB of weights on the GPU, loaded in {d:.1} s\n", .{ ids.len, @as(f64, @floatFromInt(rig.w.bytes)) / 1e9, ms(t_load, check.now(gpu.io)) / 1e3 }); + const n0 = ids.len; + const t0 = check.now(gpu.io); + const first = try rig.prompt(0, ids, 0, mm.prompt_rows); + defer gpa.free(first); + const t1 = check.now(gpu.io); + const plain = try gpa.alloc(u32, count); + defer gpa.free(plain); + try decode(&rig, 0, first, n0, plain); + const t2 = check.now(gpu.io); + const said = try tok.decode(gpa, plain, false); + defer gpa.free(said); + std.debug.print("RESULT inkling2 mini greedy: {d} tokens, prompt {d:.1} ms, decode {d:.2} ms a token ({d:.1} tok/s): \"{s}\"\n", .{ count, ms(t0, t1), ms(t1, t2) / @as(f64, @floatFromInt(count - 1)), @as(f64, @floatFromInt(count - 1)) * 1e3 / ms(t1, t2), said }); + std.debug.print("RESULT inkling2 mini ids:", .{}); + for (plain) |t| std.debug.print(" {d}", .{t}); + std.debug.print("\n", .{}); + // resumed == fresh: the prompt in chunks (a prompt-cache hit resumes at a chunk edge), then the same greedy tokens + var bad: usize = 0; + for ([_]usize{ 1, 7, 64 }) |chunk| { + if (chunk >= n0) continue; + const again = try rig.prompt(1, ids, 0, chunk); + defer gpa.free(again); + const same = std.mem.eql(u8, std.mem.sliceAsBytes(again), std.mem.sliceAsBytes(first)); + const resumed = try gpa.alloc(u32, @min(count, 32)); + defer gpa.free(resumed); + try decode(&rig, 1, again, n0, resumed); + const tokens_same = std.mem.eql(u32, resumed, plain[0..resumed.len]); + if (!same or !tokens_same) bad += 1; + std.debug.print("{s} inkling2 mini prompt in chunks of {d}: last-row logits {s}, {d} greedy tokens {s}\n", .{ if (same and tokens_same) "PASS" else "FAIL", chunk, if (same) "bit-equal" else "differ", resumed.len, if (tokens_same) "equal" else "differ" }); + } + try check.expect(bad == 0, "inkling2 mini resumed == fresh: {d} chunkings differ", .{bad}); + try concurrent(&rig, ids, plain); +} + +/// Four streams at once (prompts of different lengths) against each alone: equal tokens; the round's decode speed. +fn concurrent(rig: *Rig, ids: []const u32, plain: []const u32) !void { + const gpa = rig.gpu.gpa; + const steps = @min(plain.len, 64); + var solo: [4][]u32 = undefined; + var lens: [4]usize = undefined; + var firsts: [4][]f32 = undefined; + for (0..4) |i| { + lens[i] = @max(1, ids.len - i * ids.len / 8); // prefixes of the prompt: different lengths and contexts + firsts[i] = try rig.prompt(i, ids[0..lens[i]], 0, mm.prompt_rows); + solo[i] = try gpa.alloc(u32, steps); + try decode(rig, i, firsts[i], lens[i], solo[i]); + } + defer for (0..4) |i| { + gpa.free(solo[i]); + gpa.free(firsts[i]); + }; + var together: [4][]u32 = undefined; + for (0..4) |i| { + gpa.free(try rig.prompt(i, ids[0..lens[i]], 0, mm.prompt_rows)); + together[i] = try gpa.alloc(u32, steps); + together[i][0] = argmax(firsts[i]); + } + defer for (together) |t| gpa.free(t); + const t0 = check.now(rig.gpu.io); + for (1..steps) |j| { + var chains: [4]mm.Chain = undefined; + for (0..4) |i| chains[i] = .{ .slot = i, .p0 = lens[i] + j - 1, .tokens = together[i][j - 1 .. j] }; + const rows = try rig.step(&chains); + defer gpa.free(rows); + for (0..4) |i| together[i][j] = argmax(rows[i * rig.vocab() ..][0..rig.vocab()]); + } + const t1 = check.now(rig.gpu.io); + var bad: usize = 0; + for (0..4) |i| { + if (!std.mem.eql(u32, together[i], solo[i])) bad += 1; + } + try check.expect(bad == 0, "inkling2 mini concurrent == solo: {d} of 4 streams' tokens differ", .{bad}); + const per = ms(t0, t1) / @as(f64, @floatFromInt(steps - 1)); + check.pass("inkling2 mini concurrent == solo: 4 streams x {d} greedy tokens equal; c=4 round {d:.2} ms ({d:.1} tok/s total)", .{ steps, per, 4e3 / per }); +} + +/// tf-cuda-test inkling2-mini-ref DIR N TEXT: N greedy tokens on the GPU, then the float64 reference teacher-forced +/// over the prompt and them: each generated token against the reference's pick, every difference with its margin. +pub fn reference(gpu: Gpu, model: []const u8, count_text: []const u8, text: []const u8) !void { + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(usize, count_text, 10); + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, model); + defer tok.deinit(); + const ids = try tok.encode(gpa, text); + defer gpa.free(ids); + var rig: Rig = undefined; + try rig.init(gpu, model, 4096, 1); + defer rig.deinit(); + const first = try rig.prompt(0, ids, 0, mm.prompt_rows); + defer gpa.free(first); + const all = try gpa.alloc(u32, ids.len + count); + defer gpa.free(all); + @memcpy(all[0..ids.len], ids); + try decode(&rig, 0, first, ids.len, all[ids.len..]); + var ck = try core.checkpoint.Checkpoint.openModel(gpa, gpu.io, model); + defer ck.close(); + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck }; + const picks = try gpa.alloc(ink.mini_ref.Pick, all.len); + defer gpa.free(picks); + const t0 = check.now(gpu.io); + try r.run(all[0 .. all.len - 1], picks[0 .. all.len - 1]); + std.debug.print("INFO inkling2 mini reference: {d} positions in {d:.1} s\n", .{ all.len - 1, ms(t0, check.now(gpu.io)) / 1e3 }); + var differ: usize = 0; + var smallest: f64 = std.math.inf(f64); + for (ids.len - 1..all.len - 1) |i| { + const want = picks[i]; + smallest = @min(smallest, want.margin); + if (want.id != all[i + 1]) { + differ += 1; + std.debug.print("DIFF inkling2 mini position {d}: GPU {d}, reference {d} (reference margin {d:.4})\n", .{ i + 1, all[i + 1], want.id, want.margin }); + } + } + const said = try tok.decode(gpa, all[ids.len..], false); + defer gpa.free(said); + std.debug.print("RESULT inkling2 mini vs float64 reference: {d} of {d} greedy tokens differ, smallest reference margin {d:.4}: \"{s}\"\n", .{ differ, count, smallest, said }); + try check.expect(differ == 0, "inkling2 mini greedy == reference: {d} of {d} tokens differ", .{ differ, count }); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index d6269d02cef..5c7959dacb6 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -235,6 +235,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "nvfp4-experts")) return nvfp4_experts_tests.experts(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "bf16-experts")) return if (rest.len == 0) @import("bf16_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_bf16.zig").run(gpu) else error.UnknownCommand; if (std.mem.eql(u8, cmd, "stored-experts")) return storedExperts(gpu, rest); + if (std.mem.eql(u8, cmd, "inkling2-mini-ref")) return @import("inkling2_mini_tests.zig").reference(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "inkling2-mini")) return @import("inkling2_mini_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "projection-f32")) return projection_f32_tests.run(gpu); if (std.mem.eql(u8, cmd, "mxfp8")) return mxfp8_tests.run(gpu); if (std.mem.eql(u8, cmd, "quant-ref")) return quant_ref_tests.run(gpu); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index e94d0b16d51..d458cc2de3e 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -94,6 +94,8 @@ pub const usage = \\ nvfp4-experts grouped NVFP4 experts against recorded fixture bytes \\ bf16-experts [contract] grouped bf16 experts against float64 (repack, up, downs, rows, forms); contract: gates 1-4, controls red \\ stored-experts contract | ckpt DIR | bench DIR Inkling 2 Mini's NVFP4 and MXFP8 experts: gates, checkpoint, speed + \\ inkling2-mini DIR N TEXT Inkling 2 Mini at one rank: N greedy tokens, resumed == fresh, concurrent == solo + \\ inkling2-mini-ref DIR N TEXT Inkling 2 Mini's N greedy tokens against the float64 reference, teacher-forced \\ projection-f32 FP32 projection outputs against FP64, rounding and row/reduction invariance \\ mxfp8 MXFP8 strided projections against FP64 and row-count invariance \\ quant-ref FP8 and NVFP4 projections and experts against float64 references (synthetic) From 332e966acf1254f7a21692780513fda58d8d7545 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:15:53 +0100 Subject: [PATCH 07/84] inkling2: Mini behind lanes.Backend and the native CUDA registry (C4b): inkling2_loop, text only Each stream gets a cache slot of 48 visit slots. A prompt takes one 512-row chunk a step. A round runs one-row windows over every stream in a single forward. It offers no drafts and no copies: a conv state has no rollback here. Refused by name before any load: --loops (the pass count comes from loop_config), a drafter (C5) and captured kernels. A prompt holding the image token is refused (C6). Streams are fitted to the room at open, as in Dory. --- zig/build/cuda_engines.zig | 1 + zig/src/families/inkling2/inkling2.zig | 5 + zig/src/families/inkling2/mini_backend.zig | 364 +++++++++++++++++++++ zig/src/families/inkling2/mini_native.zig | 195 +++++++++++ zig/src/native/cuda_families.zig | 2 +- 5 files changed, 566 insertions(+), 1 deletion(-) create mode 100644 zig/src/families/inkling2/mini_backend.zig create mode 100644 zig/src/families/inkling2/mini_native.zig diff --git a/zig/build/cuda_engines.zig b/zig/build/cuda_engines.zig index 62081da2cbc..44a8cf05505 100644 --- a/zig/build/cuda_engines.zig +++ b/zig/build/cuda_engines.zig @@ -87,6 +87,7 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .{ .name = "spark25", .module = @import("spark25.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "lfm2_moe_cuda", .module = @import("lfm2_moe_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "dory", .module = @import("dory.zig").module(b, target, optimize, cuda, core, lanes) }, + .{ .name = "inkling2", .module = @import("inkling2.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "dots_mocr_cuda", .module = @import("dots_mocr_cuda.zig").module(b, target, optimize, cuda, core, lanes, @import("cuda_dense.zig").module(b, target, optimize, cuda, core, lanes)) }, .{ .name = "muse_spark", .module = @import("muse.zig").moduleOver(b, target, optimize, cuda, core, lanes, @import("tp.zig").moduleWith(b, target, optimize, cuda, verbs)) }, }, diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 41f23e45c22..406229b020b 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -9,8 +9,11 @@ pub const names = @import("names.zig"); pub const loop = @import("loop.zig"); pub const mini_weights = @import("mini_weights.zig"); pub const mini_model = @import("mini_model.zig"); +pub const mini_backend = @import("mini_backend.zig"); /// The float64 reference the CUDA forward's greedy tokens are checked against. pub const mini_ref = @import("mini_ref.zig"); +/// The native CUDA registry's entry for inkling2_loop (native/cuda_families.zig). +pub const native = @import("mini_native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -24,5 +27,7 @@ test { _ = mini_model; _ = @import("mini_visit.zig"); _ = mini_weights; + _ = mini_backend; _ = mini_ref; + _ = native; } diff --git a/zig/src/families/inkling2/mini_backend.zig b/zig/src/families/inkling2/mini_backend.zig new file mode 100644 index 00000000000..f1ab895e3e6 --- /dev/null +++ b/zig/src/families/inkling2/mini_backend.zig @@ -0,0 +1,364 @@ +//! Inkling 2 Mini behind lanes.Backend: a cache slot a stream (48 visit slots), a prompt chunk a step, one forward +//! a round of one-row windows over every stream. No draft head yet (C5) and no copy drafts: a conv state has no +//! rollback here, so every window keeps all its rows. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const mm = @import("mini_model.zig"); + +const be = lanes.backend; +const Stream = lanes.Stream; + +/// Prompt rows a step takes. +pub const prompt_rows = mm.prompt_rows; +/// Window rows a round takes over every stream. +pub const round_rows = mm.round_rows; +/// Drawn tokens a handle names (a ring; read before the round loop could wrap it). +const ring = 1024; + +/// The serving launches beside the forward: argmax, bf16 logits and sample.cu's keyed draws. +pub const Draws = struct { + mods: [3]cuda.Module, + argmax_fn: cuda.Function, + to_bf16_fn: cuda.Function, + draws: cuda.sample.Draws, + + pub fn load(d: *const cuda.Driver) !Draws { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const kk = cuda.kernels; + var x: Draws = undefined; + var loaded: usize = 0; + errdefer for (x.mods[0..loaded]) |*m| m.unload(); + for ([_][]const u8{ kk.sample, kk.torch_argmax, kk.torch_pointwise }, 0..) |img, i| { + x.mods[i] = try cuda.Module.load(d, img); + loaded += 1; + } + x.draws = try cuda.sample.Draws.resolve(x.mods[0]); + x.argmax_fn = try x.mods[1].function("tf_argmax_rows_i32_kernel"); + x.to_bf16_fn = try x.mods[2].function("tf_f32_to_bf16_kernel"); + return x; + } + + pub fn deinit(x: *Draws) void { + for (&x.mods) |*m| m.unload(); + } + + /// Each row's argmax over `v` fp32 logits, the first maximum on ties, into `out` (int32 a row). + fn argmax(x: *const Draws, s: cuda.Stream, logits: u64, rows: usize, v: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(out); + for ([_]usize{ rows, v, v }) |n| a.add(@as(i64, @intCast(n))); + a.add(@as(i32, 1)); // dtype 1: fp32 + try cuda.launch.launch(x.argmax_fn, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 1024 } }, s, &a); + } + + fn toBf16(x: *const Draws, s: cuda.Stream, src: u64, dst: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(dst); + a.add(@as(u64, n)); + const grid: u32 = @intCast(@max(1, @min((n + 255) / 256, 65535))); + try cuda.launch.launch(x.to_bf16_fn, .{ .grid = .{ .x = grid }, .block = .{ .x = 256 } }, s, &a); + } +}; + +const Lane = struct { + slot: usize, + len: u64 = 0, // positions [0, len) hold this stream's keys and its conv states are at len + base: u64 = 0, // the length the last verify started from + rows: std.ArrayList(u32) = .empty, // the last verify's row tokens + last: u64, // the prompt's last row's fp32 logits (the first draw reads them) + rule: u64, // sample.cu's Rule, when the stream samples + sampled: bool = false, + fill: ?usize = null, // a prompt pass going a chunk at a time: where its next chunk starts +}; + +/// The positions a slot holds for a served window, in whole 1,024s. +pub fn capacity(window: usize) !usize { + if (window == 0) return error.BadContext; + return (try std.math.add(usize, window, 1023)) / 1024 * 1024; +} + +/// A prompt and its reply fit `physical` positions. +pub fn fits(physical: usize, prompt: usize, reply: usize) bool { + return prompt <= physical and reply <= physical - prompt; +} + +pub const Mini = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + m: *mm.Model, + k: *const mm.Kernels, + x: *const Draws, + s: cuda.Stream, + image_token: u32, + lanes: std.AutoHashMapUnmanaged(*const Stream, Lane) = .empty, + free: []bool, // slot i is free + logits16: cuda.DeviceBuffer, // a round's logits as bf16 for keyed draws + tok: cuda.DeviceBuffer, // drawn tokens: the handle ring, then a round's rows + meta: cuda.DeviceBuffer, // a draw's first position minus one, a window each + slot_bufs: []cuda.DeviceBuffer, // a slot's last-row logits, then its rule: two a slot + next: u64 = 0, + + fn vocab(x: *const Mini) usize { + return x.m.c.unpadded_vocab; + } + + /// The device bytes `init` allocates: bf16 logits, the token ring, metas, each slot's last row and rule. + pub fn openBytes(vocab_: usize, slots: usize) usize { + return round_rows * vocab_ * 2 + (ring + round_rows) * 4 + round_rows * 16 + slots * (vocab_ * 4 + @sizeOf(cuda.sample.Rule)); + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *mm.Model, k: *const mm.Kernels, x: *const Draws, s: cuda.Stream, image_token: u32) !Mini { + const v = m.c.unpadded_vocab; + const free = try gpa.alloc(bool, m.slots); + errdefer gpa.free(free); + @memset(free, true); + var logits16 = try cuda.DeviceBuffer.alloc(d, round_rows * v * 2); + errdefer logits16.free(); + var tok = try cuda.DeviceBuffer.alloc(d, (ring + round_rows) * 4); + errdefer tok.free(); + var meta = try cuda.DeviceBuffer.alloc(d, round_rows * 16); + errdefer meta.free(); + const bufs = try gpa.alloc(cuda.DeviceBuffer, 2 * m.slots); + errdefer gpa.free(bufs); + var made: usize = 0; + errdefer for (bufs[0..made]) |*b| b.free(); + for (bufs, 0..) |*b, i| { + b.* = try cuda.DeviceBuffer.alloc(d, if (i % 2 == 0) v * 4 else @sizeOf(cuda.sample.Rule)); + made += 1; + } + return .{ .gpa = gpa, .d = d, .m = m, .k = k, .x = x, .s = s, .image_token = image_token, .free = free, .logits16 = logits16, .tok = tok, .meta = meta, .slot_bufs = bufs }; + } + + pub fn deinit(x: *Mini) void { + var it = x.lanes.valueIterator(); + while (it.next()) |l| l.rows.deinit(x.gpa); + x.lanes.deinit(x.gpa); + for (x.slot_bufs) |*b| b.free(); + x.gpa.free(x.slot_bufs); + x.gpa.free(x.free); + x.logits16.free(); + x.tok.free(); + x.meta.free(); + } + + pub fn backend(x: *Mini) be.Backend { + return .{ .ptr = x, .vtable = &vtable }; + } + + const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true }; + + /// The round loop's facts: no draft head and no copies; one-row windows, streams sharing a forward. + pub fn facts(x: *const Mini) lanes.Model { + return .{ .copy_drafts = false, .exact_width = 1, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .plain_share = true, .batch_rows = round_rows, .max_streams = @intCast(@min(x.m.slots, round_rows)) }; + } + + fn self(ptr: *anyopaque) *Mini { + return @ptrCast(@alignCast(ptr)); + } + + fn upload(x: *Mini, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(x.d, dst, bytes, x.s); + } + + /// Rows [row0, row0 + rows) of fp32 `logits` drawn into tok[at..], row r at `position0 + r` (argmax when greedy). + fn drawRows(x: *Mini, l: *const Lane, logits: u64, row0: usize, rows: usize, position0: u64, at: usize, meta_at: usize) !void { + const v = x.vocab(); + const src = logits + row0 * v * 4; + if (!l.sampled) return x.x.argmax(x.s, src, rows, v, x.tok.ptr + at * 4); + try x.x.toBf16(x.s, src, x.logits16.ptr, rows * v); + const meta = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; + const mp = x.meta.ptr + meta_at * 16; + try x.upload(mp, std.mem.asBytes(&meta)); + try x.x.draws.draw(x.s, x.logits16.ptr, v, l.rule, mp, 0, x.tok.ptr + at * 4, rows, null, null); + } + + fn freeSlot(x: *const Mini) ?usize { + return std.mem.indexOfScalar(bool, x.free, true); + } + + /// Whether a request could start now: a free slot; one that never fits passes (its open refuses it). + pub fn admits(x: *const Mini, prompt: usize, max_new: usize) bool { + if (!fits(x.m.context, prompt, max_new)) return true; + return x.freeSlot() != null; + } + + /// A prompt pass begins: a slot and the stream's rule; images are refused by name until the vision slice (C6). + fn opening(x: *Mini, s: *Stream) !*Lane { + const p = s.prompt(); + if (p.len == 0) return error.EmptyPrompt; + if (std.mem.indexOfScalar(u32, p, x.image_token) != null) return error.Inkling2MiniImages; + if (!fits(x.m.context, p.len, @as(usize, s.max_new))) return error.PastContext; + const got = try x.lanes.getOrPut(x.gpa, s); + if (!got.found_existing) { + const slot = x.freeSlot() orelse { + x.lanes.removeByPtr(got.key_ptr); + return error.NoFreeSlot; + }; + got.value_ptr.* = .{ .slot = slot, .last = x.slot_bufs[2 * slot].ptr, .rule = x.slot_bufs[2 * slot + 1].ptr }; + x.free[slot] = false; + } + const l = got.value_ptr; + l.sampled = false; + if (cuda.sample.ruleFor(s.sampling)) |r| { + try x.upload(l.rule, std.mem.asBytes(&r)); + l.sampled = true; + } + s.cached = 0; + l.fill = 0; + s.fill_at.store(0, .monotonic); + return l; + } + + /// One chunk from `l.fill`; true once the prompt's last row is in. + fn chunk(x: *Mini, s: *Stream, l: *Lane) !bool { + const p = s.prompt(); + const at = l.fill.?; + if (s.isCancelled()) return error.Cancelled; + const end = @min(p.len, (at / prompt_rows + 1) * prompt_rows); + const done = end == p.len; + try x.m.forward(x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..end] }}, true, end - at - 1, @intFromBool(done)); + if (done) try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.s.logits, x.vocab() * 4, x.s.handle), "cuMemcpyDtoDAsync"); + s.fill_at.store(@intCast(end), .monotonic); + l.fill = if (done) null else end; + if (done) l.len = p.len; + return done; + } + + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + const x = self(ptr); + const l = try x.opening(s); + errdefer x.dropLane(s); + while (!try x.chunk(s, l)) {} + } + + fn prefillStep(ptr: *anyopaque, s: *Stream, _: u32) anyerror!bool { + const x = self(ptr); + const going = if (x.lanes.getPtr(s)) |l| l.fill != null else false; + const l = if (going) x.lanes.getPtr(s).? else try x.opening(s); + errdefer x.dropLane(s); + return x.chunk(s, l); + } + + fn handle(x: *Mini) usize { + const h = x.next; + x.next += 1; + return @intCast(h % ring); + } + + fn first(ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64 { + const x = self(ptr); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + if (position != l.len or l.fill != null) return error.PositionMismatch; + const h = x.next; + try x.drawRows(l, l.last, 0, 1, position, x.handle(), 0); + return h; + } + + fn value(x: *Mini, feed: be.Feed) !u32 { + return switch (feed) { + .value => |v| v, + .handle => |h| read(x, h), + }; + } + + fn queue(ptr: *anyopaque, s: *Stream, feed: be.Feed, position: u64) anyerror!u64 { + const x = self(ptr); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + const t = try x.value(feed); + if (position != l.len + 1) return error.PositionMismatch; + try x.m.forward(x.k, x.s, &.{.{ .slot = l.slot, .p0 = l.len, .tokens = &.{t} }}, false, 0, 1); + l.len += 1; + const h = x.next; + try x.drawRows(l, x.m.s.logits, 0, 1, position, x.handle(), 0); + return h; + } + + fn read(ptr: *anyopaque, h: u64) anyerror!u32 { + const x = self(ptr); + if (h >= x.next or x.next - h > ring) return error.NoSuchToken; + var out: [1]u32 = undefined; + try x.s.synchronize(); + try x.tok.download(@intCast((h % ring) * 4), std.mem.sliceAsBytes(&out)); + return out[0]; + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const x = self(ptr); + const chains = try x.gpa.alloc(mm.Chain, windows.len); + defer x.gpa.free(chains); + var total: usize = 0; + for (windows, chains) |w, *c| { + if (w.held != 0) return error.NoHeldDrafts; // no draft head + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = x.lanes.getPtr(w.stream) orelse return error.UnknownStream; + if (w.rows() > mm.window_rows) return error.WindowTooWide; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(x.gpa, w.pending); + try l.rows.appendSlice(x.gpa, w.tokens); + for (w.positions, 0..) |pos, r| if (pos != l.base + r + 1) return error.PositionMismatch; + c.* = .{ .slot = l.slot, .p0 = l.base, .tokens = l.rows.items }; + total += l.rows.items.len; + } + if (total > round_rows) return error.RoundTooWide; + try x.m.forward(x.k, x.s, chains, false, 0, total); + var at: usize = 0; + for (windows, 0..) |w, i| { + const l = x.lanes.getPtr(w.stream).?; + try x.drawRows(l, x.m.s.logits, at, l.rows.items.len, w.positions[0], ring + at, i); + at += l.rows.items.len; + } + var got: [round_rows]u32 = undefined; + try x.s.synchronize(); + try x.tok.download(ring * 4, std.mem.sliceAsBytes(got[0..total])); + at = 0; + for (windows, out) |w, o| { + const l = x.lanes.getPtr(w.stream).?; + const n = l.rows.items.len; + @memcpy(o.sampled[0..n], got[at..][0..n]); + @memcpy(o.drafts[0 .. n - 1], l.rows.items[1..]); + l.len = l.base + n; + at += n; + } + } + + /// Every window keeps all its rows: the conv states hold no history to roll back to (no drafts are offered). + fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const x = self(ptr); + for (windows, paths) |w, path| { + const l = x.lanes.getPtr(w.stream) orelse return error.UnknownStream; + if (path.len != l.rows.items.len) return error.Inkling2MiniNoRollback; + for (path, 0..) |r, i| if (r != i) return error.ChainsOnly; + } + } + + /// No draft head: absorbing is a no-op, and a request for drafts is refused by name. + fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; + } + + fn dropLane(x: *Mini, s: *const Stream) void { + if (x.lanes.fetchRemove(s)) |entry| { + var l = entry.value; + x.free[l.slot] = true; + l.rows.deinit(x.gpa); + } + } + + fn release(ptr: *anyopaque, s: *Stream) void { + self(ptr).dropLane(s); + } +}; + +test "a slot holds the window in whole 1,024s; a reply past it does not fit" { + try std.testing.expectEqual(@as(usize, 32768), try capacity(32768)); + try std.testing.expectEqual(@as(usize, 1024), try capacity(1000)); + try std.testing.expectError(error.BadContext, capacity(0)); + try std.testing.expect(fits(32768, 30000, 2768)); + try std.testing.expect(!fits(32768, 30000, 2769)); + try std.testing.expect(!fits(32768, 32769, 0)); +} diff --git a/zig/src/families/inkling2/mini_native.zig b/zig/src/families/inkling2/mini_native.zig new file mode 100644 index 00000000000..820113bea69 --- /dev/null +++ b/zig/src/families/inkling2/mini_native.zig @@ -0,0 +1,195 @@ +//! Inkling 2 Mini (inkling2_loop) behind the native CUDA registry (native/cuda.zig): one rank, text only, plain +//! decode. Images (C6), a drafter (C5) and --loops are refused by name before any weight is read. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const wts = @import("mini_weights.zig"); +const mm = @import("mini_model.zig"); +const be = @import("mini_backend.zig"); + +pub const model_type = "inkling2_loop"; +pub const formats: []const []const u8 = &.{"modelopt-nvfp4"}; +pub const default_context: i64 = 32768; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = be.prompt_rows; +pub const takes_drafter = false; +pub const drafter_refusal = "--drafter: Inkling 2 Mini on CUDA serves plain decode so far; its DSpark drafter is the next slice (C5)"; +pub const explains_open = true; + +/// The server's reading of the room left after the weights; null if unreadable. +pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; +/// `loops` is here to refuse it by name: the pass count is the checkpoint's loop_config. +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 4, lanes_fixed: bool = false, room: ?Room = null, loops: ?u32 = null }; + +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + target: *be.Mini, +}; + +const Owned = struct { gpa: std.mem.Allocator, w: wts.Weights, k: mm.Kernels, x: be.Draws, s: cuda.Stream, m: mm.Model, b: be.Mini }; + +/// Streams to allocate in `room`: as asked, else (auto) the most that fit; a fixed count past them refuses. +fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { + const most = be.round_rows; + if (fixed and asked > most) return error.ParallelPastRound; + var n = std.math.clamp(@as(usize, asked), 1, most); + while (try plan.bytes(n) > room) : (n -= 1) { + if (fixed) return error.ParallelPastMemory; + if (n == 1) return error.NoStreamFits; + } + return n; +} + +const Plan = struct { + own: *const Owned, + d: *const cuda.Driver, + context: usize, + + fn bytes(p: Plan, n: usize) !u64 { + const o = p.own; + return try mm.Model.openBytes(o.gpa, p.d, o.s, &o.w, &o.k, p.context, n) + be.Mini.openBytes(o.w.config.text.unpadded_vocab, n); + } +}; + +/// What open refuses before any weight is read: --loops, a drafter, captured kernels. +fn refuse(kernels: ?[]const u8, o: Options) !void { + if (o.loops != null) return error.Inkling2MiniLoopsFixed; + if (o.drafts) return error.NoDraftHead; + if (kernels != null) return error.CapturedKernels; + if (o.lanes_fixed and o.lanes > be.round_rows) return error.ParallelPastRound; +} + +/// The checkpoint, the kernels and every stream's caches. +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + try refuse(kernels, o); + const context = try be.capacity(o.context); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + own.gpa = gpa; + own.w = try wts.load(gpa, io, ctx.d, dir); + errdefer own.w.deinit(); + if (context > own.w.config.text.max_context) return error.PastContext; + own.k = try mm.Kernels.load(ctx); + errdefer own.k.deinit(); + own.x = try be.Draws.load(ctx.d); + errdefer own.x.deinit(); + own.s = try cuda.Stream.init(ctx.d, false); + errdefer own.s.deinit(); + const plan: Plan = .{ .own = own, .d = ctx.d, .context = context }; + const room: u64 = if (o.room) |r| r.read(r.ctx) orelse 0 else std.math.maxInt(u64); + const n = fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { + if (e == error.ParallelPastMemory) { + const most = fit(room, o.lanes, false, plan) catch 0; + std.log.err("--parallel {d} needs {d:.2} GiB at a {d}-token window, and the CUDA memory budget leaves {d:.2} GiB after the weights: {d} stream{s} fit", .{ o.lanes, gib(try plan.bytes(o.lanes)), context, gib(room), most, if (most == 1) "" else "s" }); + } + return e; + }; + own.m = try mm.Model.init(gpa, ctx.d, own.s, &own.w, &own.k, context, n); + errdefer own.m.deinit(); + own.b = try be.Mini.init(gpa, ctx.d, &own.m, &own.k, &own.x, own.s, own.w.config.image_token); + std.log.info("Inkling 2 Mini: {d} visits a token ({d} sliding, {d} full, {d} conv slots a stream), {d} streams of {d} positions, {d:.2} GiB of weights", .{ own.w.plan.visits.len, own.w.plan.visits.count(.sliding), own.w.plan.visits.count(.full), own.w.plan.visits.count(.conv), n, context, gib(own.w.bytes) }); + return .{ + .backend = own.b.backend(), + .facts = own.b.facts(), + .rows = 1, + .stream_bytes = own.m.streamBytes(), + .free_streams = @intCast(n), + .ctx = own, + .deinit = release, + .target = &own.b, + }; +} + +/// Whether a request's caches could start now (the lane host's admission, on its engine thread). +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const own: *const Owned = @ptrCast(@alignCast(p)); + return own.b.admits(prompt, max_tokens); +} + +fn gib(b: u64) f64 { + return @as(f64, @floatFromInt(b)) / (1 << 30); +} + +/// A request or load this engine refuses, in words; null: none of its own. +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.Inkling2MiniLoopsFixed => "--loops: Inkling 2 Mini runs the passes its loop_config names (3 over layers 6 to 17); serve without --loops", + error.Inkling2MiniImages => "images: Inkling 2 Mini on CUDA reads text only until its vision slice (C6) lands; send text parts only", + error.Inkling2MiniNoRollback => "Inkling 2 Mini on CUDA keeps every verified row (no drafts are offered to roll back)", + error.Inkling2NotLooped => "Inkling 2 Small (model_type inkling2) has no CUDA engine yet: this one serves inkling2_loop", + error.Inkling2WeightMap => "the checkpoint's tensors differ from what its config.json implies (the log names each one)", + error.Inkling2Nvfp4Denominator => "an NVFP4 expert's outer_scale_denominator is not 2688, the one the checkpoint's factors are checked against", + error.PastContext => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", + error.NoFreeSlot => "every stream's caches are in use: retry once another request ends", + error.NoDraftHead => "Inkling 2 Mini on CUDA has no drafter yet (C5): serve without --drafter or drafts", + error.StructuresUnsupported => "structured output is not built for Inkling 2 Mini on CUDA yet", + error.CapturedKernels => "Inkling 2 Mini runs on the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", + error.BuiltWithoutKernels => "this build carries no CUDA kernel images: build with -Dnvcc", + error.ParallelPastRound => std.fmt.comptimePrint("--parallel: Inkling 2 Mini on CUDA holds at most {d} streams (a round's rows)", .{be.round_rows}), + error.ParallelPastMemory => "--parallel: the CUDA memory budget fits fewer Inkling 2 Mini streams than asked (each stream's 48 visit slots are allocated at load): lower --parallel or --context, or serve --parallel auto", + error.NoStreamFits => "the CUDA memory budget fits no Inkling 2 Mini stream after the weights: lower --context or free device memory", + else => null, + }; +} + +fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.b.deinit(); + own.m.deinit(); + own.s.deinit(); + own.x.deinit(); + own.k.deinit(); + own.w.deinit(); + own.gpa.destroy(own); +} + +test "Inkling 2 Mini open: --loops, a drafter and captured kernels are refused by name before any load" { + const base: Options = .{ .context = 4096, .drafts = false }; + try refuse(null, base); + var o = base; + o.loops = 3; + try std.testing.expectError(error.Inkling2MiniLoopsFixed, refuse(null, o)); + o = base; + o.drafts = true; + try std.testing.expectError(error.NoDraftHead, refuse(null, o)); + try std.testing.expectError(error.CapturedKernels, refuse("dir", base)); + // open refuses before it allocates: a failing allocator sees no request + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); + var d: cuda.Driver = undefined; + const ctx: cuda.Context = .{ .d = &d, .handle = undefined, .device = 0 }; + o = base; + o.loops = 2; + try std.testing.expectError(error.Inkling2MiniLoopsFixed, open(failing.allocator(), std.testing.io, &ctx, "/nonexistent", null, o)); + try std.testing.expectEqual(@as(usize, 0), failing.allocations); +} + +test "every refusal of its own is worded, the rest left to the server" { + for ([_]anyerror{ error.Inkling2MiniLoopsFixed, error.Inkling2MiniImages, error.Inkling2MiniNoRollback, error.Inkling2NotLooped, error.Inkling2WeightMap, error.Inkling2Nvfp4Denominator, error.PastContext, error.NoFreeSlot, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.ParallelPastRound, error.ParallelPastMemory, error.NoStreamFits }) |e| { + try std.testing.expect(explain(null, e) != null); + } + try std.testing.expect(explain(null, error.OutOfMemory) == null); +} + +/// A synthetic plan: `stream` bytes a stream plus `fixed` bytes of scratch. +const Fake = struct { + stream: u64, + fixed: u64, + fn bytes(f: Fake, n: usize) !u64 { + return f.fixed + n * f.stream; + } +}; + +test "the streams allocated at open fit the room: auto takes what fits, a fixed count refuses" { + const g: u64 = 1 << 30; + const one: Fake = .{ .stream = g, .fixed = 0 }; + try std.testing.expectEqual(@as(usize, 2), try fit(2 * g, 8, false, one)); + try std.testing.expectError(error.ParallelPastMemory, fit(2 * g, 8, true, one)); + try std.testing.expectError(error.NoStreamFits, fit(g - 1, 8, false, one)); + try std.testing.expectError(error.ParallelPastRound, fit(1024 * g, 65, true, one)); +} diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index db2d88035e8..8c6e2efc1de 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -14,7 +14,7 @@ const dory = @import("dory"); const qwen3 = @import("qwen3_cuda"); /// CUDA families provide metadata, open their lane backend and explain their refusals. -pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native }; +pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("inkling2").native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native }; pub const families: []const api.Family = blk: { var out: [registry.len + 5]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats, .decision_formats = if (@hasDecl(F, "decision_formats")) F.decision_formats else &.{} }; From b15dd116b053788dae6cc4667dca1d78cd519cd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:05:18 +0100 Subject: [PATCH 08/84] inkling2: Mini decode speed (C4c): graphs, fused input projections, gates spread over the GPU - Decode forwards of n one-row windows replay as CUDA graphs keyed by n. - A one-row forward runs q, gate, rel, sink (and k, v when they share the input) as one product. It uses a single packed buffer per layer, with views pinned to the parts' own K slices, so the bits are unchanged. - Before this, the loop gates ran on 1-3 blocks at decode, about 35% of GPU time. They now spread over rank and output blocks. Each output keeps its summation order. Greedy ids on the real checkpoint are identical to C4a. c=1 is 22 -> 33 tok/s, c=4 63 -> 79 tok/s. The server's default drafts flag is no longer refused: there is no head, so nothing is drafted. The tiny checkpoint's 128-wide rel_logits_proj is zero-padded to the kernels' 1024. Mini's is uploaded as stored. tf-cuda-test inkling2-mini-xcheck compares top-2 logits against #4337's Metal forward on prompts teacher-forced on another engine's tokens. --- zig/kernels/cuda/inkling2/loop.cu | 61 ++++++---- zig/src/families/inkling2/loop.zig | 18 ++- zig/src/families/inkling2/mini_model.zig | 37 +++++- zig/src/families/inkling2/mini_native.zig | 10 +- zig/src/families/inkling2/mini_ref.zig | 25 ++-- zig/src/families/inkling2/mini_visit.zig | 46 +++++-- zig/src/families/inkling2/mini_weights.zig | 105 ++++++++++++++-- zig/tests/cuda/inkling2_mini_tests.zig | 29 ++++- zig/tests/cuda/inkling2_mini_xcheck.zig | 133 +++++++++++++++++++++ zig/tests/cuda/main.zig | 1 + zig/tests/cuda/main_usage.zig | 1 + 11 files changed, 399 insertions(+), 67 deletions(-) create mode 100644 zig/tests/cuda/inkling2_mini_xcheck.zig diff --git a/zig/kernels/cuda/inkling2/loop.cu b/zig/kernels/cuda/inkling2/loop.cu index a0c992f928f..09cdb8ddbfa 100644 --- a/zig/kernels/cuda/inkling2/loop.cu +++ b/zig/kernels/cuda/inkling2/loop.cu @@ -111,9 +111,11 @@ struct LoopGateArgs { long long out_stride; int rows, H, rank; float eps_unit, eps; // eps_unit: the unweighted norms of state and message; eps: the gated output's norm + float* ys; // fp32 [gates][rows, H]: the gated rows before their norm }; -// down[g][row] = bf16(W_down [unit(h) bf16, unit(m) bf16]) for gate blockIdx.y of row blockIdx.x. +// down[g][row] = bf16(W_down [unit(h) bf16, unit(m) bf16]) for gate blockIdx.y of row blockIdx.x; block z takes +// rank rows [8 z, 8 z + 8), one a warp. Every block forms the same norms in the same order. extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_down(const LoopGateArgs a) { extern __shared__ float xs[]; // [2 H]: the normed state, then the normed message, each rounded to bf16 __shared__ float sh[kWarps]; @@ -134,39 +136,46 @@ extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_down(co } __syncthreads(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; - for (int r = w; r < a.rank; r += kWarps) { - const uint16_t* wr = a.down_w[g] + static_cast(r) * 2 * H; - float acc = 0.0f; - for (int i = lane; i < 2 * H; i += 32) acc = fmaf(bf(wr[i]), xs[i], acc); - acc = warpSum(acc); - if (lane == 0) a.down[(static_cast(g) * a.rows + row) * a.rank + r] = tobf(acc); - } + const int r = blockIdx.z * kWarps + w; + if (r >= a.rank) return; + const uint16_t* wr = a.down_w[g] + static_cast(r) * 2 * H; + float acc = 0.0f; + for (int i = lane; i < 2 * H; i += 32) acc = fmaf(bf(wr[i]), xs[i], acc); + acc = warpSum(acc); + if (lane == 0) a.down[(static_cast(g) * a.rows + row) * a.rank + r] = tobf(acc); } -// out[g][row] = norm * rms((1 - tanh(Wf d)) h + tanh(Wg d) m), d the gate's bf16 down row. -extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_mix(const LoopGateArgs a) { - extern __shared__ float ys[]; // [H]: the gated row before its norm - __shared__ float sh[kWarps]; +// ys[g][row][i] = (1 - tanh(Wf d)) h + tanh(Wg d) m, d the gate's bf16 down row: kLin outputs a block (z). +constexpr int kLin = 128; +extern "C" __global__ void __launch_bounds__(kLin) tf_ink2_loop_gate_lin(const LoopGateArgs a) { __shared__ float dn[kMaxRank]; const size_t row = blockIdx.x; const int g = blockIdx.y, H = a.H, R = a.rank; - const float* h = a.h[g] + row * H; - const float* m = a.msg + a.slot[g] * a.msg_stride + row * H; if (threadIdx.x < R) dn[threadIdx.x] = bf(a.down[(static_cast(g) * a.rows + row) * R + threadIdx.x]); + if (threadIdx.x + kLin < R) dn[threadIdx.x + kLin] = bf(a.down[(static_cast(g) * a.rows + row) * R + threadIdx.x + kLin]); __syncthreads(); - float ss = 0.0f; - for (int i = threadIdx.x; i < H; i += kThreads) { - const uint16_t* wf = a.forget[g] + static_cast(i) * R; - const uint16_t* wg = a.gain[g] + static_cast(i) * R; - float f = 0.0f, gn = 0.0f; - for (int r = 0; r < R; ++r) { - f = fmaf(bf(wf[r]), dn[r], f); - gn = fmaf(bf(wg[r]), dn[r], gn); - } - const float v = (1.0f - tanhf(f)) * h[i] + tanhf(gn) * m[i]; - ys[i] = v; - ss = fmaf(v, v, ss); + const int i = blockIdx.z * kLin + threadIdx.x; + if (i >= H) return; + const uint16_t* wf = a.forget[g] + static_cast(i) * R; + const uint16_t* wg = a.gain[g] + static_cast(i) * R; + float f = 0.0f, gn = 0.0f; + for (int r = 0; r < R; ++r) { + f = fmaf(bf(wf[r]), dn[r], f); + gn = fmaf(bf(wg[r]), dn[r], gn); } + const float* h = a.h[g] + row * H; + const float* m = a.msg + a.slot[g] * a.msg_stride + row * H; + a.ys[(static_cast(g) * a.rows + row) * H + i] = (1.0f - tanhf(f)) * h[i] + tanhf(gn) * m[i]; +} + +// out[g][row] = norm * rms(ys[g][row]): the squares summed in the order a 256-thread block strides them. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2_loop_gate_mix(const LoopGateArgs a) { + __shared__ float sh[kWarps]; + const size_t row = blockIdx.x; + const int g = blockIdx.y, H = a.H; + const float* ys = a.ys + (static_cast(g) * a.rows + row) * H; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += kThreads) ss = fmaf(ys[i], ys[i], ss); const float inv = rsqrtf(blockSum(ss, sh) / static_cast(H) + a.eps); uint16_t* dst = a.out + g * a.out_stride + row * H; for (int i = threadIdx.x; i < H; i += kThreads) dst[i] = tobf(bf(a.norm[g][i]) * (ys[i] * inv)); diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig index a0b8bd486fe..8aeb70ad604 100644 --- a/zig/src/families/inkling2/loop.zig +++ b/zig/src/families/inkling2/loop.zig @@ -8,6 +8,7 @@ pub const max_queries = 4; pub const max_gates = 3; pub const max_rank = 128; const threads = 256; +const lin_threads = 128; // loop.cu kLin /// loop.cu's LoopMixArgs, field for field. pub const MixArgs = extern struct { @@ -43,12 +44,14 @@ pub const GateArgs = extern struct { rank: i32, eps_unit: f32, eps: f32, + ys: u64 = 0, // fp32 [gates][rows, H] scratch: the gated rows before their norm }; pub const Kernels = struct { mod: cuda.Module, mix: cuda.Function, gate_down: cuda.Function, + gate_lin: cuda.Function, gate_mix: cuda.Function, pub fn load(d: *const cuda.Driver) !Kernels { @@ -59,6 +62,7 @@ pub const Kernels = struct { .mod = mod, .mix = try mod.function("tf_ink2_loop_mix"), .gate_down = try mod.function("tf_ink2_loop_gate_down"), + .gate_lin = try mod.function("tf_ink2_loop_gate_lin"), .gate_mix = try mod.function("tf_ink2_loop_gate_mix"), }; } @@ -76,7 +80,7 @@ pub fn mixFits(a: MixArgs) error{Inkling2LoopShape}!void { } pub fn gateFits(a: GateArgs, count: usize) error{Inkling2LoopShape}!void { - if (a.rows <= 0 or a.h_dim <= 0 or a.rank <= 0 or a.rank > max_rank or count == 0 or count > max_gates) + if (a.rows <= 0 or a.h_dim <= 0 or a.rank <= 0 or a.rank > max_rank or count == 0 or count > max_gates or a.ys == 0) return error.Inkling2LoopShape; } @@ -95,13 +99,17 @@ pub fn gates(k: *const Kernels, s: cuda.Stream, a: GateArgs, n: usize) !void { args.add(a); const grid: cuda.Dim3 = .{ .x = @intCast(a.rows), .y = @intCast(n) }; const h: u32 = @intCast(a.h_dim); - try cuda.launch.launch(k.gate_down, .{ .grid = grid, .block = .{ .x = threads }, .shared = 2 * h * 4 }, s, &args); - try cuda.launch.launch(k.gate_mix, .{ .grid = grid, .block = .{ .x = threads }, .shared = h * 4 }, s, &args); + // spread over the GPU: rank rows 8 a block, outputs 128 a block; the norm a block a row and gate + const down: cuda.Dim3 = .{ .x = grid.x, .y = grid.y, .z = @intCast(std.math.divCeil(i32, a.rank, threads / 32) catch unreachable) }; + try cuda.launch.launch(k.gate_down, .{ .grid = down, .block = .{ .x = threads }, .shared = 2 * h * 4 }, s, &args); + const lin: cuda.Dim3 = .{ .x = grid.x, .y = grid.y, .z = std.math.divCeil(u32, h, lin_threads) catch unreachable }; + try cuda.launch.launch(k.gate_lin, .{ .grid = lin, .block = .{ .x = lin_threads } }, s, &args); + try cuda.launch.launch(k.gate_mix, .{ .grid = grid, .block = .{ .x = threads } }, s, &args); } test "loop: the argument structs keep loop.cu's layouts" { try std.testing.expectEqual(@as(usize, 8 * 8 + 8 + 4 * 8 + 8 + 8 + 5 * 4 + 2 * 4 + 4), @sizeOf(MixArgs)); - try std.testing.expectEqual(@as(usize, 3 * 8 + 8 + 8 + 3 * 4 + 4 + 4 * 3 * 8 + 3 * 8 + 3 * 4 + 2 * 4 + 4), @sizeOf(GateArgs)); + try std.testing.expectEqual(@as(usize, 3 * 8 + 8 + 8 + 3 * 4 + 4 + 4 * 3 * 8 + 3 * 8 + 3 * 4 + 2 * 4 + 4 + 8), @sizeOf(GateArgs)); } test "loop: shapes past the kernels' arrays are refused by name" { @@ -113,7 +121,7 @@ test "loop: shapes past the kernels' arrays are refused by name" { bad = ok; bad.n_blocks = 9; try std.testing.expectError(error.Inkling2LoopShape, mixFits(bad)); - const g: GateArgs = .{ .msg = 1, .msg_stride = 0, .down = 1, .out = 1, .out_stride = 0, .rows = 1, .h_dim = 2304, .rank = 64, .eps_unit = 1e-6, .eps = 1e-6 }; + const g: GateArgs = .{ .ys = 1, .msg = 1, .msg_stride = 0, .down = 1, .out = 1, .out_stride = 0, .rows = 1, .h_dim = 2304, .rank = 64, .eps_unit = 1e-6, .eps = 1e-6 }; try gateFits(g, 3); try std.testing.expectError(error.Inkling2LoopShape, gateFits(g, 4)); var wide = g; diff --git a/zig/src/families/inkling2/mini_model.zig b/zig/src/families/inkling2/mini_model.zig index 6ff25a1318f..065e64c7dff 100644 --- a/zig/src/families/inkling2/mini_model.zig +++ b/zig/src/families/inkling2/mini_model.zig @@ -100,6 +100,8 @@ pub const Scratch = struct { rel: u64, gate: u64, sink: u64, + gys: u64, // fp32 [3][rows, H]: the gates' rows before their norm + fused: u64, // a one-row forward's fused projections, Fused.all bf16 columns (q, gate, rel, sink, k, v) dyn: [2]u64, // fp32 [R, kv * 4] kc: u64, vc: u64, @@ -139,6 +141,9 @@ pub const Model = struct { s: Scratch = undefined, buffers: std.ArrayList(DeviceBuffer) = .empty, planned: ?usize = null, // a plan: the bytes counted, nothing allocated + /// Decode forwards of n one-row windows as CUDA graphs, captured at first use ([n]); TF_INKLING2_GRAPHS=0: off. + graphs: [round_rows + 1]?cuda.graph.Exec = @splat(null), + graphed: bool = true, fn alloc(m: *Model, bytes: usize) !u64 { if (m.planned) |*p| { @@ -197,6 +202,10 @@ pub const Model = struct { } pub fn deinit(m: *Model) void { + for (&m.graphs) |*g| if (g.*) |*e| { + e.deinit(); + g.* = null; + }; for (m.buffers.items) |*b| b.free(); m.buffers.deinit(m.gpa); } @@ -229,6 +238,9 @@ pub const Model = struct { const stride_full = attn.slotsFor(m.full, m.context); const entries = @max(r * heads * @max(attn.slotsFor(m.sliding, m.context), stride_full), attn.split_rows * heads * stride_full * attn.subs); var part: usize = 0; + for (m.w.layers) |l| for ([_]cuda.qmmf.Weight{ l.attn.qx, l.attn.all }) |w| { + part = @max(part, k.lane.partBytes(1, w)); + }; for (m.w.layers) |l| for ([_]cuda.qmmf.Weight{ l.attn.wq, l.attn.wk, l.attn.wv, l.attn.wr, l.attn.gate, l.attn.sink, l.attn.wo }) |w| { for (1..r + 1) |rows| part = @max(part, k.lane.partBytes(rows, w)); }; @@ -255,6 +267,8 @@ pub const Model = struct { .rel = try m.alloc(r * heads * t.d_rel * 2), .gate = try m.alloc(r * q * 2), .sink = try m.alloc(r * heads * 2), + .gys = try m.alloc(3 * r * h * 4), + .fused = try m.alloc(wts.Fused.of(t).all * 2), .dyn = .{ try m.alloc(r * t.global.kv * config.conv_taps * 4), try m.alloc(r * t.global.kv * config.conv_taps * 4) }, .kc = try m.alloc(r * kvw * 2), .vc = try m.alloc(r * kvw * 2), @@ -320,7 +334,28 @@ pub const Model = struct { if (chains.len > round_rows or heads > round_rows or head0 + heads > rows) return error.TooManyRows; for (chains) |ch| if (ch.p0 == 0) try m.clear(s, ch.slot); var r = try visit.Rows.stage(m, s, chains, rows, prompt); - try visit.run(m, k, s, &r, head0, heads); + // one row a stream, every row's logits: the launches depend on the row count alone (the rest is on the device) + if (prompt or !m.graphed or head0 != 0 or heads != rows or r.streams != rows or r.n_tiles != rows) + return visit.run(m, k, s, &r, head0, heads); + const g = &m.graphs[rows]; + if (g.* == null) g.* = try m.capture(k, s, &r); + try g.*.?.launchOn(s); + } + + /// A decode forward of `r.n` one-row windows, captured as a graph. + fn capture(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const visit.Rows) !cuda.graph.Exec { + try s.synchronize(); + try cuda.graph.beginCapture(s, .thread_local); + visit.run(m, k, s, r, 0, r.n) catch |e| { + if (cuda.graph.endCapture(s)) |g| { + var gg = g; + gg.deinit(); + } else |_| {} + return e; + }; + var g = try cuda.graph.endCapture(s); + defer g.deinit(); + return g.instantiate(); } }; diff --git a/zig/src/families/inkling2/mini_native.zig b/zig/src/families/inkling2/mini_native.zig index 820113bea69..2ed404d1c1d 100644 --- a/zig/src/families/inkling2/mini_native.zig +++ b/zig/src/families/inkling2/mini_native.zig @@ -57,10 +57,10 @@ const Plan = struct { } }; -/// What open refuses before any weight is read: --loops, a drafter, captured kernels. +/// What open refuses before any weight is read: --loops and captured kernels (--drafter: the host, drafter_refusal). +/// `drafts` is the server's default on: with no head it drafts nothing (facts: mtp and copies off). fn refuse(kernels: ?[]const u8, o: Options) !void { if (o.loops != null) return error.Inkling2MiniLoopsFixed; - if (o.drafts) return error.NoDraftHead; if (kernels != null) return error.CapturedKernels; if (o.lanes_fixed and o.lanes > be.round_rows) return error.ParallelPastRound; } @@ -149,15 +149,15 @@ fn release(p: *anyopaque) void { own.gpa.destroy(own); } -test "Inkling 2 Mini open: --loops, a drafter and captured kernels are refused by name before any load" { +test "Inkling 2 Mini open: --loops and captured kernels are refused by name before any load" { const base: Options = .{ .context = 4096, .drafts = false }; try refuse(null, base); var o = base; o.loops = 3; try std.testing.expectError(error.Inkling2MiniLoopsFixed, refuse(null, o)); o = base; - o.drafts = true; - try std.testing.expectError(error.NoDraftHead, refuse(null, o)); + o.drafts = true; // the server's default: nothing to draft with, not a refusal + try refuse(null, o); try std.testing.expectError(error.CapturedKernels, refuse("dir", base)); // open refuses before it allocates: a failing allocator sees no request var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); diff --git a/zig/src/families/inkling2/mini_ref.zig b/zig/src/families/inkling2/mini_ref.zig index 24eba024369..144e30dd5ac 100644 --- a/zig/src/families/inkling2/mini_ref.zig +++ b/zig/src/families/inkling2/mini_ref.zig @@ -11,7 +11,8 @@ const Tensor = core.checkpoint.Tensor; const Checkpoint = core.checkpoint.Checkpoint; /// Each position's top token, its margin over the runner-up and the top logit (soft-capped). -pub const Pick = struct { id: u32, margin: f64, top: f64 }; +/// Its five best ids and logits, best first (ties: the lower id), for cross-engine comparisons. +pub const Pick = struct { id: u32, margin: f64, top: f64, ids: [5]u32 = @splat(0), logits: [5]f64 = @splat(-std.math.inf(f64)) }; const e4m3_table = blk: { @setEvalBranchQuota(100000); @@ -127,6 +128,7 @@ pub const Ref = struct { c: config.Config, p: plan_.Plan, ck: *Checkpoint, + plant: bool = false, // a planted control: the cross-pass messages dropped (the check must then go red) fn get(r: *Ref, comptime fmt: []const u8, args: anytype) !Tensor { var buf: [128]u8 = undefined; @@ -223,16 +225,21 @@ pub const Ref = struct { src[nb] = hcur[i]; mixOne(h, src[0 .. nb + 1], oq.bytes, 0, xf); normInto(xf, norm, t.eps); - var best: Pick = .{ .id = 0, .margin = 0, .top = -std.math.inf(f64) }; - var second = -std.math.inf(f64); + var best: Pick = .{ .id = 0, .margin = 0, .top = 0 }; for (0..t.unpadded_vocab) |vid| { const l = t.logit_cap * std.math.tanh(dotBf(unembed.bytes, vid, h, xf) / t.logit_cap); - if (l > best.top) { - second = best.top; - best = .{ .id = @intCast(vid), .margin = 0, .top = l }; - } else if (l > second) second = l; + if (l <= best.logits[4]) continue; + var at: usize = 4; + while (at > 0 and l > best.logits[at - 1]) : (at -= 1) { + best.logits[at] = best.logits[at - 1]; + best.ids[at] = best.ids[at - 1]; + } + best.logits[at] = l; + best.ids[at] = @intCast(vid); } - best.margin = best.top - second; + best.id = best.ids[0]; + best.top = best.logits[0]; + best.margin = best.logits[0] - best.logits[1]; out[i] = best; } } @@ -244,7 +251,7 @@ pub const Ref = struct { const spec = p.at(i); const h: usize = t.hidden; const global = spec.kind == .global; - const msgs = p.messages(v); + const msgs = p.messages(v) and !r.plant; const L = .{i}; if (p.bank_blocks > 1) return error.Inkling2RefBank; // one banked block (Mini), or none (the tiny checkpoint) if (p.restarts(v)) for (0..n) |row| { diff --git a/zig/src/families/inkling2/mini_visit.zig b/zig/src/families/inkling2/mini_visit.zig index 83e2befc8df..1d84885d2f2 100644 --- a/zig/src/families/inkling2/mini_visit.zig +++ b/zig/src/families/inkling2/mini_visit.zig @@ -8,6 +8,7 @@ const attn = @import("kernels.zig"); const ops = @import("ops.zig"); const loop = @import("loop.zig"); const mm = @import("mini_model.zig"); +const wts = @import("mini_weights.zig"); const Model = mm.Model; const Kernels = mm.Kernels; @@ -84,6 +85,9 @@ pub fn run(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, head0: try ops.softcap(&k.ops, s, m.s.logits, heads * v, t.logit_cap); } +/// The input projections' outputs: the scratch buffers, or a one-row forward's parts of the fused output. +const Out = struct { q: u64, k: u64, v: u64, rel: u64, gate: u64, sink: u64 }; + fn proj(m: *const Model, k: *const Kernels, s: cuda.Stream, w: cuda.qmmf.Weight, x: u64, out: u64, n: usize) !void { try k.lane.matmulOut(s, x, w.k, n, w, out, .bf16, m.s.lane_part); } @@ -114,14 +118,14 @@ fn scale(h: usize) f32 { /// A core input through its gates: the residual mix of `nq` queries over `nb` blocks and the partial, then each gate /// (controllers[g], message plane slots[g]) and its norm into `out` planes. -fn gated(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, nb: usize, partial: u64, f32_partial: bool, query: u64, nq: usize, ctl: []const @import("mini_weights.zig").Controller, slots: [3]i32, norms: [3]u64, out: u64) !void { +fn gated(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, nb: usize, partial: u64, f32_partial: bool, query: u64, nq: usize, ctl: []const wts.Controller, slots: [3]i32, norms: [3]u64, out: u64) !void { const h: usize = m.c.hidden; const plane = r.n * h; var a: loop.MixArgs = .{ .partial = partial, .out = m.s.mixf, .out_stride = @intCast(plane), .n_blocks = @intCast(nb), .partial_f32 = @intFromBool(f32_partial), .nq = @intCast(nq), .rows = @intCast(r.n), .h = @intCast(h), .eps = m.c.eps, .scale = scale(h) }; for (0..nb) |b| a.blocks[b] = m.s.blocks + b * plane * 2; for (0..nq) |q| a.query[q] = query + q * h * 4; try loop.mix(&k.loop, s, a); - var g: loop.GateArgs = .{ .msg = m.s.msg, .msg_stride = @intCast(plane), .down = m.s.gdown, .out = out, .out_stride = @intCast(plane), .rows = @intCast(r.n), .h_dim = @intCast(h), .rank = @intCast(m.c.loop.?.rank), .eps_unit = m.c.eps, .eps = m.c.eps }; + var g: loop.GateArgs = .{ .msg = m.s.msg, .msg_stride = @intCast(plane), .down = m.s.gdown, .ys = m.s.gys, .out = out, .out_stride = @intCast(plane), .rows = @intCast(r.n), .h_dim = @intCast(h), .rank = @intCast(m.c.loop.?.rank), .eps_unit = m.c.eps, .eps = m.c.eps }; for (0..ctl.len) |i| { g.h[i] = m.s.mixf + (if (nq == 3) i else 0) * plane * 4; g.slot[i] = slots[i]; @@ -171,12 +175,30 @@ fn visitOne(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32 const xq = m.s.xin; const xk = if (separate) m.s.xin + plane * 2 else xq; const xv = if (separate) m.s.xin + 2 * plane * 2 else xq; - try proj(m, k, s, a.wq, xq, m.s.q, n); - try proj(m, k, s, a.wk, xk, m.s.kraw, n); - try proj(m, k, s, a.wv, xv, m.s.vraw, n); - try proj(m, k, s, a.wr, xq, m.s.rel, n); - try proj(m, k, s, a.gate, xq, m.s.gate, n); - try proj(m, k, s, a.sink, xq, m.s.sink, n); + // one row: the fused product (q, gate, rel, sink and k, v when they share the input), its parts read in place + var o: Out = .{ .q = m.s.q, .k = m.s.kraw, .v = m.s.vraw, .rel = m.s.rel, .gate = m.s.gate, .sink = m.s.sink }; + if (n == 1) { + const f = wts.Fused.of(t); + const at = struct { + fn col(base: u64, c: usize) u64 { + return base + c * 2; + } + }.col; + const fz = m.s.fused; + o = .{ .q = at(fz, f.q), .k = at(fz, f.k), .v = at(fz, f.v), .rel = at(fz, f.rel), .gate = at(fz, f.gate), .sink = at(fz, f.sink) }; + try proj(m, k, s, if (separate) a.qx else a.all, xq, fz, 1); + if (separate) { + try proj(m, k, s, a.wk, xk, o.k, 1); + try proj(m, k, s, a.wv, xv, o.v, 1); + } + } else { + try proj(m, k, s, a.wq, xq, o.q, n); + try proj(m, k, s, a.wk, xk, o.k, n); + try proj(m, k, s, a.wv, xv, o.v, n); + try proj(m, k, s, a.wr, xq, o.rel, n); + try proj(m, k, s, a.gate, xq, o.gate, n); + try proj(m, k, s, a.sink, xq, o.sink, n); + } const kvw = kvWidth(m); const kvh: usize = t.local.kv; const taps = kvh * config.conv_taps; @@ -184,7 +206,7 @@ fn visitOne(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32 // the taps as torch's bf16 linear leaves them: float(bf16(sum)) times 1 try k.dense.rowsScaled(s, x, h, w, m.w.ones, m.s.dyn[side], taps, n, taps, h); }; - for ([_]Site{ .k, .v }, [_]u64{ m.s.kraw, m.s.vraw }, [_]u64{ m.s.kc, m.s.vc }, [_]u64{ a.k_conv, a.v_conv }, 0..) |site, x, out, w, side| { + for ([_]Site{ .k, .v }, [_]u64{ o.k, o.v }, [_]u64{ m.s.kc, m.s.vc }, [_]u64{ a.k_conv, a.v_conv }, 0..) |site, x, out, w, side| { try conv(m, k, s, r, v, site, .{ .x = x, .state = 0, .w = w, .dyn = if (global) m.s.dyn[side] else 0, .out = out, .x_bf16 = 1, .heads = @intCast(kvh), .c = @intCast(kvw), .rows = 0, .mode = 0 }); } // q, rel and the caches' new K and V rows, the bias table, then attention through the sink and the output gate @@ -192,10 +214,10 @@ fn visitOne(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32 const rows: attn.Rows = .{ .rows = @intCast(n), .heads = t.local.q, .kv_heads = t.local.kv, .pos = m.s.pos, .seg_of = m.s.seg_of, .segs = m.s.segs[@intFromBool(global)], .tiles = m.s.tiles, .n_tiles = r.n_tiles, .last_pos = r.last_pos, .streams = @intCast(r.streams) }; const cache: attn.Cache = .{ .k = m.kv[0][v], .v = m.kv[1][v] }; const prep: attn.Prep = .{ .qk_clip = t.qk_clip, .rel_clip = t.rel_clip, .floor = @floatFromInt(t.log_floor), .alpha = t.log_alpha, .eps = t.eps }; - try attn.prep(&k.attn, s, rows, l, prep, .{ m.s.q, m.s.kc, m.s.vc, m.s.rel }, .{ a.q_scale, a.rel_scale }, m.s.qp, m.s.relp, cache); + try attn.prep(&k.attn, s, rows, l, prep, .{ o.q, m.s.kc, m.s.vc, o.rel }, .{ a.q_scale, a.rel_scale }, m.s.qp, m.s.relp, cache); try attn.relTable(&k.attn, s, rows, m.s.relp, a.rel_proj, m.s.tab); const stride = attn.slotsFor(l, m.context); - try attn.attend(&k.attn, s, rows, l, stride, m.s.entries, m.s.qp, cache, m.s.tab, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.att); + try attn.attend(&k.attn, s, rows, l, stride, m.s.entries, m.s.qp, cache, m.s.tab, m.s.part_o, m.s.part_ml, o.sink, o.gate, m.s.att); try proj(m, k, s, a.wo, m.s.att, m.s.o, n); // the attention conv into the fp32 residual: a block boundary keeps only the attention output as the partial try conv(m, k, s, r, v, .attn, .{ .x = m.s.o, .state = 0, .w = L.attn_conv, .base = if (spec.boundary) 0 else hin, .resid = m.s.h32, .x_bf16 = 1, .c = @intCast(h), .rows = 0, .mode = 1 }); @@ -216,7 +238,7 @@ fn visitOne(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, v: u32 } /// The router's picks over sigmoid scores, the routed experts as stored (core experts), their weighted sum in bf16. -fn moe(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, L: *const @import("mini_weights.zig").Layer) !void { +fn moe(m: *Model, k: *const Kernels, s: cuda.Stream, r: *const Rows, L: *const wts.Layer) !void { const t = m.c; const h: usize = t.hidden; const n = r.n; diff --git a/zig/src/families/inkling2/mini_weights.zig b/zig/src/families/inkling2/mini_weights.zig index 3799e7c51b8..89fb777a64d 100644 --- a/zig/src/families/inkling2/mini_weights.zig +++ b/zig/src/families/inkling2/mini_weights.zig @@ -16,7 +16,33 @@ const Tensor = core.checkpoint.Tensor; /// NVFP4's outer scale denominator as Mini ships it (scales/RESULTS.md); another value is refused. pub const nvfp4_denominator = 2688; +/// One packed buffer a layer, rows [q | gate | rel | sink padded to 64 | k | v]: views of it, every one at the +/// parts' own K slices (one count for all six, else refused), so a fused product's rows carry the separate bits. +pub const Fused = struct { + /// Row offsets of the parts in the fused output. + q: usize, + gate: usize, + rel: usize, + sink: usize, + k: usize, + v: usize, + /// The q-side rows (q, gate, rel, sink: one input), and every row (q, k and v from one input). + qx: usize, + all: usize, + + pub fn of(c: *const config.Text) Fused { + const qw: usize = @as(usize, c.local.q) * c.local.dim; + const kvw: usize = @as(usize, c.local.kv) * c.local.dim; + const rel = 2 * qw; + const sink = rel + @as(usize, c.local.q) * c.d_rel; + const k = sink + std.mem.alignForward(usize, c.local.q, 64); + return .{ .q = 0, .gate = qw, .rel = rel, .sink = sink, .k = k, .v = k + kvw, .qx = k, .all = k + 2 * kvw }; + } +}; + pub const Attn = struct { + qx: Lane, // the fused q-side rows (one input: q, gate, rel, sink) + all: Lane, // every fused row (q, k and v from one input) wq: Lane, wk: Lane, wv: Lane, @@ -80,6 +106,37 @@ pub const Weights = struct { return b.ptr; } + /// The six input projections packed as Fused orders them; every view pinned to the parts' K slices. + fn fused(w: *Weights, d: *const cuda.Driver, parts: [6]Tensor, a: *Attn) !void { + const f = Fused.of(&w.config.text); + const k = parts[0].dim(1); + const offs = [6]usize{ f.q, f.gate, f.rel, f.sink, f.k, f.v }; + const npad = cuda.modelopt.padded(f.all); + const src = try w.gpa.alloc(u16, f.all * k); + defer w.gpa.free(src); + @memset(src, 0); + const ends = [6]usize{ f.gate, f.rel, f.sink, f.k, f.v, f.all }; + for (parts, offs, ends) |t, o, e| { + if (t.dim(1) != k or o + t.dim(0) > e) return error.Inkling2FusedShape; + @memcpy(std.mem.sliceAsBytes(src[o * k ..][0 .. t.dim(0) * k]), t.bytes[0 .. t.dim(0) * k * 2]); + } + const out = try w.gpa.alloc(u16, npad * k); + defer w.gpa.free(out); + cuda.qmmf.packBf16(out, src, f.all, k); + const base = try w.upload(d, std.mem.sliceAsBytes(out)); + const sk = cuda.qmmf.splitK(parts[0].dim(0), k); + for (parts) |t| if (cuda.qmmf.splitK(t.dim(0), k) != sk) return error.Inkling2FusedSlices; + const view = struct { + fn at(ptr: u64, row: usize, n: usize, kk: usize, slices: u32) !Lane { + return cuda.qmmf.pinned(cuda.modelopt.bf16Weight(ptr + row * kk * 2, n, kk), slices); + } + }; + a.qx = try view.at(base, 0, f.qx, k, sk); + a.all = try view.at(base, 0, f.all, k, sk); + const lanes = [_]*Lane{ &a.wq, &a.gate, &a.wr, &a.sink, &a.wk, &a.wv }; + for (lanes, parts, offs) |l, t, o| l.* = try view.at(base, o, t.dim(0), k, sk); + } + /// A bf16 [n, k] projection (its first `rows` rows) in the lane's order, padded to 128 rows. fn lane(w: *Weights, d: *const cuda.Driver, t: Tensor, rows: usize) !Lane { const k = t.dim(t.rank - 1); @@ -104,6 +161,20 @@ fn raw(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, comp return w.upload(d, (try get(ck, fmt, args)).bytes); } +/// rel_logits_proj [d_rel][e] widened to the kernels' [d_rel][1024] with zero columns: no bias past e, as in the model. +fn relProj(w: *Weights, d: *const cuda.Driver, t: Tensor) !u64 { + const ext = @import("kernels.zig").extent; + const rows = t.dim(0); + const e = t.dim(1); + if (e > ext) return error.Inkling2RelExtent; + if (e == ext) return w.upload(d, t.bytes); + const out = try w.gpa.alloc(u16, rows * ext); + defer w.gpa.free(out); + @memset(out, 0); + for (0..rows) |r| @memcpy(std.mem.sliceAsBytes(out[r * ext ..][0..e]), t.bytes[r * e * 2 ..][0 .. e * 2]); + return w.upload(d, std.mem.sliceAsBytes(out)); +} + fn proj(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, comptime fmt: []const u8, args: anytype) !Lane { const t = try get(ck, fmt, args); return w.lane(d, t, t.dim(0)); @@ -165,20 +236,28 @@ fn layer(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, i: const L = .{i}; const global = config.isGlobal(i); var a: Attn = .{ - .wq = try proj(w, d, ck, "model.llm.layers.{d}.attn.wq_du.weight", L), - .wk = try proj(w, d, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L), - .wv = try proj(w, d, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L), - .wr = try proj(w, d, ck, "model.llm.layers.{d}.attn.wr_du.weight", L), - .gate = try proj(w, d, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L), - .sink = try proj(w, d, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L), + .qx = undefined, + .all = undefined, + .wq = undefined, + .wk = undefined, + .wv = undefined, + .wr = undefined, + .gate = undefined, + .sink = undefined, .wo = try proj(w, d, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L), .q_scale = try raw(w, d, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L), .rel_scale = try raw(w, d, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L), - .rel_proj = try raw(w, d, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L), + .rel_proj = try relProj(w, d, try get(ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L)), .k_conv = undefined, .v_conv = undefined, .norms = undefined, }; + const pre = "model.llm.layers.{d}.attn."; + try w.fused(d, .{ + try get(ck, pre ++ "wq_du.weight", L), try get(ck, pre ++ "gate_attn.weight", L), + try get(ck, pre ++ "wr_du.weight", L), try get(ck, pre ++ "attn_sink_proj.weight", L), + try get(ck, pre ++ "wk_dv.weight", L), try get(ck, pre ++ "wv_dv.weight", L), + }, &a); if (global) { a.k_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.k_sconv.static_w", L); a.v_conv = try raw(w, d, ck, "model.llm.layers.{d}.attn.v_sconv.static_w", L); @@ -282,3 +361,15 @@ fn experts(w: *Weights, d: *const cuda.Driver, ck: *core.checkpoint.Checkpoint, } return l; } + +test "the fused rows: parts in order, sink padded to 64 rows, every view on a 64-row block edge" { + var c: config.Text = undefined; + c.local = .{ .q = 24, .kv = 8, .dim = 128 }; + c.d_rel = 16; + const f = Fused.of(&c); + try std.testing.expectEqual(Fused{ .q = 0, .gate = 3072, .rel = 6144, .sink = 6528, .k = 6592, .v = 7616, .qx = 6592, .all = 8640 }, f); + for ([_]usize{ f.k, f.v, f.qx, f.all }) |r| try std.testing.expect(r % 64 == 0); + // Mini's six parts share 4 K slices at K 2304 (the fused views pin them); the tiny checkpoint's share 1 at K 256 + for ([_]usize{ 3072, 1024, 384, 24 }) |n| try std.testing.expectEqual(@as(u32, 4), cuda.qmmf.splitK(n, 2304)); + for ([_]usize{ 512, 256, 64, 4 }) |n| try std.testing.expectEqual(@as(u32, 1), cuda.qmmf.splitK(n, 256)); +} diff --git a/zig/tests/cuda/inkling2_mini_tests.zig b/zig/tests/cuda/inkling2_mini_tests.zig index 0b28f0ce75e..71662a4a05b 100644 --- a/zig/tests/cuda/inkling2_mini_tests.zig +++ b/zig/tests/cuda/inkling2_mini_tests.zig @@ -130,9 +130,31 @@ pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8, text: []const u8 std.debug.print("{s} inkling2 mini prompt in chunks of {d}: last-row logits {s}, {d} greedy tokens {s}\n", .{ if (same and tokens_same) "PASS" else "FAIL", chunk, if (same) "bit-equal" else "differ", resumed.len, if (tokens_same) "equal" else "differ" }); } try check.expect(bad == 0, "inkling2 mini resumed == fresh: {d} chunkings differ", .{bad}); + try graphs(&rig, ids, first, plain); try concurrent(&rig, ids, plain); } +/// The decode graphs against direct launches: the first step's logits bit-equal, then 32 greedy tokens equal. +fn graphs(rig: *Rig, ids: []const u32, first: []const f32, plain: []const u32) !void { + const gpa = rig.gpu.gpa; + var rows: [2][]f32 = undefined; + for ([_]bool{ true, false }, 0..) |on, i| { + rig.m.graphed = on; + gpa.free(try rig.prompt(2 + i, ids, 0, mm.prompt_rows)); + rows[i] = try rig.step(&.{.{ .slot = 2 + i, .p0 = ids.len, .tokens = plain[0..1] }}); + } + defer for (rows) |r| gpa.free(r); + const same = std.mem.eql(u8, std.mem.sliceAsBytes(rows[0]), std.mem.sliceAsBytes(rows[1])); + const direct = try gpa.alloc(u32, @min(plain.len, 32)); + defer gpa.free(direct); + gpa.free(try rig.prompt(3, ids, 0, mm.prompt_rows)); // afresh: the step above moved slot 3's conv states + try decode(rig, 3, first, ids.len, direct); + rig.m.graphed = true; + const tokens_same = std.mem.eql(u32, direct, plain[0..direct.len]); + try check.expect(same and tokens_same, "inkling2 mini graphs == direct: logits {s}, tokens {s}", .{ if (same) "equal" else "differ", if (tokens_same) "equal" else "differ" }); + check.pass("inkling2 mini decode graphs == direct launches: first step's logits bit-equal, {d} greedy tokens equal", .{direct.len}); +} + /// Four streams at once (prompts of different lengths) against each alone: equal tokens; the round's decode speed. fn concurrent(rig: *Rig, ids: []const u32, plain: []const u32) !void { const gpa = rig.gpu.gpa; @@ -195,7 +217,9 @@ pub fn reference(gpu: Gpu, model: []const u8, count_text: []const u8, text: []co try decode(&rig, 0, first, ids.len, all[ids.len..]); var ck = try core.checkpoint.Checkpoint.openModel(gpa, gpu.io, model); defer ck.close(); - var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck }; + // INKLING2_REF_PLANT=1: the reference drops the cross-pass messages; the check must go red + const plant = if (std.c.getenv("INKLING2_REF_PLANT")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck, .plant = plant }; const picks = try gpa.alloc(ink.mini_ref.Pick, all.len); defer gpa.free(picks); const t0 = check.now(gpu.io); @@ -213,6 +237,7 @@ pub fn reference(gpu: Gpu, model: []const u8, count_text: []const u8, text: []co } const said = try tok.decode(gpa, all[ids.len..], false); defer gpa.free(said); - std.debug.print("RESULT inkling2 mini vs float64 reference: {d} of {d} greedy tokens differ, smallest reference margin {d:.4}: \"{s}\"\n", .{ differ, count, smallest, said }); + std.debug.print("RESULT inkling2 mini vs float64 reference{s}: {d} of {d} greedy tokens differ, smallest reference margin {d:.4}: \"{s}\"\n", .{ if (plant) " (PLANTED: no messages)" else "", differ, count, smallest, said }); + if (plant) return check.expect(differ > 0, "inkling2 mini planted control: the reference without messages still agrees", .{}); try check.expect(differ == 0, "inkling2 mini greedy == reference: {d} of {d} tokens differ", .{ differ, count }); } diff --git a/zig/tests/cuda/inkling2_mini_xcheck.zig b/zig/tests/cuda/inkling2_mini_xcheck.zig new file mode 100644 index 00000000000..0d09b54c090 --- /dev/null +++ b/zig/tests/cuda/inkling2_mini_xcheck.zig @@ -0,0 +1,133 @@ +//! tf-cuda-test inkling2-mini-xcheck DIR N: the cross-engine check against #4337's Metal forward. Prompt A is raw ids +//! [1, 100, ..., 700]; prompt B is "The capital of France is" tokenized without a template. For each it prints one +//! "XCHECK {json}" line: the prompt ids, N greedy tokens, each step's top 2 (id, soft-capped logit) and the last prompt +//! row's top 5, from the CUDA engine and, teacher-forced on the engine's tokens, from the float64 reference. +const std = @import("std"); +const core = @import("core"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const tests = @import("inkling2_mini_tests.zig"); +const Gpu = check.Gpu; + +const mm = ink.mini_model; +const Pick = ink.mini_ref.Pick; + +const Top = struct { id: u32, v: f32 }; + +/// The k best of `x`, best first (ties: the lower id). +fn top(x: []const f32, comptime k: usize) [k]Top { + var out: [k]Top = @splat(.{ .id = 0, .v = -std.math.inf(f32) }); + for (x, 0..) |v, i| { + if (!(v > out[k - 1].v)) continue; + var at: usize = k - 1; + while (at > 0 and v > out[at - 1].v) : (at -= 1) out[at] = out[at - 1]; + out[at] = .{ .id = @intCast(i), .v = v }; + } + return out; +} + +fn ids(w: anytype, xs: []const u32) !void { + try w.writeAll("["); + for (xs, 0..) |x, i| try w.print("{s}{d}", .{ if (i == 0) "" else ",", x }); + try w.writeAll("]"); +} + +fn pairsGpu(w: anytype, row: []const f32, comptime k: usize) !void { + const t = top(row, k); + try w.writeAll("["); + for (t, 0..) |p, i| try w.print("{s}[{d},{d:.6}]", .{ if (i == 0) "" else ",", p.id, p.v }); + try w.writeAll("]"); +} + +fn pairsRef(w: anytype, p: Pick, k: usize) !void { + try w.writeAll("["); + for (0..k) |i| try w.print("{s}[{d},{d:.6}]", .{ if (i == 0) "" else ",", p.ids[i], p.logits[i] }); + try w.writeAll("]"); +} + +fn forcedIds(gpa: std.mem.Allocator, name: [:0]const u8) !?[]u32 { + const v = std.mem.span(std.c.getenv(name) orelse return null); + var out: std.ArrayList(u32) = .empty; + errdefer out.deinit(gpa); + var it = std.mem.tokenizeAny(u8, v, ", "); + while (it.next()) |t| try out.append(gpa, try std.fmt.parseInt(u32, t, 10)); + return try out.toOwnedSlice(gpa); +} + +pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8) !void { + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(usize, count_text, 10); + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, model); + defer tok.deinit(); + const b = try tok.encode(gpa, "The capital of France is"); + defer gpa.free(b); + const prompts = [_]struct { name: []const u8, ids: []const u32 }{ + .{ .name = "A", .ids = &.{ 1, 100, 200, 300, 400, 500, 600, 700 } }, + .{ .name = "B", .ids = b }, + }; + var rig: tests.Rig = undefined; + try rig.init(gpu, model, 4096, 1); + defer rig.deinit(); + var ck = try core.checkpoint.Checkpoint.openModel(gpa, gpu.io, model); + defer ck.close(); + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck }; + const v = rig.w.config.text.unpadded_vocab; + var disagree: usize = 0; + for (prompts) |pr| { + const n0 = pr.ids.len; + const all = try gpa.alloc(u32, n0 + count); + defer gpa.free(all); + @memcpy(all[0..n0], pr.ids); + const rows = try gpa.alloc(f32, (count + 1) * v); // the last prompt row's logits, then each step's + defer gpa.free(rows); + const first = try rig.prompt(0, pr.ids, 0, mm.prompt_rows); + @memcpy(rows[0..v], first); + gpa.free(first); + // INKLING2_FORCED_A / _B: comma-separated ids fed in place of the argmax (teacher-forced on another engine's) + const forced = try forcedIds(gpa, if (pr.name[0] == 'A') "INKLING2_FORCED_A" else "INKLING2_FORCED_B"); + defer if (forced) |f| gpa.free(f); + if (forced) |f| if (f.len < count) return error.ForcedTooShort; + const next = struct { + fn at(f: ?[]const u32, row: []const f32, i: usize) u32 { + return if (f) |ff| ff[i] else tests.argmax(row); + } + }.at; + all[n0] = next(forced, rows[0..v], 0); + for (1..count) |i| { + const row = try rig.step(&.{.{ .slot = 0, .p0 = n0 + i - 1, .tokens = all[n0 + i - 1 .. n0 + i] }}); + defer gpa.free(row); + @memcpy(rows[i * v ..][0..v], row); + all[n0 + i] = next(forced, row, i); + } + const picks = try gpa.alloc(Pick, n0 + count - 1); + defer gpa.free(picks); + try r.run(all[0 .. n0 + count - 1], picks); + var buf: std.ArrayList(u8) = .empty; + defer buf.deinit(gpa); + var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, &buf); + const w = &aw.writer; + try w.print("{{\"prompt\":\"{s}\",\"forced\":{},\"ids\":", .{ pr.name, forced != null }); + try ids(w, pr.ids); + try w.writeAll(",\"tokens\":"); + try ids(w, all[n0..]); + try w.writeAll(",\"cuda\":{\"last_prompt_top5\":"); + try pairsGpu(w, rows[0..v], 5); + try w.writeAll(",\"top2\":["); + for (0..count) |i| { + if (i > 0) try w.writeAll(","); + try pairsGpu(w, rows[i * v ..][0..v], 2); + } + try w.writeAll("]},\"ref_f64\":{\"last_prompt_top5\":"); + try pairsRef(w, picks[n0 - 1], 5); + try w.writeAll(",\"top2\":["); + for (0..count) |i| { + if (i > 0) try w.writeAll(","); + try pairsRef(w, picks[n0 - 1 + i], 2); + if (picks[n0 - 1 + i].id != tests.argmax(rows[i * v ..][0..v])) disagree += 1; + } + try w.writeAll("]}}"); + buf = aw.toArrayList(); + std.debug.print("XCHECK {s}\n", .{buf.items}); + } + std.debug.print("RESULT inkling2 mini xcheck: {d} greedy tokens of 2 x {d} where the float64 reference's top 1 and the engine's differ\n", .{ disagree, count }); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 5c7959dacb6..fd19ae22227 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -235,6 +235,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "nvfp4-experts")) return nvfp4_experts_tests.experts(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "bf16-experts")) return if (rest.len == 0) @import("bf16_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_bf16.zig").run(gpu) else error.UnknownCommand; if (std.mem.eql(u8, cmd, "stored-experts")) return storedExperts(gpu, rest); + if (std.mem.eql(u8, cmd, "inkling2-mini-xcheck")) return @import("inkling2_mini_xcheck.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "inkling2-mini-ref")) return @import("inkling2_mini_tests.zig").reference(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "inkling2-mini")) return @import("inkling2_mini_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "projection-f32")) return projection_f32_tests.run(gpu); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index d458cc2de3e..3cc73c1e04a 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -95,6 +95,7 @@ pub const usage = \\ bf16-experts [contract] grouped bf16 experts against float64 (repack, up, downs, rows, forms); contract: gates 1-4, controls red \\ stored-experts contract | ckpt DIR | bench DIR Inkling 2 Mini's NVFP4 and MXFP8 experts: gates, checkpoint, speed \\ inkling2-mini DIR N TEXT Inkling 2 Mini at one rank: N greedy tokens, resumed == fresh, concurrent == solo + \\ inkling2-mini-xcheck DIR N Inkling 2 Mini vs #4337's Metal: prompts A (raw ids) and B, top 2 a step, JSON \\ inkling2-mini-ref DIR N TEXT Inkling 2 Mini's N greedy tokens against the float64 reference, teacher-forced \\ projection-f32 FP32 projection outputs against FP64, rounding and row/reduction invariance \\ mxfp8 MXFP8 strided projections against FP64 and row-count invariance From 75a0c398b09793e8a3e69141ebbb54fc2626bbca Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:35:33 +0000 Subject: [PATCH 09/84] inkling2: accept Mini host config and checkpoint names --- zig/src/families/inkling2/config.zig | 78 ++++++++++- zig/src/families/inkling2/config_test.zig | 35 +++++ .../inkling2/fixtures/mini_config.json | 122 ++++++++++++++++++ .../inkling2/fixtures/mini_model_header.txt | 86 ++++++++++++ .../inkling2/fixtures/mini_mtp_header.txt | 25 ++++ zig/src/families/inkling2/names.zig | 25 +++- zig/src/families/inkling2/names_test.zig | 71 +++++++++- zig/src/families/inkling2/plan.zig | 44 +++++++ 8 files changed, 475 insertions(+), 11 deletions(-) create mode 100644 zig/src/families/inkling2/fixtures/mini_config.json create mode 100644 zig/src/families/inkling2/fixtures/mini_model_header.txt create mode 100644 zig/src/families/inkling2/fixtures/mini_mtp_header.txt diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index b4143603140..9d30527e4d8 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -1,9 +1,12 @@ -//! Inkling 2 Small's shape from config.json (inkling2), refusing every layout the engine does not run. +//! Inkling 2 Small and Mini shapes from config.json, refusing every layout the engine does not run. const std = @import("std"); /// The most backbone layers the plan tables hold (Inkling 2 Small has 48). pub const max_layers = 128; +/// The most scheduled layer visits the visit-plan table holds. +pub const max_visits = max_layers * 8; + /// Every sixth layer attends over the whole context; the reference derives its layer types the same way. pub const global_every = 6; @@ -37,6 +40,14 @@ pub const Why = struct { /// One attention geometry: sliding layers read the `swa_*` keys, global layers the plain ones. pub const Heads = struct { q: u32, kv: u32, dim: u32 }; +/// The fixed loop schedule: all layers once, then only the core on each later pass. +pub const Loop = struct { + core_start: u32, // inclusive physical layer id + core_end: u32, // exclusive physical layer id + passes: u32, + gate_rank: u32, +}; + pub const Text = struct { hidden: u32, layers: u32, @@ -61,6 +72,13 @@ pub const Text = struct { up_cap: f32, logit_cap: f32, max_context: u32, + loop: ?Loop, + + /// The number of scheduled layer visits; a drafter target equal to this is the final norm. + pub fn visitCount(c: *const Text) u32 { + const l = c.loop orelse return c.layers; + return c.layers + (l.passes - 1) * (l.core_end - l.core_start); + } pub fn heads(c: *const Text, i: u32) Heads { return if (isGlobal(i)) c.global else c.local; @@ -72,7 +90,7 @@ pub const Text = struct { } }; -/// The draft head's shape (mtp_config); the target taps are indices into the backbone, `layers` meaning the final norm. +/// The draft head's shape (mtp_config); target taps are visit ids, with `visitCount` meaning the final norm. pub const Mtp = struct { layers: u32, q_heads: u32, @@ -133,6 +151,15 @@ fn int(o: std.json.ObjectMap, key: []const u8, why: *Why) !u32 { return @intCast(v.integer); } +fn index(o: std.json.ObjectMap, key: []const u8, why: *Why) !u32 { + const v = try get(o, key, why); + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) { + why.set("config.json's {s} is not a non-negative whole number", .{key}); + return error.BadConfig; + } + return @intCast(v.integer); +} + fn float(o: std.json.ObjectMap, key: []const u8, why: *Why) !f32 { const v = try get(o, key, why); const x: f64 = switch (v) { @@ -192,8 +219,33 @@ fn layerTypes(o: std.json.ObjectMap, layers: u32, why: *Why) !void { } } +fn parseLoop(o: std.json.ObjectMap, layers: u32, block: u32, why: *Why) !Loop { + const l: Loop = .{ + .core_start = try index(o, "core_start", why), + .core_end = try int(o, "core_end", why), + .passes = try int(o, "num_passes", why), + .gate_rank = try int(o, "gate_rank", why), + }; + try fixed(o, "is_varloop", false, why); + if (l.core_start == 0 or l.core_start >= l.core_end or l.core_end > layers) { + why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers", .{ l.core_start, l.core_end, layers }); + return error.Layout; + } + if (l.core_start % block != 0 or l.core_end % block != 0 or l.core_start != block or l.core_end + block != layers) { + why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, leaving its first and last blocks outside the loop", .{block}); + return error.Layout; + } + const visits = @as(u64, layers) + @as(u64, l.passes - 1) * @as(u64, l.core_end - l.core_start); + if (visits > max_visits) { + why.set("loop_config makes {d} layer visits: the plan tables hold {d}", .{ visits, max_visits }); + return error.Layout; + } + return l; +} + fn parseText(o: std.json.ObjectMap, why: *Why) !Text { var t: Text = undefined; + t.loop = null; t.hidden = try int(o, "hidden_size", why); t.layers = try int(o, "num_hidden_layers", why); t.vocab = try int(o, "vocab_size", why); @@ -261,6 +313,7 @@ fn parseText(o: std.json.ObjectMap, why: *Why) !Text { return error.Unsupported; }; try layerTypes(o, t.layers, why); + if (o.get("loop_config")) |_| t.loop = try parseLoop(try object(o, "loop_config", why), t.layers, t.block, why); return t; } @@ -311,7 +364,7 @@ fn parseMtp(o: std.json.ObjectMap, t: *const Text, why: *Why) !Mtp { m.local[@intCast(e.integer)] = true; } for (taps.array.items) |e| { - if (e != .integer or e.integer < 0 or e.integer > t.layers) { + if (e != .integer or e.integer < 0 or e.integer > t.visitCount()) { why.set("mtp_config's target_layer_ids names a layer the backbone does not have", .{}); return error.Layout; } @@ -349,15 +402,26 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, why: *Why) !Config { } const o = parsed.value.object; const arch = o.get("architectures"); - const ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string and - std.mem.eql(u8, arch.?.array.items[0].string, "Inkling2ForConditionalGeneration"); - if (!ok or !std.mem.eql(u8, text(o, "model_type") orelse "", "inkling2")) { - why.set("not an Inkling 2 checkpoint: architectures Inkling2ForConditionalGeneration, model_type inkling2", .{}); + const arch_ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string; + const arch_name: []const u8 = if (arch_ok) arch.?.array.items[0].string else ""; + const model_name = text(o, "model_type") orelse ""; + const small = std.mem.eql(u8, arch_name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2"); + const looped = std.mem.eql(u8, arch_name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2_loop"); + if (!small and !looped) { + why.set("not an Inkling 2 checkpoint: Small or Mini model_type and architectures must match", .{}); return error.NotInkling2; } try fixed(o, "tie_word_embeddings", false, why); try quantization(o, why); const t = try parseText(try object(o, "text_config", why), why); + if (looped and t.loop == null) { + why.set("inkling2_loop requires text_config.loop_config", .{}); + return error.BadConfig; + } + if (small and t.loop != null) { + why.set("loop_config requires the inkling2_loop model and architecture", .{}); + return error.Unsupported; + } const eos = try int(o, "eos_token_id", why); if (eos >= t.vocab) { why.set("eos_token_id is not a token of the {d}-token vocabulary", .{t.vocab}); diff --git a/zig/src/families/inkling2/config_test.zig b/zig/src/families/inkling2/config_test.zig index 3d24d543b66..a8ad85ab3c7 100644 --- a/zig/src/families/inkling2/config_test.zig +++ b/zig/src/families/inkling2/config_test.zig @@ -5,6 +5,7 @@ const config = @import("config.zig"); const t = std.testing; pub const real = @embedFile("fixtures/config.json"); pub const tiny = @embedFile("fixtures/tiny_config.json"); +pub const mini = @embedFile("fixtures/mini_config.json"); fn refused(json: []const u8, from: []const u8, to: []const u8, want: anyerror, says: []const u8) !void { if (std.mem.count(u8, json, from) != 1) return error.EditAnchor; @@ -46,6 +47,40 @@ test "Inkling 2 Small's config.json parses: 48 layers, 8 global, 384 experts, 8 try t.expectEqualSlices(bool, &.{ true, true, false, true, true }, m.local[0..5]); } +test "Inkling 2 Mini's config.json parses: 24 weight layers, 48 visits and four drafter taps" { + var why: config.Why = .{}; + const c = try config.parse(t.allocator, mini, &why); + try t.expectEqual(@as(u32, 2304), c.text.hidden); + try t.expectEqual(@as(u32, 24), c.text.layers); + try t.expectEqual(@as(u32, 48), c.text.visitCount()); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.global); + try t.expectEqual(@as(u32, 8192), c.text.log_floor); + try t.expectEqual(@as(u32, 128), c.text.experts); + try t.expectEqual(@as(u32, 1152), c.text.expert_inter); + try t.expectEqual(@as(f32, 8), c.text.route_scale); + const loop = c.text.loop.?; + try t.expectEqual(@as(u32, 6), loop.core_start); + try t.expectEqual(@as(u32, 18), loop.core_end); + try t.expectEqual(@as(u32, 3), loop.passes); + try t.expectEqual(@as(u32, 64), loop.gate_rank); + try t.expectEqual(@as(u32, 2304), c.vision.text_hidden); + const m = c.mtp.?; + try t.expectEqual(@as(u32, 3), m.layers); + try t.expectEqual(@as(u32, 9216), m.inter); + try t.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, m.taps[0..m.taps_n]); + try t.expectEqualSlices(bool, &.{ true, false, true }, m.local[0..3]); +} + +test "loop layouts the engine does not run are refused by their config key" { + try refused(mini, "\"is_varloop\": false", "\"is_varloop\": true", error.Unsupported, "is_varloop must be false"); + try refused(mini, "\"core_start\": 6", "\"core_start\": 0", error.Layout, "must start after layer 0"); + try refused(mini, "\"core_start\": 6", "\"core_start\": 7", error.Layout, "multiples of the 6-layer"); + try refused(mini, "\"core_end\": 18", "\"core_end\": 24", error.Layout, "multiples of the 6-layer"); + try refused(mini, "\"core_end\": 18,", "\"core_end\": 30,", error.Layout, "fit inside the 24 physical layers"); + try refused(mini, "Inkling2LoopForConditionalGeneration", "Inkling2ForConditionalGeneration", error.NotInkling2, "model_type and architectures must match"); + try refused(mini, "\"model_type\": \"inkling2_loop\"", "\"model_type\": \"inkling2\"", error.NotInkling2, "model_type and architectures must match"); +} + test "tiny-random's config.json parses: 12 layers, 96 experts, width 128, no quantization_config" { var why: config.Why = .{}; const c = try config.parse(t.allocator, tiny, &why); diff --git a/zig/src/families/inkling2/fixtures/mini_config.json b/zig/src/families/inkling2/fixtures/mini_config.json new file mode 100644 index 00000000000..e6c170c3fb6 --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_config.json @@ -0,0 +1,122 @@ +{ + "dtype": "bfloat16", + "architectures": [ + "Inkling2LoopForConditionalGeneration" + ], + "model_type": "inkling2_loop", + "eos_token_id": 200006, + "text_config": { + "model_type": "inkling2_loop_text", + "model_max_length": 1048576, + "torch_dtype": "bfloat16", + "hidden_size": 2304, + "num_hidden_layers": 24, + "vocab_size": 201024, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "d_rel": 16, + "rel_extent": 1024, + "q_bias": false, + "o_bias": false, + "log_scaling_n_floor": 8192, + "log_scaling_alpha": 0.1, + "rms_norm_eps": 1e-06, + "use_value_norm_no_gamma": true, + "qk_l2_clip_threshold": 22.627416997969522, + "rel_l2_clip_threshold": 8.0, + "local_layer_ids": [ + 0, + 1, + 2, + 3, + 4, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22 + ], + "sconv_kernel_size": 4, + "unpadded_vocab_size": 200058, + "final_logit_softcapping": 30.0, + "swa_head_dim": 128, + "swa_num_attention_heads": 24, + "swa_num_key_value_heads": 8, + "sliding_window_size": 1024, + "n_layers_per_attn_res_block": 6, + "attn_res_normalize_values": true, + "n_routed_experts": 128, + "num_experts_per_tok": 8, + "n_shared_experts": 0, + "intermediate_size": 1152, + "mlp_gate_softcap": 4.0, + "mlp_up_softcap": 25.0, + "route_scale": 8.0, + "use_gate_bias": true, + "loop_config": { + "core_start": 6, + "core_end": 18, + "num_passes": 3, + "gate_rank": 64, + "is_varloop": false + } + }, + "vision_config": { + "model_type": "inkling2_vision", + "text_hidden_size": 2304, + "temporal_patch_size": 2, + "native_patch_size": 20, + "adapter_merge_size": 2, + "projection_hidden_dim": 4096, + "projector_bias": false, + "hidden_size": 1024, + "num_hidden_layers": 23, + "num_attention_heads": 16, + "mlp_ratio": 4.0, + "posemb_grid_size": 32, + "layer_norm_eps": 1e-05 + }, + "mtp_config": { + "hidden_size": 2304, + "num_hidden_layers": 3, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "intermediate_size": 9216, + "max_position_embeddings": 1048576, + "torch_dtype": "bfloat16", + "q_bias": false, + "o_bias": false, + "rms_norm_eps": 1e-06, + "rope_theta": 1000000.0, + "local_layer_ids": [ + 0, + 2 + ], + "sliding_window_size": 1024, + "block_size": 8, + "markov_rank": 256, + "markov_head_type": "rnn_hidden", + "target_layer_ids": [ + 5, + 23, + 41, + 48 + ] + }, + "quantization_config": { + "quant_method": "modelopt", + "quant_algo": "NVFP4" + } +} diff --git a/zig/src/families/inkling2/fixtures/mini_model_header.txt b/zig/src/families/inkling2/fixtures/mini_model_header.txt new file mode 100644 index 00000000000..679d035c9eb --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_model_header.txt @@ -0,0 +1,86 @@ +inkling2-mini-model 1244 dfcec4225659aceabe432e4daadb4e6291f3718e2015d412f97f60200de32141 +model.llm.attn_res.attn_queries.{L} F32 3x2304 4,10,16,22 +model.llm.attn_res.attn_queries.{L} F32 2304 0-3,5-9,11-15,17-21 +model.llm.attn_res.mlp_queries.{L} F32 2304 0-23 +model.llm.attn_res.output_query F32 2304 +model.llm.embed.weight BF16 201024x2304 +model.llm.embed_norm.weight BF16 2304 +model.llm.layers.{L}.attn.attn_sink_proj.weight BF16 24x2304 0-23 +model.llm.layers.{L}.attn.gate_attn.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.k_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.k_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.k_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.q_l2_clip.scale BF16 24x128 0-23 +model.llm.layers.{L}.attn.rel_l2_clip.scale BF16 24x16 0-23 +model.llm.layers.{L}.attn.rel_logits_proj.proj BF16 16x1024 0-23 +model.llm.layers.{L}.attn.v_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.v_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.v_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.wk_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn.wo_ud.weight BF16 2304x3072 0-23 +model.llm.layers.{L}.attn.wq_du.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.wr_du.weight BF16 384x2304 0-23 +model.llm.layers.{L}.attn.wv_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn_norm.weight BF16 2304 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.controllers.attn.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.attn.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.attn.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.k.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.mlp.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.v.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.k_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.mlp.experts.w13_weight F8_E4M3 128x2304x2304 20-23 +model.llm.layers.{L}.mlp.experts.w13_weight U8 128x2304x1152 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale F8_E4M3 128x2304x144 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale U8 128x2304x72 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight F8_E4M3 128x2304x1152 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight U8 128x2304x576 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale F8_E4M3 128x2304x72 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale U8 128x2304x36 20-23 +model.llm.layers.{L}.mlp.gate.bias F32 128 0-23 +model.llm.layers.{L}.mlp.gate.weight BF16 128x2304 0-23 +model.llm.layers.{L}.mlp_norm.weight BF16 2304 0-23 +model.llm.layers.{L}.mlp_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.q_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.v_input_norm.weight BF16 2304 5,11,17,23 +model.llm.middle_cycle_cross_pass_kv_queries F32 24x2304 +model.llm.middle_cycle_cross_pass_queries F32 24x2304 +model.llm.norm.weight BF16 2304 +model.llm.unembed.weight BF16 201024x2304 +model.visual.backbone.embeddings.class_embedding BF16 1024 +model.visual.backbone.embeddings.cls_position_embedding BF16 1024 +model.visual.backbone.embeddings.patch_embedding.weight BF16 1024x1200 +model.visual.backbone.embeddings.position_embedding BF16 1024x1024 +model.visual.backbone.layers.{L}.ln_1.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_1.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_1.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_2.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.bias BF16 4096 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.weight BF16 4096x1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.weight BF16 1024x4096 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.ln_pre.bias BF16 1024 +model.visual.backbone.ln_pre.weight BF16 1024 +model.visual.proj_in.weight BF16 4096x4096 +model.visual.proj_out.weight BF16 2304x4096 diff --git a/zig/src/families/inkling2/fixtures/mini_mtp_header.txt b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt new file mode 100644 index 00000000000..618bdca1e6e --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt @@ -0,0 +1,25 @@ +inkling2-mini-mtp 54 f962cd87735ebbd1af0639f7513f99eed98b61d8a30b083fb33fc1bb1c3a70d1 +fuse_weight BF16 4x4 +layers.{L}.dflare_norm.weight BF16 2304 0-2 +layers.{L}.input_layernorm.weight BF16 2304 0-2 +layers.{L}.mlp.down_proj.weight BF16 2304x9216 0-2 +layers.{L}.mlp.gate_proj.weight BF16 9216x2304 0-2 +layers.{L}.mlp.up_proj.weight BF16 9216x2304 0-2 +layers.{L}.post_attention_layernorm.weight BF16 2304 0-2 +layers.{L}.self_attn.k_norm.weight BF16 128 0-2 +layers.{L}.self_attn.k_norm_ctx.weight BF16 128 0-2 +layers.{L}.self_attn.k_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.k_proj_ctx.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.o_proj.weight BF16 2304x3072 0-2 +layers.{L}.self_attn.q_norm.weight BF16 128 0-2 +layers.{L}.self_attn.q_proj.weight BF16 3072x2304 0-2 +layers.{L}.self_attn.v_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.v_proj_ctx.weight BF16 1024x2304 0-2 +markov_head.dflare_norm.weight BF16 2304 +markov_head.hidden_out.bias BF16 2304 +markov_head.hidden_out.weight BF16 2304x256 +markov_head.markov_w1.weight BF16 201024x256 +markov_head.rnn_proj.bias BF16 768 +markov_head.rnn_proj.weight BF16 768x5120 +mask_embed BF16 2304 +norm.weight BF16 2304 diff --git a/zig/src/families/inkling2/names.zig b/zig/src/families/inkling2/names.zig index 3c75db572bf..e4451ce7bf2 100644 --- a/zig/src/families/inkling2/names.zig +++ b/zig/src/families/inkling2/names.zig @@ -1,4 +1,4 @@ -//! Inkling 2 Small's weight map: each tensor the config implies, with dtype and shape, checked against headers. +//! Inkling 2 weight maps: each tensor the config implies, with dtype and shape, checked against headers. const std = @import("std"); const st = @import("safetensors"); const config = @import("config.zig"); @@ -77,6 +77,19 @@ fn experts(c: *const Text, i: u32, prec: plan.Precision, sink: anytype) !void { } } +fn controllers(c: *const Text, i: u32, sink: anytype) !void { + const loop = c.loop orelse return; + if (i < loop.core_start or i >= loop.core_end) return; + const rank: u64 = loop.gate_rank; + const h: u64 = c.hidden; + const L = .{i}; + inline for (.{ "attn", "k", "mlp", "v" }) |kind| { + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".down_weight", L, .bf16, &.{ rank, 2 * h }); + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".forget_weight", L, .bf16, &.{ h, rank }); + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".gain_weight", L, .bf16, &.{ h, rank }); + } +} + fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { const h: u64 = c.hidden; try put(sink, "model.llm.embed.weight", .{}, .bf16, &.{ c.vocab, h }); @@ -84,6 +97,11 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.norm.weight", .{}, .bf16, &.{h}); try put(sink, "model.llm.unembed.weight", .{}, .bf16, &.{ c.vocab, h }); try put(sink, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); + if (c.loop) |loop| { + const rows = 2 * @as(u64, loop.core_end - loop.core_start); + try put(sink, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ rows, h }); + try put(sink, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ rows, h }); + } for (0..c.layers) |k| { const i: u32 = @intCast(k); try put(sink, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{h}); @@ -93,6 +111,7 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); } try attention(c, i, sink); + try controllers(c, i, sink); try put(sink, "model.llm.layers.{d}.attn_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); try put(sink, "model.llm.layers.{d}.mlp_norm.weight", .{i}, .bf16, &.{h}); try put(sink, "model.llm.layers.{d}.mlp_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); @@ -131,8 +150,8 @@ fn draft(m: config.Mtp, text: *const Text, sink: anytype) !void { const q: u64 = @as(u64, m.q_heads) * m.head_dim; const kv: u64 = @as(u64, m.kv_heads) * m.head_dim; const rank: u64 = m.rank; - // fuse_weight's six rows do not follow from the config, so any row count passes - try put(sink, "fuse_weight", .{}, .bf16, &.{ any, m.taps_n }); + // One fusion row per draft layer plus the Markov head, one column per target visit tap. + try put(sink, "fuse_weight", .{}, .bf16, &.{ m.layers + 1, m.taps_n }); try put(sink, "mask_embed", .{}, .bf16, &.{h}); try put(sink, "norm.weight", .{}, .bf16, &.{h}); try put(sink, "markov_head.dflare_norm.weight", .{}, .bf16, &.{h}); diff --git a/zig/src/families/inkling2/names_test.zig b/zig/src/families/inkling2/names_test.zig index c5eb215d86b..0b9bcb0124b 100644 --- a/zig/src/families/inkling2/names_test.zig +++ b/zig/src/families/inkling2/names_test.zig @@ -1,4 +1,5 @@ -//! The weight map and layer plan against the tiny-random checkpoint's safetensors headers (fixtures fold them). +//! Weight maps and layer plans against safetensors headers (fixtures fold them). + const std = @import("std"); const config = @import("config.zig"); const config_test = @import("config_test.zig"); @@ -9,6 +10,8 @@ const plan = @import("plan.zig"); const t = std.testing; const model_fixture = @embedFile("fixtures/tiny_model_header.txt"); const mtp_fixture = @embedFile("fixtures/tiny_mtp_header.txt"); +const mini_model_fixture = @embedFile("fixtures/mini_model_header.txt"); +const mini_mtp_fixture = @embedFile("fixtures/mini_mtp_header.txt"); fn byName(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b); @@ -78,6 +81,11 @@ fn load(a: std.mem.Allocator) !config.Config { return config.parse(a, config_test.tiny, &why); } +fn loadMini(a: std.mem.Allocator) !config.Config { + var why: config.Why = .{}; + return config.parse(a, config_test.mini, &why); +} + test "the folded fixtures unfold to the 404 and 84 tensors of tiny's two files, digests equal" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -85,6 +93,13 @@ test "the folded fixtures unfold to the 404 and 84 tensors of tiny's two files, try t.expectEqual(@as(usize, 84), (try unfold(arena.allocator(), mtp_fixture, "inkling2-tiny-mtp")).count()); } +test "Mini's folded fixtures unfold to the 1244 and 54 tensors of its two files, digests equal" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + try t.expectEqual(@as(usize, 1244), (try unfold(arena.allocator(), mini_model_fixture, "inkling2-mini-model")).count()); + try t.expectEqual(@as(usize, 54), (try unfold(arena.allocator(), mini_mtp_fixture, "inkling2-mini-mtp")).count()); +} + test "the map names exactly tiny's backbone and vision tensors, with their dtypes and shapes" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -108,6 +123,19 @@ test "the map names exactly tiny's draft head tensors" { try t.expect(r.clean()); } +test "Mini's config parses and the map names exactly its model and draft tensors" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try loadMini(a); + const model = try names.check(a, &c, try unfold(a, mini_model_fixture, "inkling2-mini-model"), .model); + try t.expectEqual(@as(usize, 1244), model.expected); + try t.expect(model.clean()); + const mtp = try names.check(a, &c, try unfold(a, mini_mtp_fixture, "inkling2-mini-mtp"), .mtp); + try t.expectEqual(@as(usize, 54), mtp.expected); + try t.expect(mtp.clean()); +} + test "a missing tensor, a wrong shape, a wrong dtype and an unknown tensor are each reported by name" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -177,6 +205,15 @@ test "expert precision follows each layer's tensors: NVFP4 on layers 0 to 5, MXF try t.expectError(error.ExpertFormat, names.precisions(bad, 12, &prec)); } +test "Mini's expert precision is NVFP4 on layers 0 to 19 and MXFP8 on 20 to 23" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const entries = try unfold(arena.allocator(), mini_model_fixture, "inkling2-mini-model"); + var prec: [24]plan.Precision = undefined; + try names.precisions(entries, 24, &prec); + for (prec, 0..) |p, i| try t.expectEqual(if (i < 20) plan.Precision.nvfp4 else plan.Precision.mxfp8, p); +} + test "the plan: global layers 5 and 11, blocks of six, three attention queries before each global layer" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -199,6 +236,38 @@ test "the plan: global layers 5 and 11, blocks of six, three attention queries b try t.expectEqual(@as(u32, 3), p.at(11).attn_sources); try t.expectEqual(@as(u32, 3), p.final_sources); try t.expectError(error.PrecisionCount, plan.build(&c.text, prec[0..11])); + try t.expectEqual(@as(u32, 12), p.n_visits); + for (0..p.n_visits) |i| { + const v = p.visit(@intCast(i)); + try t.expectEqual(@as(u32, @intCast(i)), v.layer); + try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try t.expect(!v.hasMessages()); + } +} + +test "Mini's visit plan repeats only the core, gives all 48 visits private state and banks the previous pass" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try loadMini(a); + var prec: [24]plan.Precision = undefined; + try names.precisions(try unfold(a, mini_model_fixture, "inkling2-mini-model"), 24, &prec); + const p = try plan.build(&c.text, &prec); + try t.expectEqual(@as(u32, 48), p.n_visits); + try t.expectEqual(@as(u32, 8), p.visitCount(.global)); + try t.expectEqual(@as(u32, 40), p.visitCount(.local)); + for (0..p.n_visits) |i| { + const v = p.visit(@intCast(i)); + const layer: u32 = if (i < 6) @intCast(i) else if (i < 42) 6 + @as(u32, @intCast((i - 6) % 12)) else @intCast(i - 24); + const pass: u32 = if (i >= 6 and i < 42) 1 + @as(u32, @intCast((i - 6) / 12)) else 0; + try t.expectEqual(layer, v.layer); + try t.expectEqual(pass, v.pass); + try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try t.expectEqual(pass >= 2, v.hasMessages()); + const previous: ?u32 = if (pass == 2) 6 else if (pass == 3) 18 else null; + try t.expectEqual(previous, v.previous_core_start); + } + try t.expectEqual(@as(u32, 5), p.final_sources); } /// A file's header through the core reader; the files may hold the header alone, so no data length is checked. diff --git a/zig/src/families/inkling2/plan.zig b/zig/src/families/inkling2/plan.zig index c2327d26bef..86effc0c4a3 100644 --- a/zig/src/families/inkling2/plan.zig +++ b/zig/src/families/inkling2/plan.zig @@ -19,27 +19,64 @@ pub const Layer = struct { precision: Precision, }; +pub const Visit = struct { + layer: u32, // physical weight layer; core layers repeat with the same weights + pass: u32, // zero outside the core, otherwise one-based loop pass + cache_slot: u32, // this visit's private KV and four short-convolution states + previous_core_start: ?u32, // previous pass's first visit; its two bank states feed this visit's messages + + pub fn hasMessages(v: Visit) bool { + return v.previous_core_start != null; + } +}; + pub const Plan = struct { layers: [config.max_layers]Layer, n: u32, + visits: [config.max_visits]Visit, + n_visits: u32, final_sources: u32, // the output query's states: every finished block and the last layer's output pub fn at(p: *const Plan, i: u32) *const Layer { return &p.layers[i]; } + pub fn visit(p: *const Plan, i: u32) *const Visit { + return &p.visits[i]; + } + pub fn count(p: *const Plan, kind: Kind) u32 { var k: u32 = 0; for (p.layers[0..p.n]) |l| k += @intFromBool(l.kind == kind); return k; } + + pub fn visitCount(p: *const Plan, kind: Kind) u32 { + var k: u32 = 0; + for (p.visits[0..p.n_visits]) |v| k += @intFromBool(p.layers[v.layer].kind == kind); + return k; + } }; /// The plan for a parsed config and each layer's expert precision (`prec` holds one entry per layer). +fn appendVisit(p: *Plan, c: *const config.Text, layer: u32, pass: u32) void { + const previous: ?u32 = if (c.loop) |core| + (if (pass >= 2) core.core_start + (pass - 2) * (core.core_end - core.core_start) else null) + else + null; + p.visits[p.n_visits] = .{ + .layer = layer, + .pass = pass, + .cache_slot = p.n_visits, + .previous_core_start = previous, + }; + p.n_visits += 1; +} pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCount}!Plan { if (prec.len != c.layers) return error.PrecisionCount; var p: Plan = undefined; p.n = c.layers; + p.n_visits = 0; for (0..c.layers) |k| { const i: u32 = @intCast(k); const boundary = i % c.block == 0; @@ -58,5 +95,12 @@ pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCoun }; } p.final_sources = (c.layers + c.block - 1) / c.block + 1; + if (c.loop) |loop| { + for (0..loop.core_start) |i| appendVisit(&p, c, @intCast(i), 0); + for (1..loop.passes + 1) |pass| for (loop.core_start..loop.core_end) |i| appendVisit(&p, c, @intCast(i), @intCast(pass)); + for (loop.core_end..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); + } else { + for (0..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); + } return p; } From 0841f67f9d0b97800b3731ba3ac4a4d88357b37e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:38:22 +0000 Subject: [PATCH 10/84] inkling2: model the Mini loop on the host Derive per-visit cache access and exact arithmetic for the 48 visits so CUDA admission and kernels have a reference before serving is enabled. --- zig/src/families/inkling2/host_test.zig | 3 + zig/src/families/inkling2/inkling2.zig | 4 + zig/src/families/inkling2/loop.zig | 154 ++++++ zig/src/families/inkling2/loop_model.zig | 464 ++++++++++++++++++ zig/src/families/inkling2/loop_model_test.zig | 214 ++++++++ 5 files changed, 839 insertions(+) create mode 100644 zig/src/families/inkling2/loop.zig create mode 100644 zig/src/families/inkling2/loop_model.zig create mode 100644 zig/src/families/inkling2/loop_model_test.zig diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 4f8b47e83b3..5caed096fef 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -5,6 +5,9 @@ test { _ = @import("names.zig"); _ = @import("names_test.zig"); _ = @import("plan.zig"); + _ = @import("loop.zig"); + _ = @import("loop_model.zig"); + _ = @import("loop_model_test.zig"); _ = @import("prompt.zig"); _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 556bca61b13..4185398f138 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -2,6 +2,8 @@ pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); +pub const loop = @import("loop.zig"); +pub const loop_model = @import("loop_model.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -9,4 +11,6 @@ pub const model_type = "inkling2"; test { _ = kernels; _ = ops; + _ = loop; + _ = loop_model; } diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig new file mode 100644 index 00000000000..7c6e8db290f --- /dev/null +++ b/zig/src/families/inkling2/loop.zig @@ -0,0 +1,154 @@ +//! Inkling 2 Mini's loop host layout: 48 private visit caches, whole-state snapshots and one-rank admission. +const std = @import("std"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); + +pub fn validateLoad(c: *const config.Config, rank: usize, images: bool) !void { + if (rank != 1) return error.Inkling2LoopOneRankOnly; + if (images) return error.Inkling2LoopTextOnly; + const lp = c.text.loop orelse return error.Inkling2LoopRequired; + if (lp.gate_rank != 64) return error.UnsupportedLoopGateRank; +} + +pub const SnapshotSlot = struct { + kv_offset: u64, + kv_bytes: u64, + conv_offset: u64, + conv_bytes: u64, +}; + +/// A stream or a saved prompt owns the same complete layout: no visit shares KV or convolution state with another. +pub const CacheLayout = struct { + slots: [config.max_visits]SnapshotSlot, + n: u32, + bytes: u64, + + pub fn init(c: *const config.Text, p: *const plan_.Plan, context: u32) !CacheLayout { + if (context == 0 or context > c.max_context or p.n_visits != c.visitCount()) return error.BadLoopCache; + var out: CacheLayout = undefined; + out.n = p.n_visits; + out.bytes = 0; + const conv_values = 3 * (2 * @as(u64, c.local.kv * c.local.dim) + 2 * @as(u64, c.hidden)); + for (p.visits[0..p.n_visits], 0..) |visit, i| { + const layer = p.layers[visit.layer]; + const rows: u32 = @intCast(@min(2048, context)); + const tokens = if (layer.kind == .global) + std.mem.alignForward(u32, context, 64) + else + std.mem.alignForward(u32, c.window + rows - 1, 64); + const kv = try std.math.mul(u64, tokens, 2 * @as(u64, layer.heads.kv * layer.heads.dim * 2)); + // The recurrence rounds each site then widens its complete state to FP32 before the FMAs. + const conv = try std.math.mul(u64, conv_values, 4); + out.slots[i] = .{ .kv_offset = out.bytes, .kv_bytes = kv, .conv_offset = 0, .conv_bytes = conv }; + out.bytes = try std.math.add(u64, out.bytes, kv); + } + var conv_offset = out.bytes; + for (out.slots[0..out.n]) |*slot| { + slot.conv_offset = conv_offset; + conv_offset = try std.math.add(u64, conv_offset, slot.conv_bytes); + } + out.bytes = conv_offset; + return out; + } + + pub fn at(l: *const CacheLayout, visit: u32) SnapshotSlot { + return l.slots[visit]; + } +}; + +/// The serial lane adapter's admission rule. One request occupies one complete 48-visit stream. +pub const Admission = struct { + context: u32, + + pub fn fits(a: Admission, prompt: u32, max_tokens: u32) bool { + return prompt <= a.context and max_tokens <= a.context - prompt; + } +}; + +/// A prompt-cache save or restore copies every byte of this layout, including all four convolution recurrences. +pub fn snapshotBytes(l: *const CacheLayout) u64 { + return l.bytes; +} + +pub const Snapshot = struct { + bytes: []u8, + + pub fn save(gpa: std.mem.Allocator, state: []const u8, l: *const CacheLayout) !Snapshot { + if (state.len != l.bytes) return error.BadLoopSnapshot; + return .{ .bytes = try gpa.dupe(u8, state) }; + } + + pub fn restore(s: *const Snapshot, state: []u8, l: *const CacheLayout) !void { + if (s.bytes.len != l.bytes or state.len != l.bytes) return error.BadLoopSnapshot; + @memcpy(state, s.bytes); + } + + pub fn deinit(s: *Snapshot, gpa: std.mem.Allocator) void { + gpa.free(s.bytes); + s.* = undefined; + } +}; + +test "a saved prompt restores every visit byte and owns its copy" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const layout = try CacheLayout.init(&c.text, &p, 1); + const state = try std.testing.allocator.alloc(u8, @intCast(layout.bytes)); + defer std.testing.allocator.free(state); + for (state, 0..) |*v, i| v.* = @truncate(i * 29 + 7); + var saved = try Snapshot.save(std.testing.allocator, state, &layout); + defer saved.deinit(std.testing.allocator); + @memset(state, 0xa5); + try saved.restore(state, &layout); + try std.testing.expectEqualSlices(u8, saved.bytes, state); + try std.testing.expectError(error.BadLoopSnapshot, Snapshot.save(std.testing.allocator, state[0 .. state.len - 1], &layout)); +} + +test "Mini has 48 independent KV and convolution slots and a whole-state snapshot" { + const config_test = @import("config_test.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var why: config.Why = .{}; + const c = try config.parse(a, config_test.mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const layout = try CacheLayout.init(&c.text, &p, 1_048_576); + try std.testing.expectEqual(@as(u32, 48), layout.n); + try std.testing.expectEqual(@as(u64, 3072 * 2 * 8 * 128 * 2), layout.at(0).kv_bytes); + try std.testing.expectEqual(@as(u64, 1_048_576 * 2 * 8 * 128 * 2), layout.at(5).kv_bytes); + try std.testing.expectEqual(@as(u64, 34_866_888_704), layout.bytes); + try std.testing.expectEqual(layout.bytes, snapshotBytes(&layout)); + try std.testing.expect((Admission{ .context = 8192 }).fits(8000, 192)); + try std.testing.expectEqual(@as(u64, 79_872), layout.at(0).conv_bytes); +} + +test "Mini loop load is one-rank text-only with rank-64 gated controllers" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + try validateLoad(&c, 1, false); + try std.testing.expectError(error.Inkling2LoopOneRankOnly, validateLoad(&c, 2, false)); + try std.testing.expectError(error.Inkling2LoopTextOnly, validateLoad(&c, 1, true)); +} + +test "pass two resets and only completed passes with a successor capture message banks" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const lp = c.text.loop.?; + var banks: u32 = 0; + for (p.visits[0..p.n_visits]) |visit| { + if (visit.pass == 2 and visit.layer == lp.core_start) try std.testing.expect(visit.hasMessages()); + if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) banks += 1; + } + try std.testing.expectEqual(lp.passes - 1, banks); +} diff --git a/zig/src/families/inkling2/loop_model.zig b/zig/src/families/inkling2/loop_model.zig new file mode 100644 index 00000000000..c56b1ce7a2e --- /dev/null +++ b/zig/src/families/inkling2/loop_model.zig @@ -0,0 +1,464 @@ +//! f64 Mini: f32 sums/combine ascend (A12), bf16 experts/acts (A1/A2), f32 F/G (A7), postdot scale (A14); casts round. +const std = @import("std"); +const bf = @import("bf16_round"); + +pub const hidden_size = 2304; +pub const gate_rank = 64; +pub const physical_layers = 24; +pub const core_start = 6; +pub const core_end = 18; +pub const core_layers = core_end - core_start; +pub const num_passes = 3; +pub const visit_count = 48; +pub const message_roles = 4; +pub const rms_eps = 1e-6; + +pub const ShapeError = error{BadShape}; +pub const VisitError = error{BadVisit}; +pub const DriverError = error{ BadShape, BadVisit, BadDriverState, BadSequence }; + +fn narrow32(v: f64) f32 { + return @floatCast(v); +} + +fn widen32(v: f32) f64 { + return @floatCast(v); +} + +/// One round to nearest-even bf16; the returned f64 is exactly that bf16 value. +pub fn bf16(v: f64) f64 { + return bf.bf16(v); +} + +/// rho(x), with an f32 ordered sum of squares and the specified f32 mean/rsqrt/multiply. +pub fn rms(x: []const f64, eps: f64, out: []f64) ShapeError!void { + if (x.len == 0 or out.len != x.len or !std.math.isFinite(eps) or eps < 0) return error.BadShape; + var squares: f32 = 0; + for (x) |v| { + const a = narrow32(v); + squares += a * a; + } + const mean = squares / @as(f32, @floatFromInt(x.len)); + const inverse: f32 = 1 / @sqrt(mean + narrow32(eps)); + for (x, out) |v, *o| o.* = widen32(narrow32(v) * inverse); +} + +/// N_w(x): no bf16 rounding between rho and the weight product, one bf16 rounding at the end. +pub fn weightedRms(x: []const f64, weight: []const f64, eps: f64, out: []f64, scratch: []f64) ShapeError!void { + if (weight.len != x.len or scratch.len != x.len) return error.BadShape; + try rms(x, eps, scratch); + for (scratch, weight, out) |v, w, *o| o.* = bf16(widen32(narrow32(w) * narrow32(v))); +} + +/// binary32(1/sqrt(H)); in particular Mini's value is binary32(1/48), not a double scale. +pub fn residualScale(hidden: usize) ShapeError!f32 { + if (hidden == 0) return error.BadShape; + return narrow32(1 / @sqrt(@as(f64, @floatFromInt(hidden)))); +} + +fn normalizeSources(states: []const f64, partial: []const f64, eps: f64, normalized: []f64) ShapeError!usize { + if (partial.len == 0 or states.len % partial.len != 0) return error.BadShape; + const h = partial.len; + const count = states.len / h + 1; + if (normalized.len != count * h) return error.BadShape; + for (0..count - 1) |i| try rms(states[i * h ..][0..h], eps, normalized[i * h ..][0..h]); + try rms(partial, eps, normalized[(count - 1) * h ..][0..h]); + return count; +} + +fn retrieve(normalized: []const f64, query: []const f64, out: []f64, weights: []f64) ShapeError!void { + if (query.len == 0 or out.len != query.len or normalized.len % query.len != 0) return error.BadShape; + const h = query.len; + const count = normalized.len / h; + if (count == 0 or weights.len != count) return error.BadShape; + const scale = try residualScale(h); + var top: f32 = -std.math.inf(f32); + for (0..count) |i| { + var dot: f32 = 0; + for (query, normalized[i * h ..][0..h]) |q, v| dot += narrow32(q) * narrow32(v); + const logit = dot * scale; + weights[i] = widen32(logit); + top = @max(top, logit); + } + var denominator: f32 = 0; + for (weights) |*w| { + const d = narrow32(w.* - widen32(top)); + const e = @exp(d); + w.* = widen32(e); + denominator += e; + } + @memset(out, 0); + for (0..count) |i| { + const weight = narrow32(weights[i]) / denominator; + for (out, normalized[i * h ..][0..h]) |*o, v| { + const a = narrow32(o.*); + o.* = widen32(a + weight * narrow32(v)); + } + } +} + +/// AR_Q(S,p): states[S][H], queries/out[Q][H] row-major; empty S okay, partial last, normalize before attention. +pub fn attentionResidual(gpa: std.mem.Allocator, states: []const f64, partial: []const f64, queries: []const f64, query_rows: usize, eps: f64, out: []f64) !void { + if (partial.len == 0 or query_rows == 0 or states.len % partial.len != 0) return error.BadShape; + const h = partial.len; + if (queries.len != query_rows * h or out.len != queries.len) return error.BadShape; + const count = states.len / h + 1; + const normalized = try gpa.alloc(f64, count * h); + defer gpa.free(normalized); + const weights = try gpa.alloc(f64, count); + defer gpa.free(weights); + _ = try normalizeSources(states, partial, eps, normalized); + for (0..query_rows) |q| try retrieve(normalized, queries[q * h ..][0..h], out[q * h ..][0..h], weights); +} + +pub const MessageRole = enum(u2) { q = 0, k = 1, v = 2, mlp = 3 }; + +/// The previous pass's B_12 and P_18. No embedding, prelude, or current-pass state is included. +pub const MessageBank = struct { + block: []const f64, + partial: []const f64, +}; + +/// Both checkpoint tensors in their stored row-major layouts: 24 rows by H. +pub const MessageQueries = struct { + q_mlp: []const f64, + kv: []const f64, + + /// Core j uses row 2j for q/k and row 2j+1 for mlp/v, in their respective tensors. + pub fn row(q: MessageQueries, core: usize, role: MessageRole, hidden: usize) ShapeError![]const f64 { + if (core >= core_layers or hidden == 0 or q.q_mlp.len != 2 * core_layers * hidden or q.kv.len != 2 * core_layers * hidden) return error.BadShape; + const odd: usize = @intFromBool(role == .mlp or role == .v); + const row_index = 2 * core + odd; + const source = if (role == .q or role == .mlp) q.q_mlp else q.kv; + return source[row_index * hidden ..][0..hidden]; + } +}; + +fn bankNormalized(gpa: std.mem.Allocator, bank: MessageBank, eps: f64) ![]f64 { + if (bank.block.len == 0 or bank.partial.len != bank.block.len) return error.BadShape; + const normalized = try gpa.alloc(f64, 2 * bank.block.len); + errdefer gpa.free(normalized); + try rms(bank.block, eps, normalized[0..bank.block.len]); + try rms(bank.partial, eps, normalized[bank.block.len..]); + return normalized; +} + +/// One of the 48 cross-pass messages. Its bank values and output are binary32 values held in f64. +pub fn crossPassMessage(gpa: std.mem.Allocator, bank: MessageBank, query: []const f64, eps: f64, out: []f64) !void { + if (query.len != bank.block.len or out.len != query.len) return error.BadShape; + const normalized = try bankNormalized(gpa, bank, eps); + defer gpa.free(normalized); + var weights: [2]f64 = undefined; + try retrieve(normalized, query, out, &weights); +} + +/// All messages in [core layer][q,k,v,mlp][H] order. Queries are shared by passes two and three. +pub fn crossPassMessages(gpa: std.mem.Allocator, bank: MessageBank, queries: MessageQueries, eps: f64, out: []f64) !void { + const h = bank.block.len; + if (h == 0 or bank.partial.len != h or out.len != core_layers * message_roles * h) return error.BadShape; + const normalized = try bankNormalized(gpa, bank, eps); + defer gpa.free(normalized); + var weights: [2]f64 = undefined; + const roles = [_]MessageRole{ .q, .k, .v, .mlp }; + for (0..core_layers) |j| for (roles, 0..) |role, r| { + const query = try queries.row(j, role, h); + const at = (j * message_roles + r) * h; + try retrieve(normalized, query, out[at..][0..h], &weights); + }; +} + +/// Mini's rank-64 controller, represented with smaller ranks too for inexpensive host probes. +pub const GateWeights = struct { + down: []const f64, // [rank][2H], with the h half before the message half + forget: []const f64, // [H][rank] + gain: []const f64, // [H][rank] + rank: usize, +}; + +fn gateDot(row: []const f64, values: []const f64) f32 { + var sum: f32 = 0; + for (row, values) |w, v| sum += narrow32(w) * narrow32(v); + return sum; +} + +/// G(h,m) = (1-f)*h + g*m. The joined norm and bottleneck are bf16; F/G stay f32 (A7). +pub fn messageGate(gpa: std.mem.Allocator, h: []const f64, m: []const f64, w: GateWeights, eps: f64, out: []f64) !void { + const width = h.len; + if (width == 0 or m.len != width or out.len != width or w.rank == 0) return error.BadShape; + if (w.down.len != w.rank * 2 * width or w.forget.len != width * w.rank or w.gain.len != width * w.rank) return error.BadShape; + const joined = try gpa.alloc(f64, 2 * width); + defer gpa.free(joined); + const zeta = try gpa.alloc(f64, w.rank); + defer gpa.free(zeta); + try rms(h, eps, joined[0..width]); + try rms(m, eps, joined[width..]); + for (joined) |*v| v.* = bf16(v.*); + for (0..w.rank) |r| zeta[r] = bf16(widen32(gateDot(w.down[r * 2 * width ..][0 .. 2 * width], joined))); + for (0..width) |i| { + const forget = std.math.tanh(gateDot(w.forget[i * w.rank ..][0..w.rank], zeta)); + const gain = std.math.tanh(gateDot(w.gain[i * w.rank ..][0..w.rank], zeta)); + const keep: f32 = 1 - forget; + const left = keep * narrow32(h[i]); + const right = gain * narrow32(m[i]); + out[i] = widen32(left + right); + } +} + +pub const AttentionKind = enum { sliding, global }; + +/// One row of the fixed 48-visit schedule. cache_slot is visit numbering; reference_slot is HF's. +pub const Visit = struct { + index: u8, + layer: u8, + pass: u8, // zero outside the core, one-based inside it + cache_slot: u8, + reference_slot: u8, + kind: AttentionKind, + boundary: bool, + has_messages: bool, + ar_queries: u8, + attention_sources: u8, + mlp_sources: u8, +}; + +pub fn visit(index: usize) VisitError!Visit { + if (index >= visit_count) return error.BadVisit; + const layer: u8 = if (index < core_start) + @intCast(index) + else if (index < 42) + @intCast(core_start + (index - core_start) % core_layers) + else + @intCast(index - 24); + const pass: u8 = if (index >= 18 and index < 42) @intCast(1 + (index - core_start) / core_layers) else if (index >= core_start and index < 18) 1 else 0; + const reference: u8 = if (pass >= 2) @intCast(24 + (@as(usize, pass) - 2) * core_layers + layer - core_start) else layer; + const global = (@as(usize, layer) + 1) % 6 == 0; + const boundary = layer % 6 == 0; + const blocks: u8 = (layer + 5) / 6; + return .{ + .index = @intCast(index), + .layer = layer, + .pass = pass, + .cache_slot = @intCast(index), + .reference_slot = reference, + .kind = if (global) .global else .sliding, + .boundary = boundary, + .has_messages = pass >= 2, + .ar_queries = if (layer == 0) 0 else if (global) 3 else 1, + .attention_sources = if (layer == 0) 0 else blocks + 1, + .mlp_sources = blocks + 1 + @intFromBool(boundary), + }; +} + +pub const Sources = struct { + blocks: []const f64, // [completed block][H] + partial: []const f64, // p before attention, or unrounded t before the MLP +}; + +/// Residual/block only; caller attention/conv/MoE. Visit: begin->attentionSources->afterAttention->mlpSources->finish. +pub const Driver = struct { + gpa: std.mem.Allocator, + hidden: usize, + storage: []f64, // blocks[4H], prelude snapshot[2H], bank[2H], p[H], t[H] + block_count: usize, + next: usize, + phase: enum { ready, attention, mlp }, + active: Visit, + have_snapshot: bool, + + pub fn init(gpa: std.mem.Allocator, embedding: []const f64) !Driver { + if (embedding.len == 0) return error.BadShape; + const h = embedding.len; + const storage = try gpa.alloc(f64, 10 * h); + @memset(storage, 0); + for (embedding, storage[8 * h .. 9 * h]) |v, *p| p.* = bf16(v); + return .{ .gpa = gpa, .hidden = h, .storage = storage, .block_count = 0, .next = 0, .phase = .ready, .active = undefined, .have_snapshot = false }; + } + + pub fn deinit(d: *Driver) void { + d.gpa.free(d.storage); + d.* = undefined; + } + + fn blocks(d: *Driver) []f64 { + return d.storage[0 .. d.block_count * d.hidden]; + } + + fn partial(d: *Driver) []f64 { + return d.storage[8 * d.hidden .. 9 * d.hidden]; + } + + fn work(d: *Driver) []f64 { + return d.storage[9 * d.hidden .. 10 * d.hidden]; + } + + /// Applies the pass reset before visits 18 and 30, after saving that previous pass's two bank states. + pub fn begin(d: *Driver, index: usize) DriverError!Visit { + if (index >= visit_count) return error.BadVisit; + if (d.phase != .ready or d.next != index) return error.BadSequence; + if (index == core_start) { + if (d.block_count != 1) return error.BadDriverState; + @memcpy(d.storage[4 * d.hidden .. 5 * d.hidden], d.partial()); + @memcpy(d.storage[5 * d.hidden .. 6 * d.hidden], d.blocks()); + d.have_snapshot = true; + } + if (index == 18 or index == 30) { + if (!d.have_snapshot or d.block_count != 3) return error.BadDriverState; + @memcpy(d.storage[6 * d.hidden .. 7 * d.hidden], d.storage[2 * d.hidden .. 3 * d.hidden]); + @memcpy(d.storage[7 * d.hidden .. 8 * d.hidden], d.partial()); + @memcpy(d.partial(), d.storage[4 * d.hidden .. 5 * d.hidden]); + @memcpy(d.storage[0..d.hidden], d.storage[5 * d.hidden .. 6 * d.hidden]); + d.block_count = 1; + } + d.active = visit(index) catch return error.BadVisit; + d.phase = .attention; + return d.active; + } + + pub fn attentionSources(d: *Driver) DriverError!Sources { + if (d.phase != .attention) return error.BadSequence; + return .{ .blocks = d.blocks(), .partial = d.partial() }; + } + + /// Saves p as a completed boundary block, then forms f32 t without rounding it to bf16. + pub fn afterAttention(d: *Driver, attention: []const f64) DriverError!void { + if (d.phase != .attention) return error.BadSequence; + if (attention.len != d.hidden) return error.BadShape; + if (d.active.boundary) { + if (d.block_count == 4) return error.BadDriverState; + @memcpy(d.storage[d.block_count * d.hidden ..][0..d.hidden], d.partial()); + d.block_count += 1; + for (d.work(), attention) |*t, a| t.* = widen32(narrow32(a)); + } else { + for (d.work(), d.partial(), attention) |*t, p, a| t.* = widen32(narrow32(p) + narrow32(a)); + } + d.phase = .mlp; + } + + /// AR's second call sees the extended block list and t, not bf16(t). + pub fn mlpSources(d: *Driver) DriverError!Sources { + if (d.phase != .mlp) return error.BadSequence; + return .{ .blocks = d.blocks(), .partial = d.work() }; + } + + /// p_out = bf16(t + f32(post-MLP-convolution output)); the residual itself is never gated. + pub fn finish(d: *Driver, mlp: []const f64) DriverError!void { + if (d.phase != .mlp) return error.BadSequence; + if (mlp.len != d.hidden) return error.BadShape; + for (d.partial(), d.work(), mlp) |*p, t, o| p.* = bf16(widen32(narrow32(t) + narrow32(o))); + d.phase = .ready; + d.next += 1; + } + + /// Raw B_12 and P_18 of the immediately previous pass; valid until the next pass reset. + pub fn messageBank(d: *Driver) DriverError!MessageBank { + if (d.phase == .ready or !d.active.has_messages) return error.BadDriverState; + return .{ .block = d.storage[6 * d.hidden .. 7 * d.hidden], .partial = d.storage[7 * d.hidden .. 8 * d.hidden] }; + } + + /// The five final AR sources after visit 47: four completed blocks and P_24. + pub fn finalSources(d: *Driver) DriverError!Sources { + if (d.phase != .ready or d.next != visit_count or d.block_count != 4) return error.BadDriverState; + return .{ .blocks = d.blocks(), .partial = d.partial() }; + } +}; + +pub fn e2m1(code: u8) f64 { + const table = [_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const magnitude = table[code & 7]; + return std.math.copysign(magnitude, if (code & 8 != 0) @as(f64, -1) else @as(f64, 1)); +} + +/// OCP E4M3FN, including its subnormals and sole NaN encodings. +pub fn e4m3(code: u8) f64 { + const negative = code & 0x80 != 0; + const exponent: u8 = (code >> 3) & 0xf; + const mantissa: u8 = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const magnitude = if (exponent == 0) + std.math.ldexp(@as(f64, @floatFromInt(mantissa)), -9) + else + std.math.ldexp(1 + @as(f64, @floatFromInt(mantissa)) / 8, @as(i32, exponent) - 7); + return if (negative) -magnitude else magnitude; +} + +/// A2(a): both source f32 scalars are cast to bf16 before one binary32 division. +pub fn nvfp4OuterFactor(amax: f64, denominator: f64) f64 { + const a = narrow32(bf16(amax)); + const d = narrow32(bf16(denominator)); + return widen32(a / d); +} + +fn nvWeight(code: u8, scale: u8, factor: f32) f64 { + const inner = narrow32(e2m1(code) * e4m3(scale)); // the E2M1*E4M3 product is exact + return bf16(widen32(inner * factor)); +} + +pub fn nvfp4ReferenceWeight(code: u8, scale: u8, amax: f64, denominator: f64) f64 { + return nvWeight(code, scale, narrow32(nvfp4OuterFactor(amax, denominator))); +} + +/// Decode one packed NVFP4 row: low nibble is the even input, one E4M3 scale per 16 inputs. +pub fn nvfp4ReferenceRow(codes: []const u8, scales: []const u8, amax: f64, denominator: f64, out: []f64) ShapeError!void { + if (out.len == 0 or out.len % 16 != 0 or codes.len != out.len / 2 or scales.len != out.len / 16) return error.BadShape; + const factor = narrow32(nvfp4OuterFactor(amax, denominator)); + for (out, 0..) |*v, c| { + const packed_byte = codes[c / 2]; + const code = if (c % 2 == 0) packed_byte & 0xf else packed_byte >> 4; + v.* = nvWeight(code, scales[c / 16], factor); + } +} + +pub fn mxfp8Scale(scale: u8) f64 { + return std.math.ldexp(@as(f64, 1), @as(i32, scale) - 127); +} + +pub fn mxfp8ReferenceWeight(code: u8, scale: u8) f64 { + return bf16(e4m3(code) * mxfp8Scale(scale)); +} + +/// Decode one MXFP8 row using the stored per-row exponent for each group of 32 input columns (A4). +pub fn mxfp8ReferenceRow(codes: []const u8, scales: []const u8, out: []f64) ShapeError!void { + if (out.len == 0 or out.len % 32 != 0 or codes.len != out.len or scales.len != out.len / 32) return error.BadShape; + for (out, codes, 0..) |*v, code, c| v.* = mxfp8ReferenceWeight(code, scales[c / 32]); +} + +/// A bf16 reference GEMM output, with ascending f32 accumulation and no activation quantization. +pub fn expertProjection(weights: []const f64, x: []const f64, rows: usize, out: []f64) ShapeError!void { + if (rows == 0 or x.len == 0 or out.len != rows or weights.len != rows * x.len) return error.BadShape; + for (0..rows) |r| { + var sum: f32 = 0; + for (weights[r * x.len ..][0..x.len], x) |w, v| sum += narrow32(w) * narrow32(v); + out[r] = bf16(widen32(sum)); + } +} + +fn softcap32(x: f32, cap: f32) f32 { + return cap * std.math.tanh(x / cap); +} + +/// bf16(softcap4(g) * sigmoid(g) * softcap25(u)), evaluated left to right in f32. +pub fn expertActivation(gate: f64, up: f64) f64 { + const g = narrow32(gate); + const sigmoid: f32 = 1 / (1 + @exp(-g)); + const act = softcap32(g, 4) * sigmoid * softcap32(narrow32(up), 25); + return bf16(widen32(act)); +} + +/// Combine f32 from zero by ascending id, not route order (A12); expert_outputs [route][H], ids/route_weights [route]. +pub fn combineExperts(expert_count: usize, ids: []const u32, route_weights: []const f64, expert_outputs: []const f64, hidden: usize, out: []f64) ShapeError!void { + if (expert_count == 0 or hidden == 0 or ids.len != route_weights.len or expert_outputs.len != ids.len * hidden or out.len != hidden) return error.BadShape; + @memset(out, 0); + for (0..expert_count) |e| { + var found = false; + for (ids, 0..) |id, r| if (id == e) { + if (found) return error.BadShape; + found = true; + const weight = narrow32(route_weights[r]); + for (out, expert_outputs[r * hidden ..][0..hidden]) |*sum, value| { + const term = weight * narrow32(value); + sum.* = widen32(narrow32(sum.*) + term); + } + } else if (id >= expert_count) return error.BadShape; + } + for (out) |*v| v.* = bf16(v.*); +} diff --git a/zig/src/families/inkling2/loop_model_test.zig b/zig/src/families/inkling2/loop_model_test.zig new file mode 100644 index 00000000000..ee0bcf64dab --- /dev/null +++ b/zig/src/families/inkling2/loop_model_test.zig @@ -0,0 +1,214 @@ +const std = @import("std"); +const model = @import("loop_model.zig"); + +const Driver = model.Driver; +const GateWeights = model.GateWeights; +const MessageBank = model.MessageBank; +const MessageQueries = model.MessageQueries; +const attentionResidual = model.attentionResidual; +const bf16 = model.bf16; +const combineExperts = model.combineExperts; +const crossPassMessage = model.crossPassMessage; +const crossPassMessages = model.crossPassMessages; +const e2m1 = model.e2m1; +const e4m3 = model.e4m3; +const expertActivation = model.expertActivation; +const expertProjection = model.expertProjection; +const hidden_size = model.hidden_size; +const messageGate = model.messageGate; +const mxfp8ReferenceRow = model.mxfp8ReferenceRow; +const mxfp8ReferenceWeight = model.mxfp8ReferenceWeight; +const mxfp8Scale = model.mxfp8Scale; +const nvfp4OuterFactor = model.nvfp4OuterFactor; +const nvfp4ReferenceRow = model.nvfp4ReferenceRow; +const nvfp4ReferenceWeight = model.nvfp4ReferenceWeight; +const residualScale = model.residualScale; +const rms = model.rms; +const visit = model.visit; +const visit_count = model.visit_count; +const weightedRms = model.weightedRms; + +fn widen32(v: f32) f64 { + return @floatCast(v); +} + +fn expectClose(actual: f64, expected: f64, tolerance: f64) !void { + try std.testing.expectApproxEqAbs(expected, actual, tolerance); +} + +test "norm scale and weighted RMS's sole final bf16 rounding" { + const x = [_]f64{ 3, 4, 0, 0 }; + var out: [4]f64 = undefined; + var scratch: [4]f64 = undefined; + try rms(&x, 0, &out); + try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.2))), out[0]); + try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.6))), out[1]); + try weightedRms(&x, &.{ 2, 0.5, 1, 1 }, 0, &out, &scratch); + // Hand: rho=[1.2,1.6,0,0], then [2.4,0.8,0,0]. BF16(0.8) is 0.80078125. + try std.testing.expectEqualSlices(f64, &.{ 2.40625, 0.80078125, 0, 0 }, &out); +} + +test "attention residual normalizes values and applies binary32 inverse-root-H after its dot" { + const state = [_]f64{ 3, 4, 0, 0 }; + const partial = [_]f64{ 0, 10, 0, 0 }; + const query = [_]f64{ 1, 0, 0, 0 }; + var out: [4]f64 = undefined; + try attentionResidual(std.testing.allocator, &state, &partial, &query, 1, 0, &out); + // rho(S)=[1.2,1.6,0,0], rho(p)=[0,2,0,0], logits .6 and zero; w0=1/(1+exp(-.6)), output=w0*rho(S)+(1-w0)*rho(p). + const w0 = 1 / (1 + @exp(@as(f64, -0.6))); + try expectClose(out[0], 1.2 * w0, 2e-7); + try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); + try std.testing.expectEqual(@as(u32, 0x3caaaaab), @as(u32, @bitCast(try residualScale(hidden_size)))); +} + +test "message bank normalizes exactly its two states and checkpoint query rows are role-interleaved" { + const a = [_]f64{ 3, 4, 0, 0 }; + const p = [_]f64{ 0, 10, 0, 0 }; + var out: [4]f64 = undefined; + try crossPassMessage(std.testing.allocator, .{ .block = &a, .partial = &p }, &.{ 1, 0, 0, 0 }, 0, &out); + const w0 = 1 / (1 + @exp(@as(f64, -0.6))); + try expectClose(out[0], 1.2 * w0, 2e-7); + try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); + + var q_rows: [24]f64 = undefined; + var kv_rows: [24]f64 = undefined; + for (&q_rows, 0..) |*v, i| v.* = @floatFromInt(i); + for (&kv_rows, 0..) |*v, i| v.* = @floatFromInt(100 + i); + const queries: MessageQueries = .{ .q_mlp = &q_rows, .kv = &kv_rows }; + try std.testing.expectEqual(@as(f64, 4), (try queries.row(2, .q, 1))[0]); + try std.testing.expectEqual(@as(f64, 5), (try queries.row(2, .mlp, 1))[0]); + try std.testing.expectEqual(@as(f64, 104), (try queries.row(2, .k, 1))[0]); + try std.testing.expectEqual(@as(f64, 105), (try queries.row(2, .v, 1))[0]); + + var messages: [visit_count]f64 = undefined; + const one_bank: MessageBank = .{ .block = &.{3}, .partial = &.{4} }; + try crossPassMessages(std.testing.allocator, one_bank, queries, 0, &messages); + for (messages) |message| try std.testing.expectEqual(@as(f64, 1), message); +} + +test "rank gate rounds both joined norms and its down projection before f32 forget and gain" { + const h = [_]f64{ 3, 4, 0, 0 }; + const m = [_]f64{ 0, 10, 0, 0 }; + const weights: GateWeights = .{ + .down = &.{ 0.5, 1.5, 0, 0, 0.5, 1.0078125, 0, 0 }, + .forget = &.{ 1, 0, 0, 0 }, + .gain = &.{ 0, 1, 0, 0 }, + .rank = 1, + }; + var out: [4]f64 = undefined; + try messageGate(std.testing.allocator, &h, &m, weights, 0, &out); + // bf16 rho(h)=[1.203125,1.6015625,0,0], rho(m)=[0,2,0,0]; D*n=5.01953125 rounds to z=5.03125 (else 5.0). + const z: f32 = 5.03125; + const a: f32 = std.math.tanh(z); + const expected0: f32 = (1 - a) * 3; + const expected1: f32 = 4 + a * 10; + try std.testing.expectEqual(@as(f64, widen32(expected0)), out[0]); + try std.testing.expectEqual(@as(f64, widen32(expected1)), out[1]); + try std.testing.expectEqualSlices(f64, &.{ 0, 0 }, out[2..4]); +} + +test "48 visits reset from the prelude and bank B12 plus final partial of only the previous pass" { + var driver = try Driver.init(std.testing.allocator, &.{7}); + defer driver.deinit(); + const zero = [_]f64{0}; + for (0..visit_count) |v| { + _ = try driver.begin(v); + if (v == 6 or v == 18 or v == 30) { + const src = try driver.attentionSources(); + try std.testing.expectEqual(@as(usize, 1), src.blocks.len); + try std.testing.expectEqual(@as(f64, 7), src.blocks[0]); + try std.testing.expectEqual(@as(f64, 21), src.partial[0]); // sum of attention deltas 1...6 + } + if (v == 18) { + const bank = try driver.messageBank(); + try std.testing.expectEqual(@as(f64, 57), bank.block[0]); // sum 7...12 + try std.testing.expectEqual(@as(f64, 93), bank.partial[0]); // sum 13...18 + } else if (v == 30) { + const bank = try driver.messageBank(); + try std.testing.expectEqual(@as(f64, 129), bank.block[0]); // sum 19...24 + try std.testing.expectEqual(@as(f64, 165), bank.partial[0]); // sum 25...30 + } + const delta = [_]f64{@floatFromInt(v + 1)}; + try driver.afterAttention(&delta); + try driver.finish(&zero); + } + const final = try driver.finalSources(); + // Pass 3 supplies the last two core blocks. BF16 rounds the final exact sum 273 to even 272. + try std.testing.expectEqualSlices(f64, &.{ 7, 21, 201, 237 }, final.blocks); + try std.testing.expectEqual(@as(f64, 272), final.partial[0]); +} + +test "visit table preserves layer kinds, AR counts, private visit slots and reference slots" { + const expected = [_]struct { index: usize, layer: u8, pass: u8, reference: u8, messages: bool, ar: u8, attn: u8, mlp: u8 }{ + .{ .index = 0, .layer = 0, .pass = 0, .reference = 0, .messages = false, .ar = 0, .attn = 0, .mlp = 2 }, + .{ .index = 5, .layer = 5, .pass = 0, .reference = 5, .messages = false, .ar = 3, .attn = 2, .mlp = 2 }, + .{ .index = 6, .layer = 6, .pass = 1, .reference = 6, .messages = false, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 17, .layer = 17, .pass = 1, .reference = 17, .messages = false, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 18, .layer = 6, .pass = 2, .reference = 24, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 29, .layer = 17, .pass = 2, .reference = 35, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 30, .layer = 6, .pass = 3, .reference = 36, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 41, .layer = 17, .pass = 3, .reference = 47, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 42, .layer = 18, .pass = 0, .reference = 18, .messages = false, .ar = 1, .attn = 4, .mlp = 5 }, + .{ .index = 47, .layer = 23, .pass = 0, .reference = 23, .messages = false, .ar = 3, .attn = 5, .mlp = 5 }, + }; + for (expected) |e| { + const v = try visit(e.index); + try std.testing.expectEqual(e.layer, v.layer); + try std.testing.expectEqual(e.pass, v.pass); + try std.testing.expectEqual(e.reference, v.reference_slot); + try std.testing.expectEqual(@as(u8, @intCast(e.index)), v.cache_slot); + try std.testing.expectEqual(e.messages, v.has_messages); + try std.testing.expectEqual(e.ar, v.ar_queries); + try std.testing.expectEqual(e.attn, v.attention_sources); + try std.testing.expectEqual(e.mlp, v.mlp_sources); + } + try std.testing.expectError(error.BadVisit, visit(48)); +} + +test "NVFP4 uses bf16 amax and denominator and low nibble before high nibble" { + // 2689 rounds to bf16 2688, so the reference factor is exactly one rather than 2689/2688. + try std.testing.expectEqual(@as(f64, 1), nvfp4OuterFactor(2689, 2688)); + try std.testing.expectEqual(@as(f64, 1.5), nvfp4ReferenceWeight(3, 0x38, 2689, 2688)); + var row: [16]f64 = undefined; + var codes: [8]u8 = @splat(0); + codes[0] = 0xb3; + const scales = [_]u8{0x38}; + try nvfp4ReferenceRow(&codes, &scales, 2689, 2688, &row); + try std.testing.expectEqual(@as(f64, 1.5), row[0]); + try std.testing.expectEqual(@as(f64, -1.5), row[1]); + try std.testing.expectEqual(@as(f64, 0x1p-9), e4m3(1)); + try std.testing.expectEqual(@as(f64, -0.0), e2m1(8)); +} + +test "MXFP8 exponent is UE8M0 and each stored scale covers one row's 32 inputs" { + try std.testing.expectEqual(@as(f64, 8), mxfp8Scale(130)); + try std.testing.expectEqual(@as(f64, 12), mxfp8ReferenceWeight(0x3c, 130)); // 1.5 * 2^3 + var codes: [64]u8 = @splat(0); + codes[0] = 0x38; // one + codes[31] = 0x3c; // 1.5, still group zero + codes[32] = 0x3c; // group one + var out: [64]f64 = undefined; + try mxfp8ReferenceRow(&codes, &.{ 130, 129 }, &out); + try std.testing.expectEqual(@as(f64, 8), out[0]); + try std.testing.expectEqual(@as(f64, 12), out[31]); + try std.testing.expectEqual(@as(f64, 6), out[32]); +} + +test "expert projection and softcapped SwiGLU have no activation quantization" { + var projected: [2]f64 = undefined; + try expertProjection(&.{ 1, 2, -1, 0.5 }, &.{ 3, 4 }, 2, &projected); + try std.testing.expectEqualSlices(f64, &.{ 11, -1 }, &projected); + const g: f32 = 1; + const expected: f32 = 4 * std.math.tanh(g / 4) * (1 / (1 + @exp(-g))) * (25 * std.math.tanh(g / 25)); + try std.testing.expectEqual(@as(f64, bf16(widen32(expected))), expertActivation(1, 1)); +} + +test "expert sum is ascending id even when f32 route-order association gives another bf16 result" { + const ids = [_]u32{ 2, 1, 0 }; + const weights = [_]f64{ 1, 1, 1 }; + // Route order gives -1 + 2^-24 + 1 = 2^-24 in f32; ascending id gives (1 + 2^-24) - 1 = 0 by a tie to even. + const outputs = [_]f64{ -1, 0x1p-24, 1 }; + var out: [1]f64 = undefined; + try combineExperts(3, &ids, &weights, &outputs, 1, &out); + try std.testing.expectEqual(@as(f64, 0), out[0]); +} From 41807f3b59a4d26c6794ec46a483af721e405149 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:38:43 +0000 Subject: [PATCH 11/84] inkling2: run checkpoint-packed experts on CUDA Decode stored NVFP4 and MXFP8 expert weights to BF16 and launch them beside the grouped expert/vision kernels, with exact tensor baselines and planted faults. --- CHANGELOG.md | 3 + THIRD_PARTY_NOTICES.md | 11 + zig/build/cuda_kernels.zig | 3 + zig/kernels/cuda/inkling2/experts.cu | 485 ++++++++++++++++++ zig/kernels/cuda/inkling2/modelopt.cu | 204 ++++++++ zig/kernels/cuda/inkling2/vision.cu | 203 ++++++++ .../core/contract/inkling2_cuda_records.zig | 7 +- .../contract/inkling2_experts_records.zig | 22 + .../contract/measurements/pending_133.zig | 7 + zig/src/cuda/kernels.zig | 3 + zig/src/families/inkling2/experts.zig | 148 ++++++ zig/src/families/inkling2/image.zig | 242 +++++++++ zig/src/families/inkling2/inkling2.zig | 8 + zig/src/families/inkling2/modelopt.zig | 454 ++++++++++++++++ zig/src/families/inkling2/vision.zig | 400 +++++++++++++++ zig/tests/cuda/contract_inkling2.zig | 7 +- zig/tests/cuda/contract_inkling2_experts.zig | 85 +++ .../cuda/contract_inkling2_experts_attn.zig | 282 ++++++++++ .../contract_inkling2_experts_grouped.zig | 296 +++++++++++ .../cuda/contract_inkling2_experts_ref.zig | 293 +++++++++++ .../cuda/contract_inkling2_experts_vision.zig | 275 ++++++++++ zig/tests/cuda/contract_inkling2_modelopt.zig | 463 +++++++++++++++++ zig/tests/cuda/contract_inkling2_ops_mix.zig | 27 +- .../cuda/contract_inkling2_ops_route.zig | 6 +- zig/tests/cuda/contract_inkling2_ops_rows.zig | 12 +- zig/tests/cuda/contract_limits.zig | 2 +- zig/tests/cuda/main.zig | 28 + zig/tests/fixtures/gradient-serving.tsv | 2 +- 28 files changed, 3952 insertions(+), 26 deletions(-) create mode 100644 zig/kernels/cuda/inkling2/experts.cu create mode 100644 zig/kernels/cuda/inkling2/modelopt.cu create mode 100644 zig/kernels/cuda/inkling2/vision.cu create mode 100644 zig/src/core/contract/inkling2_experts_records.zig create mode 100644 zig/src/families/inkling2/experts.zig create mode 100644 zig/src/families/inkling2/image.zig create mode 100644 zig/src/families/inkling2/modelopt.zig create mode 100644 zig/src/families/inkling2/vision.zig create mode 100644 zig/tests/cuda/contract_inkling2_experts.zig create mode 100644 zig/tests/cuda/contract_inkling2_experts_attn.zig create mode 100644 zig/tests/cuda/contract_inkling2_experts_grouped.zig create mode 100644 zig/tests/cuda/contract_inkling2_experts_ref.zig create mode 100644 zig/tests/cuda/contract_inkling2_experts_vision.zig create mode 100644 zig/tests/cuda/contract_inkling2_modelopt.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 79d3b9c56c8..9387b7e7e8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -146,6 +146,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds each 512-key chunk's two pages once instead of reading the page table at every 32-key step, with every token and cache row unchanged (#3180, part of #1293). Thanks to @CodingEmil. - Nemotron 3.5 Lightning on HIP: the MTP head file is read at the width its own metadata states, so it drafts beside an oQ checkpoint of any width, and a head at a width the launches do not read is refused by name (#3251, part of #3061). Thanks to @gilby. + +- Inkling 2 on CUDA: the family's grouped-expert launches match main's `tf_exl3_grouped_2` bit for bit under the kernel contract, and the vision tower's kernels pass gates 1 to 4 (refs #3476). Thanks to @ajensenwaud. + - Tests: the served-evidence concurrency test pairs its two generated streams in the fake server, so a busy runner can no longer decode them one after the other and turn it red; other conformance fixtures keep their pacing. - GLM-5.3-Flash on CUDA at tensor-parallel widths where a rank's fused KDA input is not a multiple of eight columns (TP=3, 5, 6 or 7): the stack is padded at load to its own width rounded up to eight columns and stays row-major bf16, so prompt windows take the staged B16 tiles with every byte as before; `TF_GLM_KDA_PAD=1` still tiles the stack for glm_mm (#3697, for #3516). Thanks to @ultradaoto. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 02fa97af919..18458a70310 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -572,3 +572,14 @@ these layers of Hugging Face transformers' `src/transformers/models/inkling2/mod `Inkling2NormedEmbedding`, `Inkling2BlockAttentionResidual`, `Inkling2ShortConvolution`, `Inkling2DynamicShortConvolution`, `Inkling2TopKRouter`, `Inkling2SoftcappedSwiGLU` and `Inkling2Softcap`. The kernels are TensorFold's own. + +## Inkling 2 expert and vision kernels + +`zig/kernels/cuda/inkling2/experts.cu` and `zig/src/families/inkling2/experts.zig` run `Inkling2Experts` from Hugging +Face transformers' `src/transformers/models/inkling2/modeling_inkling2.py` at commit `109a7d19bf66` +([huggingface/transformers](https://github.com/huggingface/transformers), Apache-2.0) on main's EXL3 grouped-expert +arithmetic. `zig/kernels/cuda/inkling2/vision.cu` and `zig/src/families/inkling2/vision.zig` compute the same file's +vision tower: `Inkling2VisionEmbeddings`, `Inkling2VisionRotaryEmbedding`, `Inkling2VisionAttention`, +`Inkling2VisionMLP` and `Inkling2VisionMerger`. `zig/src/families/inkling2/image.zig` follows `Inkling2ImageProcessor` +in `image_processing_inkling2.py` at the same commit for its 40-pixel patches and the tower's input tables. + diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 4ddb07b7e23..dd80b81d0d3 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -164,6 +164,9 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_pattn", .src = "inkling2/prompt_attention", .flags = &.{"-O3"} }, // ours: Inkling 2's global-layer prompt attention .{ .name = "inkling2_ops", .src = "inkling2/ops", .flags = glue }, // ours: Inkling 2's residual mix, convs, router, SwiGLU .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows + .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // ours: Inkling 2's grouped experts + .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations + .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family .{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5 .{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts diff --git a/zig/kernels/cuda/inkling2/experts.cu b/zig/kernels/cuda/inkling2/experts.cu new file mode 100644 index 00000000000..622b8813562 --- /dev/null +++ b/zig/kernels/cuda/inkling2/experts.cu @@ -0,0 +1,485 @@ +// Inkling 2's grouped expert projections: exl3_grouped.cuh's arithmetic per output, launched without empty tiles. +#include +#include +#include + +#include "exl3_decode.cuh" +#include "common/fp_pairs.cuh" + +namespace ink2x { +using namespace tf_exl3; + +constexpr int ITEM_THREADS = 1024; + +// tf_ink2x_group's arguments: tf_exl3_group's lists, plus items (u, first, count), runs of at most `per` members. +struct GroupArgs { + const int* pick; // int32 [rows * slots] + int* uids; // int32 [nexp_max] + int* ucount; // int32 [1] + int* members; // int32 [nexp_max, maxm] + int* items; // int32 [3 * max items] (per > 0) + int* nitems; // int32 [1] (per > 0) + int rows, slots, experts, maxm, per, pad; // pad: -1 after each expert's members up to maxm +}; + +// One projection; z, k, n, p, sk, maxm and slots as GroupedArgs has them. +struct WideArgs { + const half* x0; // fp16 [P, K], the rotated gate (or down) inputs + const half* x1; // fp16 [P, K], the rotated up inputs + const long long* tp0; // int64 [E], one trellis pointer per expert + const long long* tp1; + const int* k2_0; // int32 [E], half-bits a value + const int* k2_1; + const int* uids; // int32 [nexp_max], distinct routed experts in id order + const int* items; // int32 [3 * max items], (u, first member, count); null: item u is expert u, maxm <= 16 MT + const int* nitems; // int32 [1]: the items, or the group's count when items is null + const int* members; // int32 [nexp_max, maxm], row * 32 + slot + float* z; // fp32 partials, [(mat * sk + split) * P + p] * N + col + int k, n, p, sk, maxm, slots; +}; + +// A warp's k tiles for MT member tiles in grouped_body's order per output; words and inputs travel a tile ahead. +template +struct Tiles { + static constexpr int TW = tile_words(), LW = lane_words(); + uint32_t nx[NT][LW]; + + __device__ __forceinline__ void first(const uint32_t* tb, int nkt, int lane) { + if (nkt > 0) +#pragma unroll + for (int j = 0; j < NT; ++j) ldg_lane_words(tb + j * TW, lane, nx[j]); + } + + __device__ __forceinline__ static void xload(const half* (&xr)[MT][2], const bool (&ok)[MT][2], int mts, int k, + uint32_t (&a)[MT][4]) { +#pragma unroll + for (int m = 0; m < MT; ++m) { + const bool o0 = m < mts && ok[m][0], o1 = m < mts && ok[m][1]; + a[m][0] = o0 ? *reinterpret_cast(xr[m][0] + k) : 0u; + a[m][1] = o1 ? *reinterpret_cast(xr[m][1] + k) : 0u; + a[m][2] = o0 ? *reinterpret_cast(xr[m][0] + k + 8) : 0u; + a[m][3] = o1 ? *reinterpret_cast(xr[m][1] + k + 8) : 0u; + } + } + + __device__ __forceinline__ void run(const uint32_t* tb, size_t kstride, int kt0, int nkt, const half* (&xr)[MT][2], + const bool (&ok)[MT][2], int mts, int lane, float (&acc)[MT][NT][2][4]) { + uint32_t xa[MT][4]; + if (nkt > 0) xload(xr, ok, mts, kt0 * 16, xa); + for (int i = 0; i < nkt; ++i) { + uint32_t w[NT][LW], a[MT][4]; +#pragma unroll + for (int j = 0; j < NT; ++j) +#pragma unroll + for (int l = 0; l < LW; ++l) w[j][l] = nx[j][l]; +#pragma unroll + for (int m = 0; m < MT; ++m) +#pragma unroll + for (int c = 0; c < 4; ++c) a[m][c] = xa[m][c]; + if (i + 1 < nkt) { +#pragma unroll + for (int j = 0; j < NT; ++j) ldg_lane_words(tb + (size_t)(i + 1) * kstride + j * TW, lane, nx[j]); + xload(xr, ok, mts, (kt0 + i + 1) * 16, xa); + } +#pragma unroll + for (int j = 0; j < NT; ++j) { + uint32_t b0[2], b1[2]; + decode_lane(w[j], lane, b0, b1); +#pragma unroll + for (int m = 0; m < MT; ++m) + if (m < mts) { + mma16816(acc[m][j][0], a[m], b0); + mma16816(acc[m][j][1], a[m], b1); + } + } + } + } +}; + +// This lane's member-row input pointers (rows_sh filled and synced). +template +__device__ __forceinline__ void member_rows(const half* X, int k, const int* rows_sh, int mts, int g, int t, + const half* (&xr)[MT][2], bool (&ok)[MT][2]) { +#pragma unroll + for (int m = 0; m < MT; ++m) { + const int r0 = m < mts ? rows_sh[16 * m + g] : -1, r1 = m < mts ? rows_sh[16 * m + g + 8] : -1; + xr[m][0] = X + (size_t)(r0 < 0 ? 0 : r0) * k + 2 * t; + xr[m][1] = X + (size_t)(r1 < 0 ? 0 : r1) * k + 2 * t; + ok[m][0] = r0 >= 0; + ok[m][1] = r1 >= 0; + } +} + +// Program (n block, item, mat * sk + split): 16 MT members by W_q over the split's K; SEQ: warps add in turn. +template +__device__ __forceinline__ void wide_body(const WideArgs a) { + const int nblock = blockIdx.x, item = blockIdx.y; + if (item >= a.nitems[0]) return; + int u = item, first = 0, cnt = a.maxm; + if (a.items) { + u = a.items[3 * item]; + first = a.items[3 * item + 1]; + cnt = a.items[3 * item + 2]; + } + const int split = blockIdx.z % a.sk, mat = blockIdx.z / a.sk; + const half* X = mat ? a.x1 : a.x0; + const int e = a.uids[u]; + const uint32_t* T = reinterpret_cast(mat ? a.tp1[e] : a.tp0[e]); + const int k2 = mat ? a.k2_1[e] : a.k2_0[e]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int g = lane >> 2, t = lane & 3; + const int ntiles = a.n >> 4; + const int per_warp = (a.k >> 4) / a.sk / W; + const int kt0 = split * (per_warp * W) + warp * per_warp; + const int nt0 = nblock * NT; + + __shared__ int rows_sh[16 * MT]; + for (int m = threadIdx.x; m < 16 * MT; m += W * 32) { + const int code = m < cnt ? a.members[(size_t)u * a.maxm + first + m] : -1; + rows_sh[m] = code >= 0 ? (code >> 5) * a.slots + (code & 31) : -1; + } + float acc[MT][NT][2][4]; +#pragma unroll + for (int m = 0; m < MT; ++m) +#pragma unroll + for (int i = 0; i < NT; ++i) +#pragma unroll + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int c = 0; c < 4; ++c) acc[m][i][h][c] = 0.f; + + int mts = 0; + switch (k2) { // the first k tile's words are in flight before the members' rows are read +#define TF_INK2X_CASE(K2_) \ + case K2_: { \ + Tiles tl; \ + const size_t kstride = (size_t)ntiles * tile_words(); \ + const uint32_t* tb = T + (size_t)kt0 * kstride + (size_t)nt0 * tile_words(); \ + tl.first(tb, per_warp, lane); \ + __syncthreads(); \ + if (!a.items) \ + while (cnt > 0 && rows_sh[cnt - 1] < 0) --cnt; \ + mts = (cnt + 15) >> 4; \ + if (mts == 0) return; \ + const half* xr[MT][2]; \ + bool ok[MT][2]; \ + member_rows(X, a.k, rows_sh, mts, g, t, xr, ok); \ + tl.run(tb, kstride, kt0, per_warp, xr, ok, mts, lane, acc); \ + break; \ + } + TF_INK2X_CASE(2) + TF_INK2X_CASE(3) + TF_INK2X_CASE(4) + TF_INK2X_CASE(5) + TF_INK2X_CASE(6) + TF_INK2X_CASE(7) + TF_INK2X_CASE(8) +#undef TF_INK2X_CASE + default: + __trap(); + } + + __shared__ __align__(16) float red[SEQ ? 1 : W][16][NT * 16]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + if (m >= mts) break; + if (m) __syncthreads(); // the last tile's sums are read + for (int w = SEQ ? 0 : warp; w < (SEQ ? W : warp + 1); ++w) { + if (w == warp) +#pragma unroll + for (int i = 0; i < NT; ++i) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int col = i * 16 + h * 8 + 2 * t; + float* p0 = &red[SEQ ? 0 : warp][g][col]; + float* p1 = &red[SEQ ? 0 : warp][g + 8][col]; + if (!SEQ || w == 0) { + p0[0] = acc[m][i][h][0]; + p0[1] = acc[m][i][h][1]; + p1[0] = acc[m][i][h][2]; + p1[1] = acc[m][i][h][3]; + } else { + p0[0] += acc[m][i][h][0]; + p0[1] += acc[m][i][h][1]; + p1[0] += acc[m][i][h][2]; + p1[1] += acc[m][i][h][3]; + } + } + if (SEQ) __syncthreads(); + } + if (!SEQ) __syncthreads(); + for (int idx = threadIdx.x; idx < 16 * NT * 16; idx += W * 32) { + const int row = idx / (NT * 16), col = idx % (NT * 16); + const int r = rows_sh[16 * m + row]; + if (r < 0) continue; + float s = red[0][row][col]; +#pragma unroll + for (int w = 1; w < (SEQ ? 1 : W); ++w) s += red[w][row][col]; + a.z[(((size_t)mat * a.sk + split) * a.p + r) * a.n + nt0 * 16 + col] = s; + } + } +} + +// Exclusive sum over the block of one value a thread (ITEM_THREADS threads); `tot` gets the total. +__device__ __forceinline__ int block_scan(int v, int* part, int& tot) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + int inc = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int x = __shfl_up_sync(0xffffffffu, inc, o); + if (lane >= o) inc += x; + } + if (lane == 31) part[warp] = inc; + __syncthreads(); + if (warp == 0) { + const int w = part[lane]; + int sum = w; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int x = __shfl_up_sync(0xffffffffu, sum, o); + if (lane >= o) sum += x; + } + part[lane] = sum - w; + if (lane == 31) part[32] = sum; + } + __syncthreads(); + tot = part[32]; + const int r = part[warp] + inc - v; + __syncthreads(); + return r; +} + +} // namespace ink2x + +// tf_exl3_group's lists and the item list in O(pairs): warp w counts, then places, its 32nd of the pairs in order. +extern "C" __global__ void __launch_bounds__(ink2x::ITEM_THREADS) tf_ink2x_group(const ink2x::GroupArgs a) { + extern __shared__ int sh[]; + __shared__ int part[33]; + const int E = a.experts, n = a.rows * a.slots; + uint16_t* wc = reinterpret_cast(sh); // [32][E]: a warp's pairs of each expert, then its first rank + int* cnt = sh + 16 * E; + int* uidx = cnt + E; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int span = (n + 31) / 32, lo = warp * span, hi = min(n, lo + span); + const unsigned below = (1u << lane) - 1u; + for (int i = threadIdx.x; i < 32 * E; i += ink2x::ITEM_THREADS) wc[i] = 0; + __syncthreads(); + for (int i0 = lo; i0 < hi; i0 += 32) { + const int i = i0 + lane; + const int e = i < hi ? a.pick[i] : -1; + const unsigned m = __match_any_sync(0xffffffffu, e); + if (e >= 0 && e < E && (m & below) == 0) wc[warp * E + e] += __popc(m); + } + __syncthreads(); + int has = 0, k = 0, c = 0; + const int e = threadIdx.x; + if (e < E) { + for (int w = 0; w < 32; ++w) { + const int t = wc[w * E + e]; + wc[w * E + e] = c; + c += t; + } + cnt[e] = c; + has = c > 0; + k = a.per > 0 ? (c + a.per - 1) / a.per : 0; + } + int nu, ni; + const int u = ink2x::block_scan(has, part, nu); + int it = ink2x::block_scan(k, part, ni); + if (e < E) { + uidx[e] = u; + if (has) { + a.uids[u] = e; + for (int j = 0; j < k; ++j, ++it) { + a.items[3 * it] = u; + a.items[3 * it + 1] = j * a.per; + a.items[3 * it + 2] = min(a.per, c - j * a.per); + } + } + } + if (threadIdx.x == 0) { + a.ucount[0] = nu; + if (a.per > 0) a.nitems[0] = ni; + } + __syncthreads(); + for (int i0 = lo; i0 < hi; i0 += 32) { + const int i = i0 + lane; + const int pe = i < hi ? a.pick[i] : -1; + const unsigned m = __match_any_sync(0xffffffffu, pe); + if (pe >= 0 && pe < E) { + const int rank = wc[warp * E + pe] + __popc(m & below); + a.members[(size_t)uidx[pe] * a.maxm + rank] = (i / a.slots) * 32 + i % a.slots; + } + __syncwarp(); + if (pe >= 0 && pe < E && (m & below) == 0) wc[warp * E + pe] += __popc(m); + __syncwarp(); + } + if (a.pad) // -1 after each expert's members, as tf_exl3_group leaves them + for (int x = threadIdx.x; x < E; x += ink2x::ITEM_THREADS) + if (cnt[x] > 0) + for (int j = cnt[x]; j < a.maxm; ++j) a.members[(size_t)uidx[x] * a.maxm + j] = -1; +} + +// Decode rows and short windows: 128 columns and 16 members a block (grouped_body's tile), warp sums apart. +extern "C" __global__ void __launch_bounds__(128) tf_ink2x_rows(const ink2x::WideArgs a) { + ink2x::wide_body(a); +} + +// Prompt chunks: 64 columns and 32 members a block, one sum buffer. +extern "C" __global__ void __launch_bounds__(128) tf_ink2x_wide(const ink2x::WideArgs a) { + ink2x::wide_body(a); +} + +namespace ink2m { + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } +__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } +__device__ __forceinline__ float warpSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +template +__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); + __syncthreads(); + if (lane == 0) + for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; + __syncthreads(); + for (int i = 0; i < N; ++i) { + float t = lane < nw ? sh[i * 32 + lane] : 0.0f; + v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); + } +} + +struct GateUpArgs { + const uint16_t* x; // bf16 [rows, x_stride], pair p reads row p / slots + const uint8_t *codes, *scales; + const float *amax, *denominator; + const int* pick; // int32 [P] + uint16_t* out; // bf16 [P, N], the rounded softcapped SwiGLU + int x_stride, p, slots, n, k, experts, format; + float gate_cap, up_cap; +}; + +struct DownArgs { + const uint16_t* x; // bf16 [P, K], gateup's output + const uint8_t *codes, *scales; + const float *amax, *denominator; + const int* pick; + uint16_t* out; // bf16 [P, N], each selected expert's rounded output + int p, n, k, experts, format; +}; + +struct CombineArgs { + const uint16_t* experts; // bf16 [rows * slots, H] + const int* pick; + const float* weights; + uint16_t* out; // bf16 [rows, H] + int rows, h, slots; +}; + +struct TensorActArgs { + const uint16_t* gateup; // bf16 [P, 2 * M], adjacent gate and up projections + uint16_t* out; // bf16 [P, M] + int n; +}; + +__device__ __forceinline__ float e2m1(unsigned code) { + const float values[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + const float v = values[code & 7u]; + return code & 8u ? -v : v; +} + +// The checkpoint's stored codes and scales become one bf16 weight, with no activation quantization. +__device__ __forceinline__ float weight(const uint8_t* codes, const uint8_t* scales, const float* amax, + const float* denominator, int e, int r, int c, int n, int k, int format) { + const int er = e * n + r; + if (format == 0) { + const uint8_t packed = codes[(size_t)er * (k / 2) + c / 2]; + const unsigned code = c & 1 ? packed >> 4 : packed & 15u; + const float scale = tf_common::e4m3f(scales[(size_t)er * (k / 16) + c / 16]); + const float phi = __fdiv_rn(bfr(amax[e]), bfr(denominator[0])); + return bfr(__fmul_rn(__fmul_rn(e2m1(code), scale), phi)); + } + const float value = tf_common::e4m3f(codes[(size_t)er * k + c]); + const float scale = ldexpf(1.0f, static_cast(scales[(size_t)er * (k / 32) + c / 32]) - 127); + return bfr(__fmul_rn(value, scale)); +} + +__device__ __forceinline__ float cap(float x, float c) { return c * tanhf(x / c); } + +} // namespace ink2m + +// One (routed pair, intermediate unit): two stored NVFP4/MXFP8 rows and the rounded SwiGLU epilogue. +extern "C" __global__ void __launch_bounds__(128) tf_ink2moe_gateup(const ink2m::GateUpArgs a) { + __shared__ float sh[64]; + const int p = blockIdx.y, unit = blockIdx.x, e = a.pick[p]; + const uint16_t* x = a.x + static_cast(p / a.slots) * a.x_stride; + float v[2] = {0.0f, 0.0f}; + for (int c = threadIdx.x; c < a.k; c += blockDim.x) { + const float xv = ink2m::bf(x[c]); + const float g = ink2m::weight(a.codes, a.scales, a.amax, a.denominator, e, 2 * unit, c, 2 * a.n, a.k, a.format); + const float u = ink2m::weight(a.codes, a.scales, a.amax, a.denominator, e, 2 * unit + 1, c, 2 * a.n, a.k, a.format); + v[0] = __fmaf_rn(xv, g, v[0]); + v[1] = __fmaf_rn(xv, u, v[1]); + } + ink2m::blockSums<2>(v, sh); + if (threadIdx.x == 0) { + const float g = ink2m::cap(ink2m::bfr(v[0]), a.gate_cap); + const float u = ink2m::cap(ink2m::bfr(v[1]), a.up_cap); + a.out[(size_t)p * a.n + unit] = ink2m::tobf(g * (1.0f / (1.0f + expf(-ink2m::bfr(v[0])))) * u); + } +} + +// One (routed pair, hidden output): the down projection, rounded to bf16 before routing weights are applied. +extern "C" __global__ void __launch_bounds__(128) tf_ink2moe_down(const ink2m::DownArgs a) { + __shared__ float sh[32]; + const int p = blockIdx.y, row = blockIdx.x, e = a.pick[p]; + float v[1] = {0.0f}; + for (int c = threadIdx.x; c < a.k; c += blockDim.x) { + const float w = ink2m::weight(a.codes, a.scales, a.amax, a.denominator, e, row, c, a.n, a.k, a.format); + v[0] = __fmaf_rn(ink2m::bf(a.x[(size_t)p * a.k + c]), w, v[0]); + } + ink2m::blockSums<1>(v, sh); + if (threadIdx.x == 0) a.out[(size_t)p * a.n + row] = ink2m::tobf(v[0]); +} + +// Tensor-core gate/up rows are interleaved; keep the scalar baseline's softcapped SwiGLU arithmetic. +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_tensor_act(const ink2m::TensorActArgs a) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= a.n) return; + const float gate = ink2m::bf(a.gateup[2 * (size_t)i]); + const float up = ink2m::bf(a.gateup[2 * (size_t)i + 1]); + const float g = ink2m::cap(gate, 4.0f); + const float u = ink2m::cap(up, 25.0f); + const float sigmoid = 1.0f / (1.0f + expf(-gate)); + const float activated = g * sigmoid * u; + a.out[i] = ink2m::tobf(activated); +} + +// One output element: route in ascending expert id, independent of the router's selection order. +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_combine(const ink2m::CombineArgs a) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= a.rows * a.h) return; + const int row = i / a.h, col = i % a.h; + float total = 0.0f; + uint32_t seen = 0; + for (int n = 0; n < a.slots; ++n) { + int best = -1, id = 0; + for (int s = 0; s < a.slots; ++s) { + if (seen & (1u << s)) continue; + const int e = a.pick[row * a.slots + s]; + if (best < 0 || e < id) { + best = s; + id = e; + } + } + seen |= 1u << best; + const float out = ink2m::bf(a.experts[(size_t)(row * a.slots + best) * a.h + col]); + total = __fadd_rn(total, __fmul_rn(a.weights[row * a.slots + best], out)); + } + a.out[i] = ink2m::tobf(total); +} diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu new file mode 100644 index 00000000000..2f8a4c40bd7 --- /dev/null +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -0,0 +1,204 @@ +// Mini routed experts: checkpoint NVFP4/MXFP8 codes decode to BF16 mma fragments; no activation quantization. +#include +#include +#include "experts.cuh" + +namespace ink2o { + +struct Weight { + const uint8_t* codes; + const uint8_t* scales; + const float* amax; + const float* den; + long long E, N, K; + int G, format, row0, row_step; +}; + +__device__ __forceinline__ float e2m1(uint32_t n) { + const uint32_t s = (n & 8) ? 0x80000000u : 0; + const uint32_t e = (n >> 1) & 3, m = n & 1; + if (!e) return __uint_as_float(s | (m ? 0x3f000000u : 0)); + return __uint_as_float(s | ((e + 126) << 23) | (m << 22)); +} + +__device__ __forceinline__ float e4m3(uint32_t n) { + const uint32_t s = (n & 128) ? 0x80000000u : 0; + const uint32_t e = (n >> 3) & 15, m = n & 7; + if (e == 15 && m == 7) return __uint_as_float(s | 0x7fc00000u); + if (!e) return (s ? -1.f : 1.f) * (float)m * 0.001953125f; + return __uint_as_float(s | ((e + 120) << 23) | (m << 20)); +} + +__device__ __forceinline__ float e8m0(uint32_t n) { + if (n == 0) return 0x1p-127f; + return __uint_as_float(n << 23); +} + +__device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } +__device__ __forceinline__ __nv_bfloat16 decoded(const Weight& w, long long e, long long row, long long col) { + const long long z = e * w.N * w.K + row * w.K + col; + const uint32_t nib = w.format ? w.codes[z] : ((w.codes[z / 2] >> ((col & 1) * 4)) & 15); + float v; + if (w.format) { + v = __fmul_rn(e4m3(nib), e8m0(w.scales[z / w.G])); + } else { + const float outer = __fdiv_rn(bf(__ldg(w.amax + e)), bf(__ldg(w.den))); + v = __fmul_rn(__fmul_rn(e2m1(nib), e4m3(w.scales[z / w.G])), outer); + } + return __float2bfloat16_rn(v); +} + +// One uint4 is eight BF16 weights in the fragment layout of experts_bf16.cu. +__device__ __forceinline__ uint4 ld_w(const Weight& w, long long e, int cb, int g, int lane, int j) { + const int row = w.row0 + w.row_step * (cb * 32 + 8 * j + (lane >> 2)), col = g * 32 + 4 * (lane & 3); + uint16_t h[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int c = col + (i & 3) + 16 * (i >> 2); + h[i] = __bfloat16_as_ushort(decoded(w, e, row, c)); + } + uint4 o; + o.x = h[0] | (uint32_t)h[1] << 16; + o.y = h[2] | (uint32_t)h[3] << 16; + o.z = h[4] | (uint32_t)h[5] << 16; + o.w = h[6] | (uint32_t)h[7] << 16; + return o; +} + +template +__device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, Weight w, + int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, + const int* __restrict__ members, void* __restrict__ out, int N, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(item_count) * NB; + for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) { + const int it = unit / NB, cb = unit - it * NB; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + for (int r0 = 0; r0 < cnt; r0 += 16 * RT) { + bool v[RT][2]; + int pr[RT][2]; + const __nv_bfloat16* x[RT][2]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int i = r0 + 16 * r + gq + 8 * h; + v[r][h] = i < cnt; + pr[r][h] = v[r][h] ? __ldg(members + first + i) : 0; + x[r][h] = X + (size_t)(slots ? pr[r][h] / slots : pr[r][h]) * x_stride + 4 * t; + } + float acc[1][RT][NTW][4]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[0][r][j][0] = acc[0][r][j][1] = acc[0][r][j][2] = acc[0][r][j][3] = 0.f; + const uint2 zero = make_uint2(0u, 0u); + for (int g = 0; g < KG; ++g) { + uint4 ww[NTW]; +#pragma unroll + for (int j = 0; j < NTW; ++j) ww[j] = ld_w(w, e, cb, g, lane, j); +#pragma unroll + for (int r = 0; r < RT; ++r) { + uint2 xa[2], xb[2]; +#pragma unroll + for (int q = 0; q < 2; ++q) { + xa[q] = v[r][0] ? __ldg(reinterpret_cast(x[r][0] + 32 * g + 16 * q)) : zero; + xb[q] = v[r][1] ? __ldg(reinterpret_cast(x[r][1] + 32 * g + 16 * q)) : zero; + } +#pragma unroll + for (int q = 0; q < 2; ++q) +#pragma unroll + for (int j = 0; j < NTW; ++j) + mma(acc[0][r][j], xa[q].x, xb[q].x, xa[q].y, xb[q].y, q ? ww[j].z : ww[j].x, q ? ww[j].w : ww[j].y); + } + } +#pragma unroll + for (int r = 0; r < RT; ++r) + epilogue<3, 1, RT>(acc, r, out, N, cb * COLS + 2 * t, pr[r][0], pr[r][1], v[r][0], v[r][1], 0.f); + } + } +} + +__device__ __forceinline__ void act(const __nv_bfloat16* __restrict__ gate, const __nv_bfloat16* __restrict__ up, + __nv_bfloat16* __restrict__ out, int n, float gate_cap, float up_cap) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float raw = __bfloat162float(gate[i]); + const float g = gate_cap * tanhf(raw / gate_cap); + const float u = up_cap * tanhf(__bfloat162float(up[i]) / up_cap); + // σ(raw) is its own FP32 rounding before the two left-to-right products (§6.4). + const float sigmoid = 1.f / (1.f + expf(-raw)); + const float a = g * sigmoid * u; + out[i] = __float2bfloat16_rn(a); +} + +__device__ __forceinline__ void combine(const int32_t* __restrict__ pick, const float* __restrict__ wts, + const __nv_bfloat16* __restrict__ ey, __nv_bfloat16* __restrict__ out, + int rows, int hidden, int slots, int experts) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * hidden) return; + const int r = i / hidden, h = i - r * hidden; + float total = 0.f; + uint32_t seen = 0; + for (int n = 0; n < slots; ++n) { + int best = -1; + int32_t id = 0; + for (int s = 0; s < slots; ++s) { + if (seen & (1u << s)) continue; + const int32_t expert = pick[r * slots + s]; + if (expert < 0 || expert >= experts) continue; + if (best < 0 || expert < id) { + best = s; + id = expert; + } + } + if (best < 0) break; + seen |= 1u << best; + const int pair = r * slots + best; + const float term = __fmul_rn(__ldg(wts + pair), __bfloat162float(ey[pair * hidden + h])); + total = __fadd_rn(total, term); + } + out[i] = __float2bfloat16_rn(total); +} + +} // namespace ink2o + +// Pair indices are row * slots + slot. Items hold a physical expert ID, a global member offset and a count. +extern "C" __global__ void __launch_bounds__(32) tf_ink2moe_plan(const int32_t* __restrict__ pick, + int* __restrict__ items, int* __restrict__ members, int* __restrict__ item_count, + int rows, int slots, int experts, int tile) { + if (blockIdx.x || threadIdx.x) return; + const int pairs = rows * slots; + int used = 0, at = 0; + for (int e = 0; e < experts; ++e) { + const int first = used; + for (int pair = 0; pair < pairs; ++pair) { + if (pick[pair] == e) members[used++] = pair; + } + const int count = used - first; + for (int off = 0; off < count; off += tile) { + items[3 * at] = e; + items[3 * at + 1] = first + off; + items[3 * at + 2] = (count - off < tile) ? count - off : tile; + ++at; + } + } + *item_count = at; +} + +#define TF_INK2_MOE(NAME, RT) \ + extern "C" __global__ void __launch_bounds__(128) NAME(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, \ + ink2o::Weight w, int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, \ + const int* __restrict__ members, void* __restrict__ out, int N, int skip) { \ + ink2o::body(X, x_stride, slots, w, KG, NB, items, item_count, members, out, N, skip); \ + } +TF_INK2_MOE(tf_ink2moe_up, 1) +TF_INK2_MOE(tf_ink2moe_prompt_up, 4) +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_act(const __nv_bfloat16* g, const __nv_bfloat16* u, __nv_bfloat16* o, int n, float gc, float uc) { + ink2o::act(g, u, o, n, gc, uc); +} +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_combine(const int32_t* p, const float* w, const __nv_bfloat16* e, + __nv_bfloat16* o, int rows, int hidden, int slots, int experts) { + ink2o::combine(p, w, e, o, rows, hidden, slots, experts); +} diff --git a/zig/kernels/cuda/inkling2/vision.cu b/zig/kernels/cuda/inkling2/vision.cu new file mode 100644 index 00000000000..5b0468bb4a7 --- /dev/null +++ b/zig/kernels/cuda/inkling2/vision.cu @@ -0,0 +1,203 @@ +// Inkling 2's vision tower glue: patch rows to the sequence, axial rotary, layer-scaled residuals, full attention. +#include +#include + +#include "prefill_attention.cuh" + +namespace ink2v { + +using namespace tf_prefill_attention; + +constexpr int kWidth = 1024; // the tower's hidden size +constexpr int kHeads = 16; +constexpr int kDim = 64; +constexpr int kPairs = kDim / 2; +constexpr int kThreads = 256; + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } + +__device__ __forceinline__ __nv_bfloat16 tobf(float v) { return __float2bfloat16_rn(v); } + +// prefill_attention.cu's vision_kernel body (v1.2.7, verbatim): 16 query rows a warp, 64-key tiles, online softmax. +template +__device__ __forceinline__ void attend(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ out, int W, int HO, + float scale) { + static_assert(D % 16 == 0, "whole 16-dim steps"); + constexpr int C = D / 8, RS = C + 1, K16 = D / 16, NT = BN / 8, THREADS = 32 * WARPS; + extern __shared__ uint4 smem[]; + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32, g = lane / 4, qd = lane % 4, mt = lane / 8; + const int head = blockIdx.y, wrow = (blockIdx.x * WARPS + warp) * 16, last = W - 1, tiles = (W + BN - 1) / BN; + const int64_t stride = 3LL * HO * D; + const __nv_bfloat16* __restrict__ q = qkv + head * D; + const __nv_bfloat16* __restrict__ kc = qkv + (HO + head) * D; + const __nv_bfloat16* __restrict__ vc = qkv + (2 * HO + head) * D; + auto stage = [&](int t) { // tile t's K rows then V rows into buffer t % 2 + uint4* dst = smem + (t & 1) * 2 * BN * RS; + for (int i = threadIdx.x; i < 2 * BN * C; i += THREADS) { + const int kv = i / (BN * C), r = (i / C) % BN, c = i % C, key = t * BN + r; + const bool in = key < W; + cp16z(dst + (kv * BN + r) * RS + c, (kv ? vc : kc) + (int64_t)(in ? key : 0) * stride + c * 8, in); + } + commit(); + }; + uint32_t qa[K16][4]; + const int r0 = wrow + g, r1 = r0 + 8; + { + const uint32_t* q0 = reinterpret_cast(q + (int64_t)min(r0, last) * stride); + const uint32_t* q1 = reinterpret_cast(q + (int64_t)min(r1, last) * stride); +#pragma unroll + for (int k = 0; k < K16; ++k) { + qa[k][0] = r0 < W ? q0[8 * k + qd] : 0u; + qa[k][1] = r1 < W ? q1[8 * k + qd] : 0u; + qa[k][2] = r0 < W ? q0[8 * k + qd + 4] : 0u; + qa[k][3] = r1 < W ? q1[8 * k + qd + 4] : 0u; + } + } + float o[C][4]; +#pragma unroll + for (int i = 0; i < C; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.0f; + float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.0f, l1 = 0.0f; + stage(0); + for (int t = 0; t < tiles; ++t) { + cp_wait<0>(); + __syncthreads(); // tile t landed, and every warp is done with tile t - 1 + if (t + 1 < tiles) stage(t + 1); + const uint4* ks = smem + (t & 1) * 2 * BN * RS; + const uint4* vs = ks + BN * RS; + float sc[NT][4]; +#pragma unroll + for (int k = 0; k < K16; ++k) { +#pragma unroll + for (int n = 0; n < NT; n += 2) { + uint32_t b[4]; + ldmatrix4(b, ks + (8 * (n + mt / 2) + lane % 8) * RS + 2 * k + mt % 2); + if (k == 0) { + mma0(sc[n], qa[k], b[0], b[1]); + mma0(sc[n + 1], qa[k], b[2], b[3]); + } else { + mma(sc[n], qa[k], b[0], b[1]); + mma(sc[n + 1], qa[k], b[2], b[3]); + } + } + } + const int kb = t * BN + 2 * qd; + float tm0 = -INFINITY, tm1 = -INFINITY; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = c <= last ? __fmul_rn(sc[n][0], scale) : -INFINITY; + sc[n][1] = c + 1 <= last ? __fmul_rn(sc[n][1], scale) : -INFINITY; + sc[n][2] = c <= last ? __fmul_rn(sc[n][2], scale) : -INFINITY; + sc[n][3] = c + 1 <= last ? __fmul_rn(sc[n][3], scale) : -INFINITY; + tm0 = fmaxf(tm0, fmaxf(sc[n][0], sc[n][1])); + tm1 = fmaxf(tm1, fmaxf(sc[n][2], sc[n][3])); + } + for (int x = 1; x <= 2; x *= 2) { + tm0 = fmaxf(tm0, __shfl_xor_sync(0xffffffffu, tm0, x)); + tm1 = fmaxf(tm1, __shfl_xor_sync(0xffffffffu, tm1, x)); + } + const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; + const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; + const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; + const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + float c0[NT], c1[NT]; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = act0 && c <= last ? texp(__fsub_rn(sc[n][0], n0)) : 0.0f; + sc[n][1] = act0 && c + 1 <= last ? texp(__fsub_rn(sc[n][1], n0)) : 0.0f; + sc[n][2] = act1 && c <= last ? texp(__fsub_rn(sc[n][2], n1)) : 0.0f; + sc[n][3] = act1 && c + 1 <= last ? texp(__fsub_rn(sc[n][3], n1)) : 0.0f; + c0[n] = __fadd_rn(sc[n][0], sc[n][1]); + c1[n] = __fadd_rn(sc[n][2], sc[n][3]); + } + l0 = __fmaf_rn(l0, a0, rowsum(c0)); + l1 = __fmaf_rn(l1, a1, rowsum(c1)); + m0 = n0; + m1 = n1; +#pragma unroll + for (int i = 0; i < C; ++i) { + o[i][0] = __fmul_rn(o[i][0], a0); + o[i][1] = __fmul_rn(o[i][1], a0); + o[i][2] = __fmul_rn(o[i][2], a1); + o[i][3] = __fmul_rn(o[i][3], a1); + } +#pragma unroll + for (int j = 0; j < NT / 2; ++j) { // 16-key chunks, in key order for every output tile + const uint32_t pa[4] = {pack(sc[2 * j][0], sc[2 * j][1]), pack(sc[2 * j][2], sc[2 * j][3]), + pack(sc[2 * j + 1][0], sc[2 * j + 1][1]), pack(sc[2 * j + 1][2], sc[2 * j + 1][3])}; +#pragma unroll + for (int i = 0; i < C; i += 2) { + uint32_t b[4]; + ldmatrix4t(b, vs + (16 * j + 8 * (mt % 2) + lane % 8) * RS + i + mt / 2); + mma(o[i], pa, b[0], b[1]); + mma(o[i + 1], pa, b[2], b[3]); + } + } + } +#pragma unroll + for (int i = 0; i < C; ++i) { + const int d = 8 * i + 2 * qd; + if (r0 < W) + *reinterpret_cast(out + ((int64_t)r0 * HO + head) * D + d) = + pack(tdiv(o[i][0], l0), tdiv(o[i][1], l0)); + if (r1 < W) + *reinterpret_cast(out + ((int64_t)r1 * HO + head) * D + d) = + pack(tdiv(o[i][2], l1), tdiv(o[i][3], l1)); + } +} + +} // namespace ink2v + +using namespace ink2v; + +// Block a head and 128 rows: every row of one picture over all its rows (no mask), q | k | v heads of qkv [W, 3 H 64]. +extern "C" __global__ void __launch_bounds__(256) tf_ink2v_attention(const __nv_bfloat16* __restrict__ qkv, + __nv_bfloat16* __restrict__ out, int W, int HO, + float scale) { + attend(qkv, out, W, HO, scale); +} + +// Block a sequence row: row 0 the class token bf16(cls + cls_pos), row r the patch r - 1 plus its resampled position. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_embed(const __nv_bfloat16* __restrict__ pe, + const __nv_bfloat16* __restrict__ table, + const uint32_t* __restrict__ taps, + const float* __restrict__ wts, + const __nv_bfloat16* __restrict__ cls, + const __nv_bfloat16* __restrict__ cls_pos, + __nv_bfloat16* __restrict__ x) { + const int r = blockIdx.x; + for (int c = threadIdx.x; c < kWidth; c += kThreads) { + float v; + if (r == 0) { + v = __fadd_rn(bf(cls[c]), bf(cls_pos[c])); + } else { + const int p = r - 1; + float s = 0.0f; + for (int t = 0; t < 4; ++t) s = __fadd_rn(s, __fmul_rn(bf(table[(int64_t)taps[p * 4 + t] * kWidth + c]), wts[p * 4 + t])); + v = __fadd_rn(bf(pe[(int64_t)p * kWidth + c]), bf(tobf(s))); + } + x[(int64_t)r * kWidth + c] = tobf(v); + } +} + +// Block a row: q and k of qkv [rows, 3 H 64] turned in place, pair j by cos, sin [rows][32]; fp32 as torch, then bf16. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_rope(__nv_bfloat16* __restrict__ qkv, const float* __restrict__ cs, + const float* __restrict__ sn) { + const int r = blockIdx.x; + for (int i = threadIdx.x; i < 2 * kHeads * kPairs; i += kThreads) { + const int j = i % kPairs; + __nv_bfloat16* p = qkv + (int64_t)r * 3 * kWidth + (i / kPairs) * kDim + 2 * j; + const float c = cs[r * kPairs + j], s = sn[r * kPairs + j], a = bf(p[0]), b = bf(p[1]); + p[0] = tobf(__fadd_rn(__fmul_rn(a, c), __fmul_rn(-b, s))); + p[1] = tobf(__fadd_rn(__fmul_rn(b, c), __fmul_rn(a, s))); + } +} + +// x [count] = bf16(x + bf16(gamma[i % width] y)): the layer-scaled residual add of an attention or MLP output. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_scale_add(__nv_bfloat16* __restrict__ x, const __nv_bfloat16* __restrict__ y, + const __nv_bfloat16* __restrict__ gamma, int64_t count) { + const int64_t i = (int64_t)blockIdx.x * kThreads + threadIdx.x; + if (i >= count) return; + x[i] = tobf(__fadd_rn(bf(x[i]), bf(tobf(__fmul_rn(bf(gamma[i % kWidth]), bf(y[i])))))); +} diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index a448fb73d8d..b24f4ea1efe 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -1,7 +1,8 @@ //! Inkling 2's CUDA kernels: their compile records, one file per kernel group. const attn = @import("inkling2_attn_records.zig"); const ops = @import("inkling2_ops_records.zig"); +const experts = @import("inkling2_experts_records.zig"); -pub const cuda = attn.cuda ++ ops.cuda; -pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132; -pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133; +pub const cuda = attn.cuda ++ ops.cuda ++ experts.cuda; +pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ experts.cuda_132; +pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ experts.cuda_133; diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig new file mode 100644 index 00000000000..c8189365e75 --- /dev/null +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -0,0 +1,22 @@ +//! Inkling 2's inkling2_experts, inkling2_vision images: every SM's compile records (nvcc 13.0, 13.2, 13.3). +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage (nvcc -cubin per SM at the images' flags); 13.2 pending, 13.3 in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_group", .symbol = "tf_ink2x_group", .image = "inkling2_experts", .threads = 1024, .dynamic = 27648, .min_sm = 80 }, .usage = .{ .{ .regs = 28, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_rows", .symbol = "tf_ink2x_rows", .image = "inkling2_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_wide", .symbol = "tf_ink2x_wide", .image = "inkling2_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 167, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_attention", .symbol = "tf_ink2v_attention", .image = "inkling2_vision", .threads = 256, .dynamic = 36864, .min_sm = 80 }, .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_embed", .symbol = "tf_ink2v_embed", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, +}; +/// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. +pub const cuda_132 = [_]registry.Override{}; +/// nvcc 13.3's: none here, as later_pending reads 13.3 from measurements/pending_133.zig (all seven launches). +pub const cuda_133 = [_]registry.Override{}; diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index c89f898270c..ba09ea61ed0 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -5,6 +5,13 @@ pub const records = [_]Override{ .{ .name = "exl3_experts tf_exl3_grouped_0", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_grouped_1", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_grouped_2", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 148, .static = 32832, .bound = 0 }, .{ .regs = 148, .static = 32832, .bound = 0 } } }, + .{ .name = "inkling2_experts tf_ink2x_group", .usage = .{ .{ .regs = 28, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 } } }, + .{ .name = "inkling2_experts tf_ink2x_rows", .usage = .{ .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 } } }, + .{ .name = "inkling2_experts tf_ink2x_wide", .usage = .{ .{ .regs = 167, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 } } }, + .{ .name = "inkling2_vision tf_ink2v_attention", .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_embed", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_rope", .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_scale_add", .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_0", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 127, .static = 32832, .bound = 0 }, .{ .regs = 127, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_1", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_2", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 } } }, diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 68f917f8362..c365ca57ba0 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -114,6 +114,9 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; +pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; +pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; +pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; diff --git a/zig/src/families/inkling2/experts.zig b/zig/src/families/inkling2/experts.zig new file mode 100644 index 00000000000..2d0d017d95f --- /dev/null +++ b/zig/src/families/inkling2/experts.zig @@ -0,0 +1,148 @@ +//! Inkling 2's routed experts: the family's grouping and grouped projections, main's rotation and combine. +const std = @import("std"); +const cuda = @import("cuda"); +const ops = @import("ops.zig"); + +const ex = cuda.exl3_experts; + +/// The two SwiGLU softcaps (config.json mlp_gate_softcap, mlp_up_softcap). +pub const Caps = struct { gate: f32, up: f32 }; + +/// Calls of at least this many rows take an item list (runs of one expert's members), not one item an expert. +pub const listed_from = 17; +/// Calls of at least this many rows take the prompt kernel (32 members by 64 columns a block). +pub const wide_from = 512; + +/// main's experts module beside the family's grouped projections. +pub const Kernels = struct { + main: ex.Experts, + mod: cuda.Module, + group: cuda.Function, + rows: cuda.Function, + wide: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + var main = try ex.Experts.load(d); + errdefer main.unload(); + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_experts); + errdefer mod.unload(); + return .{ + .main = main, + .mod = mod, + .group = try mod.function("tf_ink2x_group"), + .rows = try mod.function("tf_ink2x_rows"), + .wide = try mod.function("tf_ink2x_wide"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.main.unload(); + } +}; + +fn i32d(v: usize) i32 { + return @intCast(v); +} + +fn align256(n: usize) usize { + return (n + 255) / 256 * 256; +} + +/// Items at most a call of `rows` rows lists: runs of 16 members, plus one partial run a distinct expert. +fn maxItems(l: ex.Layer, rows: usize, slots: usize) usize { + const p = rows * slots; + return (p + 15) / 16 + @min(p, l.experts); +} + +/// main's scratch, then the item count and the item list (three int32 an item). +pub fn scratchBytes(l: ex.Layer, rows: usize, slots: usize) !usize { + return try ex.scratchBytes(l, rows, slots) + 256 + align256(maxItems(l, rows, slots) * 12); +} + +/// Where the item count sits in scratch laid out by ex.scratch over scratchBytes(); the list follows 256 bytes on. +fn itemsAt(l: ex.Layer, sc: ex.Scratch) u64 { + return sc.members + align256(@min(sc.rows * sc.slots, l.experts) * sc.rows * 4); +} + +/// exl3_experts.Experts.run's launches in its order: the family's grouped projections, ops.cu's tf_ink2_gateup. +pub fn run(e: *const Kernels, k: *const ops.Kernels, s: cuda.Stream, l: ex.Layer, caps: Caps, x: u64, x_stride: usize, x_dtype: ex.DType, pick: u64, wts: u64, rows: usize, out: u64, sc: ex.Scratch) !void { + const d = l.dims; + const w = l.width; + const slots = sc.slots; + if (rows < 1 or rows > sc.rows or slots < 1 or slots > 32) return error.BadExperts; + if (l.experts < 1 or l.experts > 512 or l.codebook != .mul1 or l.gu_stride != 0) return error.BadExperts; + const g_sk = try ex.plan(d, w, true); + const d_sk = try ex.plan(w, d, false); + const p = rows * slots; + const maxu = @min(p, l.experts); + + const listed = rows >= listed_from; + const wide = rows >= wide_from; + const per: usize = if (wide) 32 else 16; + const at = itemsAt(l, sc); + var a: cuda.Args = .{}; + for ([_]u64{ pick, sc.ids, sc.count, sc.members, at + 256, at }) |v| a.add(v); + for ([_]usize{ rows, slots, l.experts, rows, if (listed) per else 0, @intFromBool(!listed) }) |v| a.add(i32d(v)); + const shared: u32 = @intCast(l.experts * (32 * 2 + 2 * 4)); // per-warp uint16 counts, then counts and places + try cuda.launch.launch(e.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = shared }, s, &a); + const items: u64 = if (listed) at + 256 else 0; + const count: u64 = if (listed) at else sc.count; + const gy: u32 = @intCast(if (listed) (p + per - 1) / per + maxu else maxu); + const f = if (wide) e.wide else e.rows; + const cols: usize = if (wide) 64 else 128; + + var r: cuda.Args = .{}; + r.add(x); + r.add(i32d(x_stride)); + r.add(@as(i32, @backingInt(x_dtype))); + for ([_]u64{ pick, l.suh_g, l.suh_u, sc.xg, sc.xu }) |v| r.add(v); + for ([_]usize{ d, slots, l.experts }) |v| r.add(i32d(v)); + const rot: cuda.Dim3 = .{ .x = @intCast(p), .y = @intCast(d / 128), .z = 2 }; + try cuda.launch.launch(e.main.rot_in, .{ .grid = rot, .block = .{ .x = 32 } }, s, &r); + + var g: cuda.Args = .{}; + for ([_]u64{ sc.xg, sc.xu, l.gate, l.up, l.gate_k2, l.up_k2, sc.ids }) |v| g.add(v); + for ([_]u64{ items, count, sc.members, sc.z }) |v| g.add(v); + for ([_]usize{ d, w, p, g_sk, rows, slots }) |v| g.add(i32d(v)); + const gu: cuda.Dim3 = .{ .x = @intCast(w / cols), .y = gy, .z = @intCast(2 * g_sk) }; + try cuda.launch.launch(f, .{ .grid = gu, .block = .{ .x = 128 } }, s, &g); + + try ops.gateup(k, s, .{ .z = sc.z, .pick = pick, .svh_g = l.svh_g, .svh_u = l.svh_u, .suh_d = l.suh_d, .xd = sc.xd, .p = i32d(p), .n = i32d(w), .sk = i32d(g_sk), .experts = i32d(l.experts), .gate_cap = caps.gate, .up_cap = caps.up }); + + var dn: cuda.Args = .{}; + for ([_]u64{ sc.xd, sc.xd, l.down, l.down, l.down_k2, l.down_k2, sc.ids }) |v| dn.add(v); + for ([_]u64{ items, count, sc.members, sc.z }) |v| dn.add(v); + for ([_]usize{ w, d, p, d_sk, rows, slots }) |v| dn.add(i32d(v)); + const down: cuda.Dim3 = .{ .x = @intCast(d / cols), .y = gy, .z = @intCast(d_sk) }; + try cuda.launch.launch(f, .{ .grid = down, .block = .{ .x = 128 } }, s, &dn); + + var cb: cuda.Args = .{}; + for ([_]u64{ sc.z, pick, l.svh_d, sc.y, wts, out }) |v| cb.add(v); + for ([_]usize{ p, d, d_sk, l.experts, slots }) |v| cb.add(i32d(v)); + const comb: cuda.Dim3 = .{ .x = @intCast(rows), .y = @intCast(d / 128) }; + try cuda.launch.launch(e.main.down_combine, .{ .grid = comb, .block = .{ .x = @intCast(32 * slots) } }, s, &cb); +} + +test "experts: Inkling's expert shapes have built tiles (gate/up 4608 -> 2304 whole and a rank's 1152, down back)" { + try std.testing.expectEqual(@as(u32, 4), try ex.plan(4608, 2304, true)); + try std.testing.expectEqual(@as(u32, 4), try ex.plan(4608, 1152, true)); + _ = try ex.plan(2304, 4608, false); + _ = try ex.plan(1152, 4608, false); +} + +test "experts: the item list sits past main's scratch and holds a 2,048-row call's items" { + var l = std.mem.zeroes(ex.Layer); + l.experts = 384; + l.dims = 4608; + l.width = 1152; + l.codebook = .mul1; + const bytes = try scratchBytes(l, 2048, 8); + const sc = try ex.scratch(0, l, 2048, 8); + const at = itemsAt(l, sc); + try std.testing.expectEqual(@as(u64, try ex.scratchBytes(l, 2048, 8)), at); + try std.testing.expectEqual(@as(usize, 16384 / 16 + 384), maxItems(l, 2048, 8)); + try std.testing.expect(at + 256 + maxItems(l, 2048, 8) * 12 <= bytes); + // the kernels' column blocks: the rows kernel 128 columns, the wide one 64, of a rank's 1152 and the 4608 width + try std.testing.expect(1152 % 128 == 0 and 4608 % 128 == 0); +} diff --git a/zig/src/families/inkling2/image.zig b/zig/src/families/inkling2/image.zig new file mode 100644 index 00000000000..9b62e00d518 --- /dev/null +++ b/zig/src/families/inkling2/image.zig @@ -0,0 +1,242 @@ +//! Inkling 2's image processor on the host: Inkling2ImageProcessor's 40-pixel patches and the tower's input tables. +const std = @import("std"); +const core = @import("core"); + +const picture = core.picture; +const b16 = core.bf16_round; + +pub const side = 40; // pixels a decoder token covers: the native 20-pixel patch, 2 x 2 merged +pub const patch = 20; +pub const merge = 2; +pub const grid = 32; // the learned position table's side +pub const patch_width = 3 * patch * patch; // a native patch's inputs: row, column, channel +pub const pairs = 32; // rotary pairs a 64-wide head: 16 by column, then 16 by row +const theta: f32 = 10000; +const pad: f32 = -1; // pixels outside the picture, on the 0-255 scale +const mean: f32 = 0.5 * 255.0; // the fused mean and std (0.5 each, rescale 1/255) as fp32 +const std_: f32 = 0.5 * 255.0; + +/// The release's placeholder: one per decoder image token, its rows replaced by the tower's. +pub const image_token: u32 = 200054; +/// The chat template's marker ahead of an image's placeholders. +pub const image_marker = "<|content_image|>"; + +/// One picture: its normalized patches ([tokens][40][40][3] fp32, the processor's pixel_values) and its grid. +pub const Prepared = struct { + pixels: []f32, + rows: u32, + cols: u32, + + pub fn tokens(p: Prepared) u32 { + return p.rows * p.cols; + } + + pub fn deinit(p: *Prepared, a: std.mem.Allocator) void { + a.free(p.pixels); + p.* = undefined; + } +}; + +/// Decoder tokens a picture of `w` x `h` pixels takes: no resize, one per 40-pixel cell of the padded grid. +pub fn tokensFor(w: usize, h: usize) usize { + return ((h + side - 1) / side) * ((w + side - 1) / side); +} + +/// PNG, JPEG or WebP bytes as the processor reads them: EXIF-oriented, alpha over its 8-pixel checkerboard. +pub fn decode(io: std.Io, a: std.mem.Allocator, bytes: []const u8, limits: picture.Limits) picture.Error!picture.Rgb { + const s = switch (picture.sniff(bytes)) { + .png => try picture.png.decodeWithLimits(a, bytes, limits), + .jpeg => try picture.jpeg.decodeWithLimits(io, a, bytes, limits), + .webp => try picture.webp.decodeWithLimits(io, a, bytes, limits), + .unknown => return error.Invalid, + }; + defer a.free(s.data); + if (s.channels != 4) return picture.finish(a, s); + // orient the alpha with the colours (finish on a 4-channel copy keeps it), then composite + const rgba = try a.alloc(u8, s.width * s.height * 4); + defer a.free(rgba); + const turned = orient4(s, rgba); + const out = try a.alloc(u8, turned.w * turned.h * 3); + for (0..turned.h) |y| for (0..turned.w) |x| { + const px = rgba[(y * turned.w + x) * 4 ..][0..4]; + const bg: u32 = if ((y / 8 + x / 8) % 2 == 0) 204 else 153; + for (out[(y * turned.w + x) * 3 ..][0..3], px[0..3]) |*c, v| c.* = over(v, px[3], bg); + }; + return .{ .width = turned.w, .height = turned.h, .pixels = out }; +} + +/// The processor's composite: (c * alpha + bg * (255 - alpha) + 127) // 255 in integers. +pub fn over(c: u8, alpha: u8, bg: u32) u8 { + return @intCast((@as(u32, c) * alpha + bg * (255 - alpha) + 127) / 255); +} + +/// picture.finish's transpose of 4-channel samples into `out`. +fn orient4(s: picture.Samples, out: []u8) struct { w: usize, h: usize } { + const o = if (s.orientation >= 2 and s.orientation <= 8) s.orientation else 1; + const w, const h = if (o >= 5) .{ s.height, s.width } else .{ s.width, s.height }; + for (0..h) |y| for (0..w) |x| { + const sx, const sy = switch (o) { + 2 => .{ s.width - 1 - x, y }, + 3 => .{ s.width - 1 - x, s.height - 1 - y }, + 4 => .{ x, s.height - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, s.height - 1 - x }, + 7 => .{ s.width - 1 - y, s.height - 1 - x }, + 8 => .{ s.width - 1 - y, x }, + else => .{ x, y }, + }; + @memcpy(out[(y * w + x) * 4 ..][0..4], s.data[(sy * s.width + sx) * 4 ..][0..4]); + }; + return .{ .w = w, .h = h }; +} + +/// RGB rows to the processor's pixel_values: padded with -1 to the 40-pixel grid, (v - 127.5) / 127.5 in fp32. +pub fn patches(a: std.mem.Allocator, img: picture.Rgb) !Prepared { + const rows: u32 = @intCast((img.height + side - 1) / side); + const cols: u32 = @intCast((img.width + side - 1) / side); + const px = try a.alloc(f32, @as(usize, rows) * cols * side * side * 3); + for (0..rows) |r| for (0..cols) |c| for (0..side) |y| for (0..side) |x| { + const iy = r * side + y; + const ix = c * side + x; + const at = ((((r * cols + c) * side + y) * side) + x) * 3; + for (0..3) |ch| { + const v: f32 = if (iy < img.height and ix < img.width) @floatFromInt(img.pixels[(iy * img.width + ix) * 3 + ch]) else pad; + px[at + ch] = (v - mean) / std_; + } + }; + return .{ .pixels = px, .rows = rows, .cols = cols }; +} + +/// Bytes to patches: decode, then patches; refuses pictures over `max_tokens`. +pub fn prepare(io: std.Io, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !Prepared { + var img = try decode(io, a, bytes, .{}); + defer img.deinit(a); + if (tokensFor(img.width, img.height) > max_tokens) return error.ImageTooLarge; + return patches(a, img); +} + +/// The words for a refusal of prepare's own. +pub fn explain(err: anyerror) ?[]const u8 { + return switch (err) { + error.ImageTooLarge => "image too large for the tower's limit (one token per 40 x 40 pixels, no resize)", + error.Invalid => picture.problem(error.Invalid), + error.Oversized => picture.problem(error.Oversized), + error.Animated => picture.problem(error.Animated), + else => picture.decoderProblem(err), + }; +} + +/// Native patches a picture holds: 4 a token, in merge order (token raster, then the 2 x 2 block raster). +pub fn patchCount(p: Prepared) usize { + return @as(usize, p.tokens()) * merge * merge; +} + +/// A merge-order patch's (row, column) on the native patch grid. +pub fn place(i: usize, cols: u32) [2]usize { + const t = i / (merge * merge); + const in = i % (merge * merge); + return .{ t / cols * merge + in / merge, t % cols * merge + in % merge }; +} + +/// The patch embedding's input rows as bf16 bits: [patches][row][column][channel] (the tower's reshape). +pub fn patchRows(p: Prepared, out: []u16) void { + for (0..patchCount(p)) |i| { + const t = i / (merge * merge); + const my = i % (merge * merge) / merge; + const mx = i % merge; + for (0..patch) |y| for (0..patch) |x| for (0..3) |ch| { + const v = p.pixels[((t * side + my * patch + y) * side + mx * patch + x) * 3 + ch]; + out[i * patch_width + (y * patch + x) * 3 + ch] = b16.bits(v); + }; + } +} + +/// One axis's two bilinear taps and weights (torch's align_corners=False interpolation, edge taps clamped). +const Taps = struct { t: [2]u32, w: [2]f32 }; + +fn axis(index: usize, size: usize) Taps { + const src = (@as(f32, @floatFromInt(index)) + 0.5) * @as(f32, grid) / @as(f32, @floatFromInt(size)) - 0.5; + const fl = @floor(src); + var out: Taps = undefined; + for (0..2) |o| { + const raw = @as(i64, @intFromFloat(fl)) + @as(i64, @intCast(o)); + out.t[o] = @intCast(std.math.clamp(raw, 0, grid - 1)); + out.w[o] = @max(1 - @abs(src - fl - @as(f32, @floatFromInt(o))), 0); + } + return out; +} + +/// Each patch's four position-table rows and fp32 weights (h0 w0, h0 w1, h1 w0, h1 w1), as the tower resamples. +pub fn positionTaps(p: Prepared, taps: []u32, weights: []f32) void { + const H = @as(usize, p.rows) * merge; + const W = @as(usize, p.cols) * merge; + for (0..patchCount(p)) |i| { + const rc = place(i, p.cols); + const h = axis(rc[0], H); + const w = axis(rc[1], W); + for (0..2) |a| for (0..2) |b| { + taps[i * 4 + a * 2 + b] = h.t[a] * grid + w.t[b]; + weights[i * 4 + a * 2 + b] = h.w[a] * w.w[b]; + }; + } +} + +/// Rotary cos and sin a sequence row ([rows][32] fp32): row 0 the class token at (0, 0), patch i at its place + 1. +pub fn rotary(p: Prepared, cs: []f32, sn: []f32, on: bool) void { + var inv: [pairs / 2]f32 = undefined; + for (&inv, 0..) |*f, i| f.* = 1.0 / std.math.pow(f32, theta, @as(f32, @floatFromInt(2 * i)) / @as(f32, pairs)); + for (0..patchCount(p) + 1) |r| { + const rc: [2]usize = if (r == 0) .{ 0, 0 } else blk: { + const q = place(r - 1, p.cols); + break :blk .{ q[0] + 1, q[1] + 1 }; + }; + for (0..pairs) |j| { + const pos: f32 = @floatFromInt(if (j < pairs / 2) rc[1] else rc[0]); + const ang = pos * inv[j % (pairs / 2)]; + cs[r * pairs + j] = if (on) @cos(ang) else 1; + sn[r * pairs + j] = if (on) @sin(ang) else 0; + } + } +} + +test "tokens: one per 40-pixel cell, padded up" { + try std.testing.expectEqual(@as(usize, 15), tokensFor(200, 120)); + try std.testing.expectEqual(@as(usize, 117), tokensFor(333, 517)); + try std.testing.expectEqual(@as(usize, 2), tokensFor(37, 45)); +} + +test "checkerboard composite as the processor rounds it" { + try std.testing.expectEqual(@as(u8, 10), over(10, 255, 204)); + try std.testing.expectEqual(@as(u8, 204), over(10, 0, 204)); + try std.testing.expectEqual(@as(u8, (100 * 128 + 153 * 127 + 127) / 255), over(100, 128, 153)); +} + +test "merge order and bilinear taps against torch's interpolation formula" { + try std.testing.expectEqual([2]usize{ 0, 1 }, place(1, 5)); + try std.testing.expectEqual([2]usize{ 1, 0 }, place(2, 5)); + try std.testing.expectEqual([2]usize{ 0, 2 }, place(4, 5)); + try std.testing.expectEqual([2]usize{ 2, 0 }, place(20, 5)); + // a 6-patch axis on the 32 grid: src = (i + 0.5) * 32 / 6 - 0.5 + const a0 = axis(0, 6); + try std.testing.expectEqual([2]u32{ 2, 3 }, a0.t); + try std.testing.expectApproxEqAbs(@as(f32, 0.8333333), a0.w[0], 1e-6); + const e = axis(0, 64); // src -0.25: floor -1 clamped to 0 twice, weights 0.25 and 0.75 + try std.testing.expectEqual([2]u32{ 0, 0 }, e.t); + try std.testing.expectEqual([2]f32{ 0.25, 0.75 }, e.w); +} + +test "patches: padding reads -1 on the 0-255 scale, the patch rows reorder by 20-pixel blocks" { + const a = std.testing.allocator; + var px: [41 * 3]u8 = @splat(0); + px[40 * 3] = 255; + var p = try patches(a, .{ .width = 41, .height = 1, .pixels = &px }); + defer p.deinit(a); + try std.testing.expectEqual(@as(u32, 2), p.cols); + try std.testing.expectEqual(@as(f32, -1), p.pixels[0]); + try std.testing.expectEqual(@as(f32, (-1 - 127.5) / 127.5), p.pixels[3 * side]); + try std.testing.expectEqual(@as(f32, 1), p.pixels[side * side * 3]); + const rows = try a.alloc(u16, patchCount(p) * patch_width); + defer a.free(rows); + patchRows(p, rows); + try std.testing.expectEqual(b16.bits(1), rows[4 * patch_width]); // token 1's first patch, pixel (0, 0) +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 4185398f138..d55f6ae813b 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -1,7 +1,11 @@ //! Inkling 2 Small (model_type inkling2) on CUDA: config, chat, reply split, admission, kernels, EXL3 weights, forward. +pub const image = @import("image.zig"); +pub const vision = @import("vision.zig"); pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); +pub const experts = @import("experts.zig"); +pub const modelopt = @import("modelopt.zig"); pub const loop = @import("loop.zig"); pub const loop_model = @import("loop_model.zig"); @@ -9,8 +13,12 @@ pub const loop_model = @import("loop_model.zig"); pub const model_type = "inkling2"; test { + _ = image; + _ = vision; _ = kernels; _ = ops; + _ = experts; + _ = modelopt; _ = loop; _ = loop_model; } diff --git a/zig/src/families/inkling2/modelopt.zig b/zig/src/families/inkling2/modelopt.zig new file mode 100644 index 00000000000..322a81e8bf3 --- /dev/null +++ b/zig/src/families/inkling2/modelopt.zig @@ -0,0 +1,454 @@ +//! Inkling 2 Mini's routed experts: stored NVFP4/MXFP8 codes, bf16 activations and fp32 routing. +const std = @import("std"); +const cuda = @import("cuda"); +const experts = @import("experts.zig"); +const core = @import("core"); + +pub const Format = enum(i32) { nvfp4 = 0, mxfp8 = 1 }; +pub const max_slots = 32; +const max_experts = 512; + +pub const Projection = struct { + codes: u64, + scales: u64, + amax: u64 = 0, + denominator: u64 = 0, + n: u32, + k: u32, +}; + +/// One physical layer. Loop visits share these device pointers. +pub const Layer = struct { + format: Format, + experts: u32, + w13: Projection, + w2: Projection, +}; + +const Weight = extern struct { + codes: u64, + scales: u64, + amax: u64, + denominator: u64, + experts: i64, + n: i64, + k: i64, + group: i32, + format: i32, + row0: i32, + row_step: i32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + plan: cuda.Function, + decode: cuda.Function, + prompt: cuda.Function, + act: cuda.Function, + combine: cuda.Function, + resident: usize, + + pub fn load(d: *const cuda.Driver, sms: usize) !Kernels { + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_modelopt); + errdefer mod.unload(); + const decode = try mod.function("tf_ink2moe_up"); + return .{ + .mod = mod, + .plan = try mod.function("tf_ink2moe_plan"), + .decode = decode, + .prompt = try mod.function("tf_ink2moe_prompt_up"), + .act = try mod.function("tf_ink2moe_act"), + .combine = try mod.function("tf_ink2moe_combine"), + .resident = @max(1, try decode.occupancy(128, 0)) * sms, + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } +}; + +fn aligned(n: usize) usize { + return (n + 255) / 256 * 256; +} + +pub const Layout = struct { + gate: u64, + up: u64, + act: u64, + down: u64, + items: u64, + item_count: u64, + members: u64, + bytes: usize, +}; + +/// Reconstructs the stable intermediate addresses inside one scratch allocation. +pub fn layout(base: u64, rows: usize, slots: usize, hidden: usize, intermediate: usize) Layout { + const pairs = rows * slots; + const items_max = (pairs + 15) / 16 + @min(pairs, max_experts); + var at = base; + const take = struct { + fn f(p: *u64, bytes: usize) u64 { + const r = p.*; + p.* = r + aligned(bytes); + return r; + } + }.f; + const gate = take(&at, pairs * intermediate * 2); + const up = take(&at, pairs * intermediate * 2); + const act = take(&at, pairs * intermediate * 2); + const down = take(&at, pairs * hidden * 2); + const items = take(&at, items_max * 12); + const item_count = take(&at, 4); + const members = take(&at, pairs * 4); + return .{ .gate = gate, .up = up, .act = act, .down = down, .items = items, .item_count = item_count, .members = members, .bytes = at - base }; +} + +/// Gate, up, activation and per-expert outputs, plus the ascending-expert group plan. +pub fn scratchBytes(rows: usize, slots: usize, hidden: usize, intermediate: usize) !usize { + if (rows == 0 or rows > 2048 or slots == 0 or slots > max_slots) return error.BadExperts; + return layout(0, rows, slots, hidden, intermediate).bytes; +} + +fn i32d(v: usize) i32 { + return @intCast(v); +} + +fn weight(p: Projection, l: Layer, row0: i32, row_step: i32) Weight { + return .{ + .codes = p.codes, + .scales = p.scales, + .amax = p.amax, + .denominator = p.denominator, + .experts = l.experts, + .n = p.n, + .k = p.k, + .group = if (l.format == .nvfp4) 16 else 32, + .format = @backingInt(l.format), + .row0 = row0, + .row_step = row_step, + }; +} + +fn projection(s: cuda.Stream, fn_: cuda.Function, prompt: bool, resident: usize, x: u64, x_stride: usize, slots: usize, w: Weight, items: u64, item_count: u64, members: u64, out: u64, item_bound: usize) !void { + const kg: usize = @intCast(@divExact(w.k, 32)); + const outputs: usize = @intCast(if (w.row_step == 2) @divExact(w.n, 2) else w.n); + const nb = outputs / 32; + var a: cuda.Args = .{}; + a.add(x); + a.add(i32d(x_stride)); + a.add(i32d(slots)); + a.add(w); + a.add(i32d(kg)); + a.add(i32d(nb)); + for ([_]u64{ items, item_count, members, out }) |v| a.add(v); + a.add(i32d(outputs)); + a.add(@as(i32, -1)); + const bound = item_bound * nb; + const grid = if (prompt) (bound + 3) / 4 else @min((bound + 3) / 4, resident); + if (grid == 0) return; + try cuda.launch.launch(fn_, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, s, &a); +} + +/// Run one MoE layer. `pick` is row-major int32 expert IDs; routing `weights` are fp32. +pub fn run(k: *const Kernels, s: cuda.Stream, l: Layer, caps: experts.Caps, x: u64, x_stride: usize, pick: u64, weights: u64, rows: usize, slots: usize, out: u64, scratch: u64) !void { + if (rows == 0 or rows > 2048 or slots == 0 or slots > max_slots or l.experts == 0 or l.experts > max_experts) return error.BadExperts; + if (l.w13.n % 64 != 0 or l.w13.k % 32 != 0 or l.w2.n % 32 != 0 or l.w2.k % 32 != 0) return error.BadExperts; + if (l.w13.k != l.w2.n or l.w13.n / 2 != l.w2.k or x_stride < l.w13.k) return error.BadExperts; + const hidden: usize = l.w2.n; + const intermediate: usize = l.w2.k; + const pairs = rows * slots; + const b = layout(scratch, rows, slots, hidden, intermediate); + const listed = rows >= 32; + const tile: usize = if (listed) 64 else 16; + const item_bound = (pairs + tile - 1) / tile + @min(pairs, @as(usize, l.experts)); + + var g: cuda.Args = .{}; + for ([_]u64{ pick, b.items, b.members, b.item_count }) |v| g.add(v); + for ([_]usize{ rows, slots, l.experts, tile }) |v| g.add(i32d(v)); + try cuda.launch.launch(k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, s, &g); + + const fn_ = if (listed) k.prompt else k.decode; + try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 0, 2), b.items, b.item_count, b.members, b.gate, item_bound); + try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 1, 2), b.items, b.item_count, b.members, b.up, item_bound); + + var aa: cuda.Args = .{}; + for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); + aa.add(i32d(pairs * intermediate)); + aa.add(caps.gate); + aa.add(caps.up); + try cuda.launch.launch(k.act, .{ .grid = .{ .x = @intCast((pairs * intermediate + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &aa); + try projection(s, fn_, listed, k.resident, b.act, intermediate, 0, weight(l.w2, l, 0, 1), b.items, b.item_count, b.members, b.down, item_bound); + + var ca: cuda.Args = .{}; + for ([_]u64{ pick, weights, b.down, out }) |v| ca.add(v); + for ([_]i32{ i32d(rows), i32d(hidden), i32d(slots), i32d(l.experts) }) |v| ca.add(v); + const count = rows * hidden; + try cuda.launch.launch(k.combine, .{ .grid = .{ .x = @intCast((count + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &ca); +} + +fn put(e: anytype, bytes: []const u8) !u64 { + const p = try e.alloc(bytes.len); + try e.arena.upload(p - e.arena.ptr, bytes); + return p; +} + +fn loadProjection(e: anytype, ck: *core.Checkpoint, prefix: []const u8, name: []const u8, format: Format, count: usize, n: usize, k: usize) !Projection { + var wb: [256]u8 = undefined; + var sb: [256]u8 = undefined; + const weight_name = try std.fmt.bufPrint(&wb, "{s}{s}_weight", .{ prefix, name }); + const scale_name = try std.fmt.bufPrint(&sb, "{s}{s}_weight_scale", .{ prefix, name }); + const w = switch (format) { + .nvfp4 => try ck.expect(weight_name, .u8, &.{ count, n, k / 2 }), + .mxfp8 => try ck.expect(weight_name, .f8_e4m3, &.{ count, n, k }), + }; + const scales = switch (format) { + .nvfp4 => try ck.expect(scale_name, .f8_e4m3, &.{ count, n, k / 16 }), + .mxfp8 => try ck.expect(scale_name, .u8, &.{ count, n, k / 32 }), + }; + var p: Projection = .{ .codes = try put(e, w.bytes), .scales = try put(e, scales.bytes), .n = @intCast(n), .k = @intCast(k) }; + if (format == .nvfp4) { + var ab: [256]u8 = undefined; + var db: [256]u8 = undefined; + const amax = try ck.expect(try std.fmt.bufPrint(&ab, "{s}{s}_weight_amax", .{ prefix, name }), .f32, &.{count}); + const denominator = try ck.expect(try std.fmt.bufPrint(&db, "{s}{s}_weight_outer_scale_denominator", .{ prefix, name }), .f32, &.{1}); + p.amax = try put(e, amax.bytes); + p.denominator = try put(e, denominator.bytes); + } + return p; +} + +/// Upload the checkpoint's two stored projections without a repack or an activation-quantization side input. +pub fn load(e: anytype, ck: *core.Checkpoint, prefix: []const u8, format: Format, count: usize, hidden: usize, intermediate: usize) !Layer { + if (count == 0 or count > max_experts or hidden % 32 != 0 or intermediate % 32 != 0) return error.BadExperts; + return .{ + .format = format, + .experts = @intCast(count), + .w13 = try loadProjection(e, ck, prefix, "w13", format, count, 2 * intermediate, hidden), + .w2 = try loadProjection(e, ck, prefix, "w2", format, count, hidden, intermediate), + }; +} + +test "Mini's expert scratch holds all tensor-core stages and the group plan" { + const bytes = try scratchBytes(2048, 8, 2304, 1152); + try std.testing.expectEqual(@as(usize, 72), @sizeOf(Weight)); + try std.testing.expect(bytes > 2048 * 8 * (3 * 1152 + 2304) * 2); + try std.testing.expectEqual(@as(i32, 0), @backingInt(Format.nvfp4)); + try std.testing.expectEqual(@as(i32, 1), @backingInt(Format.mxfp8)); + try std.testing.expectError(error.BadExperts, scratchBytes(0, 8, 2304, 1152)); +} + +/// One-member warp: A/B lanes explicit; exact rationals expose scalar/mma FP32 reduction diffs despite BF16 rounding. +const FragmentHostProbe = struct { + const expert_count = 2; + const hidden = 64; // two 32-column output blocks in the down projection + const intermediate = 64; // two gate/up blocks and two 32-input groups in down + const gate_cap = 4; + const up_cap = 25; + + const Matrix = struct { + codes: []const u8, + scales: []const u8, + n: usize, + k: usize, + + /// Checkpoint NVFP4 -> BF16, with outer scale one to isolate fragment addressing. + fn decoded(m: Matrix, e: usize, row: usize, col: usize) u16 { + const z = (e * m.n + row) * m.k + col; + const nib = (m.codes[z / 2] >> @as(u3, @intCast(4 * (col & 1)))) & 15; + const magnitude = ([8]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[nib & 7]; + const q = if ((nib & 8) != 0) -magnitude else magnitude; + const scale_code = m.scales[z / 16]; + const se = (scale_code >> 3) & 15; + const sm = scale_code & 7; + const sign: u32 = if ((scale_code & 128) != 0) 0x80000000 else 0; + const scale: f32 = if (se == 0) + @as(f32, @floatFromInt(sm)) * 0x1p-9 * (if (sign != 0) @as(f32, -1) else 1) + else + @bitCast(sign | ((@as(u32, se) + 120) << 23) | (@as(u32, sm) << 20)); + return core.bf16_round.bits(q * scale); + } + }; + + fn value(bits: u16) f32 { + return core.bf16_round.value(bits); + } + + fn fill(codes: []u8, scales: []u8, e: usize, n: usize, k: usize, one_per_row: bool) void { + const order = [16]u8{ 2, 10, 4, 13, 1, 7, 14, 0, 3, 9, 5, 12, 6, 15, 11, 8 }; + const scale_codes = [4]u8{ 0x28, 0x30, 0x2c, 0x34 }; // 1/4, 1/2, 3/8, 3/4 + for (0..n) |row| for (0..k) |col| { + const z = (e * n + row) * k + col; + const index = (7 * row + 11 * col + (row * col) % 13 + 3 * e) & 15; + var code = order[index]; + // Down's one nonzero rotates through all K positions over the two output tiles. + if (one_per_row and col != (19 * row + 7 * e) % k) code = 0; + if (one_per_row and col == (19 * row + 7 * e) % k and (code & 7) == 0) code = 2; + if ((col & 1) == 0) codes[z / 2] = code else codes[z / 2] |= code << 4; + if ((col & 15) == 0) scales[z / 16] = scale_codes[(3 * row + col / 16 + e) & 3]; + }; + } + + /// The arithmetic baseline: dequantize row-major weights and evaluate x @ W directly. + fn scalarProjection(m: Matrix, e: usize, row0: usize, row_step: usize, x: []const u16, out: []u16) void { + for (out, 0..) |*o, col| { + var sum: f32 = 0; + const row = row0 + row_step * col; + for (0..m.k) |k| sum += value(x[k]) * value(m.decoded(e, row, k)); + o.* = core.bf16_round.bits(sum); + } + } + + /// Served RT=1 (ten max): materialize uint2/uint4 A/B; m16n8k16 D gathers PTX lanes, B column 2*t+n, not lane gq. + fn fragmentProjection(m: Matrix, e: usize, row0: usize, row_step: usize, x: []const u16, out: []u16, members: usize) void { + const width = out.len / members; + for (0..width / 32) |cb| { + var acc: [32][4][4]f32 = std.mem.zeroes([32][4][4]f32); + for (0..m.k / 32) |g| { + // [lane][row half][q][uint2 member][BF16 in the member] + var a: [32][2][2][2][2]f32 = std.mem.zeroes([32][2][2][2][2]f32); + // Four ld_w uint4s: [n8 tile][lane][eight BF16 values in x,y,z,w]. + var b: [4][32][8]f32 = undefined; + for (0..32) |lane| { + const gq = lane >> 2; + const t = lane & 3; + for (0..2) |h| for (0..2) |q| for (0..2) |pair| for (0..2) |element| { + const i = gq + 8 * h; + // x = X + token*x_stride + 4*t; uint2 spans two adjacent pairs. + const col = 32 * g + 16 * q + 4 * t + 2 * pair + element; + a[lane][h][q][pair][element] = if (i < members) value(x[col]) else 0; + }; + for (0..4) |j| for (0..8) |i| { + const row = row0 + row_step * (cb * 32 + 8 * j + gq); + const col = g * 32 + 4 * t + (i & 3) + 16 * (i >> 2); + b[j][lane][i] = value(m.decoded(e, row, col)); + }; + } + for (0..2) |q| for (0..4) |j| for (0..32) |lane| { + const gq = lane >> 2; + const t = lane & 3; + for (0..2) |h| for (0..2) |n| { + const output_col = 2 * t + n; + var dot: f32 = 0; + for (0..16) |kk| { + // uint2 A/B permute mma K as 4*t+(0,1,2,3), valid only together; gather both source lanes. + const a_lane = 4 * gq + kk / 4; + const b_lane = 4 * output_col + kk / 4; + const av = a[a_lane][h][q][(kk & 3) / 2][kk & 1]; + const bv = b[j][b_lane][4 * q + (kk & 3)]; + dot += av * bv; + } + acc[lane][j][2 * h + n] += dot; + }; + }; + } + // Every valid member uses its own lane group's D row, including h=1,q=1. + for (0..32) |lane| for (0..2) |h| { + const member = (lane >> 2) + 8 * h; + if (member >= members) continue; + for (0..4) |j| for (0..2) |n| { + const col = cb * 32 + 8 * j + 2 * (lane & 3) + n; + out[member * width + col] = core.bf16_round.bits(acc[lane][j][2 * h + n]); + }; + }; + } + } + + fn reference(m13: Matrix, m2: Matrix, x: []const u16) [hidden]u16 { + var gate: [expert_count * intermediate]u16 = undefined; + var up: [expert_count * intermediate]u16 = undefined; + var act: [expert_count * intermediate]u16 = undefined; + var down: [expert_count * hidden]u16 = undefined; + var out: [hidden]u16 = undefined; + for (0..expert_count) |e| { + scalarProjection(m13, e, 0, 2, x, gate[e * intermediate ..][0..intermediate]); + scalarProjection(m13, e, 1, 2, x, up[e * intermediate ..][0..intermediate]); + for (0..intermediate) |j| { + const raw = value(gate[e * intermediate + j]); + const gc = gate_cap * @as(f32, @floatCast(std.math.tanh(raw / gate_cap))); + const uc = up_cap * @as(f32, @floatCast(std.math.tanh(value(up[e * intermediate + j]) / up_cap))); + const sigmoid: f32 = 1 / (1 + @exp(-raw)); + act[e * intermediate + j] = core.bf16_round.bits(gc * sigmoid * uc); + } + scalarProjection(m2, e, 0, 1, act[e * intermediate ..][0..intermediate], down[e * hidden ..][0..hidden]); + } + // Routing is slot 0 -> expert 1 (+3/4), slot 1 -> expert 0 (-3/8). + for (&out, 0..) |*o, col| { + var total: f32 = 0; + total += -0.375 * value(down[col]); + total += 0.75 * value(down[hidden + col]); + o.* = core.bf16_round.bits(total); + } + return out; + } + + fn model(m13: Matrix, m2: Matrix, x: []const u16) [hidden]u16 { + var gate: [expert_count * intermediate]u16 = undefined; + var up: [expert_count * intermediate]u16 = undefined; + var act: [expert_count * intermediate]u16 = undefined; + var down: [expert_count * hidden]u16 = undefined; + var out: [hidden]u16 = undefined; + for (0..expert_count) |e| { + fragmentProjection(m13, e, 0, 2, x, gate[e * intermediate ..][0..intermediate], 1); + fragmentProjection(m13, e, 1, 2, x, up[e * intermediate ..][0..intermediate], 1); + for (0..intermediate) |j| { + const raw = value(gate[e * intermediate + j]); + const gc = gate_cap * @as(f32, @floatCast(std.math.tanh(raw / gate_cap))); + const uc = up_cap * @as(f32, @floatCast(std.math.tanh(value(up[e * intermediate + j]) / up_cap))); + const sigmoid: f32 = 1 / (1 + @exp(-raw)); + act[e * intermediate + j] = core.bf16_round.bits(gc * sigmoid * uc); + } + fragmentProjection(m2, e, 0, 1, act[e * intermediate ..][0..intermediate], down[e * hidden ..][0..hidden], 1); + } + for (&out, 0..) |*o, col| { + var total: f32 = 0; + total += -0.375 * value(down[col]); + total += 0.75 * value(down[hidden + col]); + o.* = core.bf16_round.bits(total); + } + return out; + } + + fn checkMembers(m13: Matrix, x: []const u16) !void { + const members = 10; + var tensor: [members * intermediate]u16 = undefined; + var scalar: [intermediate]u16 = undefined; + scalarProjection(m13, 0, 0, 2, x, &scalar); + fragmentProjection(m13, 0, 0, 2, x, &tensor, members); + var first_difference: ?usize = null; + for (tensor, 0..) |got, i| if (got != scalar[i % intermediate]) { + first_difference = i; + break; + }; + try std.testing.expectEqual(@as(?usize, null), first_difference); + } + + fn check() !void { + var codes13: [expert_count * 2 * intermediate * hidden / 2]u8 = undefined; + var scales13: [expert_count * 2 * intermediate * hidden / 16]u8 = undefined; + var codes2: [expert_count * hidden * intermediate / 2]u8 = undefined; + var scales2: [expert_count * hidden * intermediate / 16]u8 = undefined; + for (0..expert_count) |e| { + fill(&codes13, &scales13, e, 2 * intermediate, hidden, false); + fill(&codes2, &scales2, e, hidden, intermediate, true); + } + const m13: Matrix = .{ .codes = &codes13, .scales = &scales13, .n = 2 * intermediate, .k = hidden }; + const m2: Matrix = .{ .codes = &codes2, .scales = &scales2, .n = hidden, .k = intermediate }; + var x: [hidden]u16 = undefined; + for (&x, 0..) |*v, i| v.* = core.bf16_round.bits(@as(f32, @floatFromInt(@as(i32, @intCast(i % 13)) - 6)) / 128); + const got = model(m13, m2, &x); + const want = reference(m13, m2, &x); + var first_difference: ?usize = null; + for (got, want, 0..) |g, w, i| if (g != w) { + first_difference = i; + break; + }; + try std.testing.expectEqual(@as(?usize, null), first_difference); + try checkMembers(m13, &x); + } +}; + +test "one token: m16n8k16 fragment pipeline matches independent BF16 dequantization" { + try FragmentHostProbe.check(); +} diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig new file mode 100644 index 00000000000..eced25b1697 --- /dev/null +++ b/zig/src/families/inkling2/vision.zig @@ -0,0 +1,400 @@ +//! Inkling 2's vision tower on CUDA in bf16: patch embedding, 23 ViT layers with axial rotary, the 2 x 2 projector. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const image = @import("image.zig"); + +const vit = cuda.vit; + +pub const width = 1024; +pub const heads = 16; +pub const head_dim = 64; +pub const depth = 23; +pub const mlp_inter = 4096; +pub const proj_inter = 4096; +pub const hidden = 4608; // the decoder's width +const merged = image.merge * image.merge * width; // a token's four patch rows side by side +const eps: f32 = 1e-5; +const pre = "model.visual.backbone."; +/// The checkpoint names the tower reads (source shards and the pack's vision sidecar alike). +pub const prefixes = [_][]const u8{"model.visual."}; +/// Image tokens a tower's scratch covers when the caller names no limit: 1280 x 1280 pixels. +pub const default_tokens: u32 = 1024; +const attn_smem: u32 = 2 * 2 * 64 * (head_dim / 8 + 1) * 16; + +/// The family's tower kernels (inkling2/vision.cu). +pub const Kernels = struct { + mod: cuda.Module, + attention: cuda.Function, + embed: cuda.Function, + rope: cuda.Function, + scale_add: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_vision); + errdefer mod.unload(); + const k: Kernels = .{ + .mod = mod, + .attention = try mod.function("tf_ink2v_attention"), + .embed = try mod.function("tf_ink2v_embed"), + .rope = try mod.function("tf_ink2v_rope"), + .scale_add = try mod.function("tf_ink2v_scale_add"), + }; + try k.attention.allowDynamicShared(attn_smem); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// The tower's tensors: a pack's vision.safetensors sidecar (as the release stores them), else the model's shards. +fn openTower(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !core.Checkpoint { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, "{s}/" ++ sidecar, .{dir}); + std.Io.Dir.cwd().access(io, path, .{}) catch return core.Checkpoint.openModelPrefixes(gpa, io, dir, &prefixes); + var ck: core.Checkpoint = .{ .gpa = gpa, .io = io }; + errdefer ck.close(); + try ck.add(dir, sidecar); + return ck; +} + +/// The file a pack carries the tower in, copied unchanged from the release's shards. +pub const sidecar = "vision.safetensors"; + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, shared: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads }, .shared = shared }, s, a); +} + +const Layer = struct { ln1_w: u64, ln1_b: u64, qkv_w: u64, qkv_b: u64, out_w: u64, out_b: u64, ls1: u64, ln2_w: u64, ln2_b: u64, fc1_w: u64, fc1_b: u64, fc2_w: u64, fc2_b: u64, ls2: u64 }; + +/// What one image row of scratch costs: patch inputs, x/xn/att/y, qkv, mid, the f32 bias sums, tables. +const row_bytes: u64 = image.patch_width * 2 + 4 * width * 2 + 3 * width * 2 + mlp_inter * 2 + mlp_inter * 4 + 4 * 4 + 4 * 4 + 2 * image.pairs * 4; + +/// Scratch for pictures of up to `tokens` decoder tokens, plus cuBLASLt's workspace. +pub fn scratchBytes(tokens: u32) u64 { + const rows: u64 = @as(u64, tokens) * image.merge * image.merge + 1; + return rows * row_bytes + @as(u64, tokens) * proj_inter * 2 + (32 << 20); +} + +/// The tower's weights and scratch on one GPU. +pub const Tower = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + k: Kernels, + vk: vit.Kernels, + g: vit.Gemms, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + max_tokens: u32, + patch_w: u64 = 0, // [width][1200]: a native patch's row, column, channel + table: u64 = 0, // [32 * 32][width] position rows + cls: u64 = 0, + cls_pos: u64 = 0, + pre_w: u64 = 0, + pre_b: u64 = 0, + proj_in: u64 = 0, // [4096][4096], no bias + proj_out: u64 = 0, // [hidden][4096], no bias + layers: [depth]Layer = undefined, + px: u64 = 0, // bf16 [P][1200] + x: u64 = 0, // bf16 [R][width]: the residual stream (row 0 the class token) + xn: u64 = 0, + att: u64 = 0, + y: u64 = 0, + qkv: u64 = 0, // bf16 [R][3 width] + mid: u64 = 0, // bf16 [R][mlp_inter] + acc: u64 = 0, // f32 [R][mlp_inter]: a Linear's sums when cuBLASLt cannot fuse its bias + taps: u64 = 0, // u32 [P][4] + wts: u64 = 0, // f32 [P][4] + cs: u64 = 0, // f32 [R][32] + sn: u64 = 0, + p1: u64 = 0, // bf16 [T][proj_inter] + bytes: u64 = 0, + /// Layers encode runs (a parity tool stops early to read a layer's output at `x`). + layers_run: usize = depth, + + fn alloc(t: *Tower, n: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(t.d, @max(n, 256)); + errdefer b.free(); + try t.bufs.append(t.gpa, b); + t.bytes += n; + return b.ptr; + } + + fn up(t: *Tower, bytes: []const u8) !u64 { + const p = try t.alloc(bytes.len); + try t.d.check(t.d.api.cuMemcpyHtoD_v2(p, bytes.ptr, bytes.len), "cuMemcpyHtoD"); + return p; + } + + fn get(t: *Tower, ck: *core.Checkpoint, name: []const u8, dims: []const usize) !u64 { + return t.up((try ck.expect(name, .bf16, dims)).bytes); + } + + /// The tower from the checkpoint at `dir` (its model.visual.* tensors, bf16 as released), scratch for `max_tokens`. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, max_tokens: u32) !*Tower { + if (max_tokens == 0) return error.ImageTokens; + const t = try gpa.create(Tower); + errdefer gpa.destroy(t); + var k = try Kernels.load(d); + errdefer k.unload(); + var vk = try vit.Kernels.load(d); + errdefer vk.unload(); + t.* = .{ .gpa = gpa, .d = d, .k = k, .vk = vk, .g = try vit.Gemms.init(gpa, d), .max_tokens = max_tokens }; + errdefer { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(gpa); + t.g.deinit(); + } + var ck = try openTower(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + t.patch_w = try t.get(&ck, pre ++ "embeddings.patch_embedding.weight", &.{ width, image.patch_width }); + t.table = try t.get(&ck, pre ++ "embeddings.position_embedding", &.{ image.grid * image.grid, width }); + t.cls = try t.get(&ck, pre ++ "embeddings.class_embedding", &.{width}); + t.cls_pos = try t.get(&ck, pre ++ "embeddings.cls_position_embedding", &.{width}); + t.pre_w = try t.get(&ck, pre ++ "ln_pre.weight", &.{width}); + t.pre_b = try t.get(&ck, pre ++ "ln_pre.bias", &.{width}); + t.proj_in = try t.get(&ck, "model.visual.proj_in.weight", &.{ proj_inter, merged }); + t.proj_out = try t.get(&ck, "model.visual.proj_out.weight", &.{ hidden, proj_inter }); + const w = try gpa.alloc(u8, 3 * width * width * 2); + defer gpa.free(w); + for (&t.layers, 0..) |*l, i| { + var nb: [128]u8 = undefined; + const at = struct { + fn f(buf: *[128]u8, li: usize, comptime rel: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, pre ++ "layers.{d}." ++ rel, .{li}); + } + }.f; + l.ln1_w = try t.get(&ck, try at(&nb, i, "ln_1.weight"), &.{width}); + l.ln1_b = try t.get(&ck, try at(&nb, i, "ln_1.bias"), &.{width}); + l.ln2_w = try t.get(&ck, try at(&nb, i, "ln_2.weight"), &.{width}); + l.ln2_b = try t.get(&ck, try at(&nb, i, "ln_2.bias"), &.{width}); + l.ls1 = try t.get(&ck, try at(&nb, i, "ls_1.gamma"), &.{width}); + l.ls2 = try t.get(&ck, try at(&nb, i, "ls_2.gamma"), &.{width}); + // q | k | v stacked by rows, their biases likewise: one Linear, heads as the attention reads them + var b: [3 * width * 2]u8 = undefined; + inline for (.{ "q", "k", "v" }, 0..) |which, j| { + const wt = try ck.expect(try at(&nb, i, "self_attn." ++ which ++ "_proj.weight"), .bf16, &.{ width, width }); + @memcpy(w[j * width * width * 2 ..][0 .. width * width * 2], wt.bytes); + const bt = try ck.expect(try at(&nb, i, "self_attn." ++ which ++ "_proj.bias"), .bf16, &.{width}); + @memcpy(b[j * width * 2 ..][0 .. width * 2], bt.bytes); + } + l.qkv_w = try t.up(w); + l.qkv_b = try t.up(&b); + l.out_w = try t.get(&ck, try at(&nb, i, "self_attn.out_proj.weight"), &.{ width, width }); + l.out_b = try t.get(&ck, try at(&nb, i, "self_attn.out_proj.bias"), &.{width}); + l.fc1_w = try t.get(&ck, try at(&nb, i, "mlp.c_fc.weight"), &.{ mlp_inter, width }); + l.fc1_b = try t.get(&ck, try at(&nb, i, "mlp.c_fc.bias"), &.{mlp_inter}); + l.fc2_w = try t.get(&ck, try at(&nb, i, "mlp.c_proj.weight"), &.{ width, mlp_inter }); + l.fc2_b = try t.get(&ck, try at(&nb, i, "mlp.c_proj.bias"), &.{width}); + } + const P: usize = @as(usize, max_tokens) * image.merge * image.merge; + const R = P + 1; + t.px = try t.alloc(P * image.patch_width * 2); + inline for (.{ "x", "xn", "att", "y" }) |f| @field(t, f) = try t.alloc(R * width * 2); + t.qkv = try t.alloc(R * 3 * width * 2); + t.mid = try t.alloc(R * mlp_inter * 2); + t.acc = try t.alloc(R * mlp_inter * 4); + t.taps = try t.alloc(P * 4 * 4); + t.wts = try t.alloc(P * 4 * 4); + t.cs = try t.alloc(R * image.pairs * 4); + t.sn = try t.alloc(R * image.pairs * 4); + t.p1 = try t.alloc(@as(usize, max_tokens) * proj_inter * 2); + return t; + } + + /// The device bytes load takes for `dir`: the tower's tensors as stored, scratch and workspace for `max_tokens`. + pub fn bytesFor(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, max_tokens: u32) !u64 { + var ck = try openTower(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var total: u64 = scratchBytes(max_tokens); + for (ck.files.items) |*f| for (f.names.keys()) |name| { + total += f.get(name).?.bytes.len; + }; + return total; + } + + pub fn deinit(t: *Tower) void { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(t.gpa); + t.g.deinit(); + t.vk.unload(); + t.k.unload(); + t.gpa.destroy(t); + } + + fn upload(t: *Tower, dst: u64, bytes: []const u8) !void { + try t.d.check(t.d.api.cuMemcpyHtoD_v2(dst, bytes.ptr, bytes.len), "cuMemcpyHtoD"); + } + + /// The host tables of one picture (patch rows, position taps, rotary; rotary off only for a planted control). + fn stage(t: *Tower, s: cuda.Stream, p: image.Prepared, rope: bool) !void { + const P = image.patchCount(p); + const rows = try t.gpa.alloc(u16, P * image.patch_width); + defer t.gpa.free(rows); + const taps = try t.gpa.alloc(u32, P * 4); + defer t.gpa.free(taps); + const wts = try t.gpa.alloc(f32, P * 4); + defer t.gpa.free(wts); + const cs = try t.gpa.alloc(f32, (P + 1) * image.pairs); + defer t.gpa.free(cs); + const sn = try t.gpa.alloc(f32, (P + 1) * image.pairs); + defer t.gpa.free(sn); + image.patchRows(p, rows); + image.positionTaps(p, taps, wts); + image.rotary(p, cs, sn, rope); + try s.synchronize(); // the previous picture's kernels may still read the tables + try t.upload(t.px, std.mem.sliceAsBytes(rows)); + try t.upload(t.taps, std.mem.sliceAsBytes(taps)); + try t.upload(t.wts, std.mem.sliceAsBytes(wts)); + try t.upload(t.cs, std.mem.sliceAsBytes(cs)); + try t.upload(t.sn, std.mem.sliceAsBytes(sn)); + } + + /// One picture to its tokens' rows at `out` (bf16 [tokens][hidden]): what replaces its placeholders' embeddings. + pub fn encode(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64) !void { + return t.encodeWith(s, p, out, true); + } + + pub fn encodeWith(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64, rope: bool) !void { + const T: usize = p.tokens(); + if (T == 0 or p.pixels.len != T * image.side * image.side * 3) return error.ImageGrid; + if (T > t.max_tokens) return error.ImageTooLarge; + try t.stage(s, p, rope); + const P = image.patchCount(p); + const R = P + 1; + try t.g.run(s, t.px, t.patch_w, t.y, P, width, image.patch_width, .bf16); + var a: cuda.Args = .{}; + for ([_]u64{ t.y, t.table, t.taps, t.wts, t.cls, t.cls_pos, t.xn }) |v| a.add(v); + try go(t.k.embed, s, .{ .x = @intCast(R) }, 256, 0, &a); + try t.vk.layerNorm(s, t.xn, t.pre_w, t.pre_b, t.x, R, width, eps); + for (t.layers[0..@min(t.layers_run, depth)]) |l| try t.layer(s, l, R); + if (t.layers_run < depth) return; + // the projector: each token's four patch rows (merge order, after the class row) as one 4096-wide row + try t.g.run(s, t.x + width * 2, t.proj_in, t.p1, T, proj_inter, merged, .bf16); + try t.vk.pointwise(s, t.p1, null, t.p1, T * proj_inter, .gelu); + try t.g.run(s, t.p1, t.proj_out, out, T, hidden, proj_inter, .bf16); + } + + fn layer(t: *Tower, s: cuda.Stream, l: Layer, R: usize) !void { + try t.vk.layerNorm(s, t.x, l.ln1_w, l.ln1_b, t.xn, R, width, eps); + try vit.linear(&t.g, &t.vk, s, t.acc, t.xn, l.qkv_w, l.qkv_b, t.qkv, R, 3 * width, width); + var a: cuda.Args = .{}; + for ([_]u64{ t.qkv, t.cs, t.sn }) |v| a.add(v); + try go(t.k.rope, s, .{ .x = @intCast(R) }, 256, 0, &a); + var b: cuda.Args = .{}; + b.add(t.qkv); + b.add(t.att); + b.add(@as(c_int, @intCast(R))); + b.add(@as(c_int, heads)); + b.add(@as(f32, 1.0 / @sqrt(@as(f32, head_dim)))); + try go(t.k.attention, s, .{ .x = @intCast((R + 127) / 128), .y = heads }, 256, attn_smem, &b); + try vit.linear(&t.g, &t.vk, s, t.acc, t.att, l.out_w, l.out_b, t.y, R, width, width); + try t.scaleAdd(s, l.ls1, R); + try t.vk.layerNorm(s, t.x, l.ln2_w, l.ln2_b, t.xn, R, width, eps); + try vit.linearAct(&t.g, &t.vk, s, t.acc, t.xn, l.fc1_w, l.fc1_b, t.mid, R, mlp_inter, width, null, t.mid, .gelu); + try vit.linear(&t.g, &t.vk, s, t.acc, t.mid, l.fc2_w, l.fc2_b, t.y, R, width, mlp_inter); + try t.scaleAdd(s, l.ls2, R); + } + + /// x = bf16(x + bf16(gamma y)), the layer scale of torch's `residual + lambda * h`. + fn scaleAdd(t: *Tower, s: cuda.Stream, gamma: u64, R: usize) !void { + const n = R * width; + var a: cuda.Args = .{}; + for ([_]u64{ t.x, t.y, gamma }) |v| a.add(v); + a.add(@as(i64, @intCast(n))); + try go(t.k.scale_add, s, .{ .x = @intCast((n + 255) / 256) }, 256, 0, &a); + } +}; + +/// Prompt rows [at, at + n) take image rows [row, row + n) (rows of the encoded pictures, in prompt order). +pub const Span = struct { at: u32, n: u32, row: u32 }; + +/// The placeholder runs of a prompt's ids: each maximal run of image_token is one picture's rows, in order. +pub fn spans(a: std.mem.Allocator, ids: []const u32) ![]Span { + var out: std.ArrayList(Span) = .empty; + errdefer out.deinit(a); + var row: u32 = 0; + var i: usize = 0; + while (i < ids.len) : (i += 1) { + if (ids[i] != image.image_token) continue; + const at = i; + while (i < ids.len and ids[i] == image.image_token) i += 1; + try out.append(a, .{ .at = @intCast(at), .n = @intCast(i - at), .row = row }); + row += @intCast(i - at); + } + return out.toOwnedSlice(a); +} + +/// The prompt's placeholders must equal the encoded pictures' rows, as transformers' get_placeholder_mask requires. +pub fn check(list: []const Span, pictures: []const image.Prepared) !void { + var want: usize = 0; + for (pictures) |p| want += p.tokens(); + var have: usize = 0; + for (list) |sp| have += sp.n; + if (have != want) return error.ImagePlaceholders; +} + +/// One copy into a pass: pass row `dst` on takes image rows from `src`, `n` of them. +pub const Copy = struct { dst: u32, src: u32, n: u32 }; + +/// The part of a placeholder run inside a pass over prompt positions [lo, hi), if any. +pub fn cut(sp: Span, lo: usize, hi: usize) ?Copy { + const a = @max(lo, sp.at); + const b = @min(hi, sp.at + sp.n); + if (a >= b) return null; + return .{ .dst = @intCast(a - lo), .src = @intCast(sp.row + (a - sp.at)), .n = @intCast(b - a) }; +} + +/// After the normed embedding, a pass's rows at positions [lo, hi) (bf16 at `x`) take their image rows (at `rows`). +pub fn splice(d: *const cuda.Driver, s: cuda.Stream, rows: u64, list: []const Span, lo: usize, hi: usize, x: u64) !void { + for (list) |sp| { + const c = cut(sp, lo, hi) orelse continue; + const row: u64 = hidden * 2; + try d.check(d.api.cuMemcpyDtoDAsync_v2(x + c.dst * row, rows + c.src * row, c.n * row, s.handle), "cuMemcpyDtoDAsync"); + } +} + +test "placeholder runs map to picture rows in prompt order" { + const a = std.testing.allocator; + const t = image.image_token; + const got = try spans(a, &.{ 1, t, t, t, 2, 3, t, t, 4 }); + defer a.free(got); + try std.testing.expectEqual(@as(usize, 2), got.len); + try std.testing.expectEqual(Span{ .at = 1, .n = 3, .row = 0 }, got[0]); + try std.testing.expectEqual(Span{ .at = 6, .n = 2, .row = 3 }, got[1]); + var px: [2 * image.side * image.side * 3]f32 = undefined; + const two = [_]image.Prepared{ .{ .pixels = &px, .rows = 1, .cols = 3 }, .{ .pixels = &px, .rows = 1, .cols = 2 } }; + try check(got, &two); + try std.testing.expectError(error.ImagePlaceholders, check(got, two[0..1])); +} + +test "chunked passes give every placeholder the row masked_scatter gives it" { + const a = std.testing.allocator; + const t = image.image_token; + const ids = [_]u32{ 7, t, t, t, t, t, 9, 9, t, 4, t, t, t, t, t, t, t, 3, 2 }; + const list = try spans(a, &ids); + defer a.free(list); + for ([_]usize{ 1, 2, 3, 5, 8, ids.len }) |chunk| { + var got: [ids.len]i32 = @splat(-1); + var lo: usize = 0; + while (lo < ids.len) : (lo += chunk) { + const hi = @min(ids.len, lo + chunk); + for (list) |sp| if (cut(sp, lo, hi)) |c| for (0..c.n) |i| { + got[lo + c.dst + i] = @intCast(c.src + i); + }; + } + var next: i32 = 0; // masked_scatter: the k-th placeholder in the prompt takes feature row k + for (ids, got) |id, g| { + try std.testing.expectEqual(if (id == t) next else -1, g); + if (id == t) next += 1; + } + } +} + +test "scratch for the default limit stays under 256 MiB" { + try std.testing.expect(scratchBytes(default_tokens) < 256 << 20); + try std.testing.expectEqual(@as(u32, 36864), attn_smem); +} diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index fccf522af06..57b41e050ae 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -1,4 +1,4 @@ -//! Inkling 2's CUDA kernels under the contract: attention, glue, drafter, experts and tower, each with controls. +//! Inkling 2's CUDA kernels under the contract: attention, glue, experts and tower, each with controls. const std = @import("std"); const cuda = @import("cuda"); const check = @import("check.zig"); @@ -9,6 +9,7 @@ pub const Set = struct { gpa: std.mem.Allocator, attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, + experts: @import("contract_inkling2_experts.zig").Set = .{}, /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -18,10 +19,14 @@ pub const Set = struct { try set.attn.init(gpu, s, a, list); errdefer set.attn.deinit(); try set.ops.init(gpu, s, a, list); + errdefer set.ops.deinit(); + try set.experts.init(gpu, s, a, list); + errdefer set.experts.deinit(); return set; } pub fn deinit(set: *Set) void { + set.experts.deinit(); set.ops.deinit(); set.attn.deinit(); set.gpa.destroy(set); diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig new file mode 100644 index 00000000000..fe5fabbd9f0 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -0,0 +1,85 @@ +//! Inkling 2's grouped experts and vision tower (inkling2/experts.cu, vision.cu) under the contract, with controls. +const std = @import("std"); +const cuda = @import("cuda"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const g = @import("core").contract.gates; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); +const grouped = @import("contract_inkling2_experts_grouped.zig"); +const vision = @import("contract_inkling2_experts_vision.zig"); +const modelopt = @import("contract_inkling2_modelopt.zig"); +const Attention = @import("contract_inkling2_experts_attn.zig").Attention; + +/// Every registration, each control after the kernel it breaks; the gates point at these fields. +pub const Set = struct { + live: bool = false, + ek: ink.experts.Kernels = undefined, + vk: ink.vision.Kernels = undefined, + mk: ink.modelopt.Kernels = undefined, + groups: [2]grouped.Group = undefined, + projections: [4]grouped.Grouped = undefined, + moe: [7]modelopt.ModelOpt = undefined, + embeds: [2]ref.Gated(vision.Embed) = undefined, + ropes: [2]ref.Gated(vision.Rope) = undefined, + adds: [2]ref.Gated(vision.ScaleAdd) = undefined, + attns: [2]Attention = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.ek = try ink.experts.Kernels.load(gpu.d); + errdefer set.ek.unload(); + set.vk = try ink.vision.Kernels.load(gpu.d); + errdefer set.vk.unload(); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + set.mk = try ink.modelopt.Kernels.load(gpu.d, sms); + errdefer set.mk.unload(); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.groups, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .wrong_run = i == 1 }; + const forms = [4]@import("contract_inkling2_experts_ref.zig").Form{ .rows, .rows, .wide, .wide }; + for (&set.projections, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = &set.ek, .form = f, .fault = if (i == 1) .short else if (i == 3) .swapped else .none }; + for (&set.moe, 0..) |*x, i| x.* = .{ + .rig = rig, + .k = &set.mk, + .format = if (i <= 2) .nvfp4 else .mxfp8, + .fault = switch (i) { + 0, 1 => .none, + 2, 3 => .wrong_combine, + 4 => .wrong_plan, + 5 => .wrong_up, + 6 => .wrong_act, + else => unreachable, + }, + }; + for (&set.embeds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; + for (&set.ropes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .swapped = i == 1 } }; + for (&set.adds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; + for (&set.attns, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.vk, .wide = i == 1 }; + set.live = true; + for (&set.groups) |*x| try list.append(a, x.kernel()); + for (&set.projections) |*x| try list.append(a, x.kernel()); + for (&set.moe) |*x| try list.append(a, x.kernel()); + for (&set.embeds) |*x| try list.append(a, x.kernel()); + for (&set.ropes) |*x| try list.append(a, x.kernel()); + for (&set.adds) |*x| try list.append(a, x.kernel()); + for (&set.attns) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.live) return; + for (&set.attns) |*x| x.deinit(); + for (&set.adds) |*x| x.deinit(); + for (&set.ropes) |*x| x.deinit(); + for (&set.embeds) |*x| x.deinit(); + for (&set.moe) |*x| x.deinit(); + for (&set.projections) |*x| x.deinit(); + for (&set.groups) |*x| x.deinit(); + set.mk.unload(); + set.vk.unload(); + set.ek.unload(); + set.live = false; + } +}; + +test { + _ = @import("contract_inkling2_experts_ref.zig"); +} diff --git a/zig/tests/cuda/contract_inkling2_experts_attn.zig b/zig/tests/cuda/contract_inkling2_experts_attn.zig new file mode 100644 index 00000000000..e914309ae75 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_attn.zig @@ -0,0 +1,282 @@ +//! tf_ink2v_attention under the contract: the tower's full attention over one picture's rows, head dim 64. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const aref = core.attention_ref; +const threads = core.contract.reference_threads; + +const D = ink.vision.head_dim; +const smem: u32 = 2 * 2 * 64 * (D / 8 + 1) * 16; // vision.zig's attn_smem + +/// The P x V chain of a row: every key, a 64-key tile at a time. +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +fn scale(wide: bool) f32 { + return 1.0 / @sqrt(@as(f32, if (wide) 128 else D)); +} + +/// Shape: heads (rows), head dim (n), sequence rows W (k): 16 heads at 1, 4 and 32 tokens, two at 256 to 4,096. +fn spec(wide: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 2, .n = D, .k = 1025 }, .{ .rows = 16, .n = D, .k = 5 }, .{ .rows = 16, .n = D, .k = 17 }, .{ .rows = 16, .n = D, .k = 129 }, .{ .rows = 2, .n = D, .k = 4097 }, .{ .rows = 2, .n = D, .k = 16385 } }; + const name = if (wide) "inkling2 experts control: tf_ink2v_attention scaled for head dim 128" else "inkling2 experts vision tf_ink2v_attention (full attention, head dim 64)"; + return .{ .name = name, .accum = .f32, .depth = keyChain, .ops = 1, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 128 } }, .served = served, .sums = .{ .why = attn.why } }; +} + +/// Gate 4's values: odd integers, every other one times 4, the second half cancelling the first (fp32 exact at 16K). +fn mirrored(rng: std.Random, out: []f32) void { + const h = out.len / 2; + for (0..h) |i| { + const v: f32 = @floatFromInt((1 + 2 * rng.uintLessThan(u32, 128)) * @as(u32, if (i % 2 == 1) 4 else 1)); + out[i] = v; + out[h + i] = (if (i < 8) @as(f32, 1) else 0) - v; + } + if (out.len % 2 == 1) out[out.len - 1] = 0; +} + +pub const Attention = struct { + rig: rig_.Rig, + k: *const ink.vision.Kernels, + wide: bool = false, // control: the score scale of head dim 128 + shape: c.Shape = undefined, + qkv: []u16 = &.{}, // [W][3 heads 64]: q heads, then k, then v + f: []f64 = &.{}, // [3][heads][W][64]: the same in float64 + keys: []usize = &.{}, + stressed: bool = false, + dev: u64 = 0, + out: u64 = 0, + msg: [240]u8 = undefined, + + pub fn deinit(self: *Attention) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Attention) void { + const a = self.rig.gpu.gpa; + a.free(self.qkv); + a.free(self.f); + a.free(self.keys); + self.qkv = &.{}; + self.f = &.{}; + self.keys = &.{}; + } + + pub fn kernel(self: *Attention) g.Kernel { + return .{ .spec = spec(self.wide), .ctx = self, .vt = &vt, .control = if (self.wide) .shapes else null }; + } + + const vt = g.hooks(Attention); + + fn heads(self: *const Attention) usize { + return self.shape.rows; + } + + fn at(self: *const Attention, row: usize, which: usize, head: usize) []u16 { + return self.qkv[row * 3 * self.heads() * D + (which * self.heads() + head) * D ..][0..D]; + } + + /// Float64 rows of q, k or v for one head: [W][64]. + fn rows(self: *const Attention, which: usize, head: usize) []const f64 { + const w = self.shape.k; + return self.f[(which * self.heads() + head) * w * D ..][0 .. w * D]; + } + + pub fn prepare(self: *Attention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != D or shape.rows == 0 or shape.k == 0) return false; + const a = self.rig.gpu.gpa; + self.free(); + self.shape = shape; + self.stressed = fill == .stress; + const W = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.qkv = try a.alloc(u16, W * 3 * shape.rows * D); + for (self.qkv) |*e| e.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.f = try a.alloc(f64, self.qkv.len); + for (0..W) |j| for (0..3) |which| for (0..shape.rows) |h| { + for (self.f[((which * shape.rows + h) * W + j) * D ..][0..D], self.at(j, which, h)) |*y, x| y.* = c.fromBf16(x); + }; + self.keys = try a.alloc(usize, W); + for (self.keys, 0..) |*k, i| k.* = i; + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.out = try self.rig.output(W * shape.rows * D * 2); + return true; + } + + /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. + fn plant(self: *Attention) void { + const L = self.shape.k; + self.at(0, 0, 0)[3] = c.toBf16(std.math.nan(f32)); + self.at(L - 1, 2, 0)[7] = c.toBf16(std.math.inf(f32)); + self.at(L / 2, 2, 0)[9] = c.toBf16(-std.math.inf(f32)); + if (L >= 3) { + self.at(1, 2, 0)[11] = c.toBf16(std.math.inf(f32)); + self.at(2, 2, 0)[11] = c.toBf16(-std.math.inf(f32)); + } + if (self.heads() > 1) self.at(L / 3, 1, 1)[5] = c.toBf16(std.math.nan(f32)); + } + + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. + fn stress(self: *Attention, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const L = self.shape.k; + var key: [D]u16 = undefined; + for (&key) |*e| e.* = attn.normal(rng); + const col = try a.alloc(f32, L); + defer a.free(col); + for (0..self.heads()) |h| { + for (0..L) |j| @memcpy(self.at(j, 1, h), &key); + for (0..D) |e| { + mirrored(rng, col); + for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); + } + } + } + + pub fn run(self: *Attention) !void { + var a: cuda.Args = .{}; + a.add(self.dev); + a.add(self.out); + a.add(@as(c_int, @intCast(self.shape.k))); + a.add(@as(c_int, @intCast(self.heads()))); + a.add(scale(self.wide)); + try cuda.launch.launch(self.k.attention, .{ .grid = .{ .x = @intCast((self.shape.k + 127) / 128), .y = @intCast(self.heads()) }, .block = .{ .x = 256 }, .shared = smem }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Attention) usize { + return self.shape.k * self.heads() * D; + } + + /// Output rows [lo, hi) (row-major over sequence row and head) checked against attention_ref on one thread. + const Job = struct { + t: *const Attention, + out: []const u8, + lo: usize, + hi: usize, + gate: g.Gate, + planted: usize = 0, + bad: ?usize = null, // first failing output + ratio: f64 = 0, + + pub fn run(j: *Job) void { + var want: [D]f64 = undefined; + var tol: [D]f64 = undefined; + const t = j.t; + const s: f64 = scale(false); + for (j.lo..j.hi) |i| { + const row = i / t.heads(); + const head = i % t.heads(); + aref.head(t.rows(0, head)[row * D ..][0..D], t.rows(1, head), t.rows(2, head), t.keys, D, s, &want, &tol); + for (want, tol, 0..) |w, tl, e| { + const got = c.read(.bf16, j.out, i * D + e); + if (c.classOf(w) != .finite) j.planted += 1; + const off = c.classOf(got) != c.classOf(w) or (j.gate != .nonfinite and std.math.isFinite(w) and !(@abs(got - w) <= tl)); + if (off and j.bad == null) { + j.bad = i * D + e; + j.ratio = @abs(got - w) / tl; + } + } + if (j.bad != null) return; + } + } + }; + + /// Gates 1 and 3: every output's class equals float64's, and a finite one is within attention_ref's bound. + pub fn check(self: *Attention, gate: g.Gate) !?[]const u8 { + const out = try self.rig.outputBytes(); + const n = self.shape.k * self.heads(); + var jobs: [threads.maximum]Job = undefined; + const parts = threads.count(threads.maximum, n); + for (jobs[0..parts], 0..) |*j, p| j.* = .{ .t = self, .out = out, .lo = n * p / parts, .hi = n * (p + 1) / parts, .gate = gate }; + threads.run(Job, jobs[0..parts], .normal); + var planted: usize = 0; + for (jobs[0..parts]) |j| { + planted += j.planted; + if (j.bad) |b| { + const got = c.read(.bf16, out, b); + return try std.fmt.bufPrint(&self.msg, "output {d} (row {d}, head {d}, dim {d}) is {e:.6}: {t}, {d:.2} of attention_ref's bound", .{ b, b / D / self.heads(), b / D % self.heads(), b % D, got, c.classOf(got), j.ratio }); + } + } + if (gate == .nonfinite and (planted == 0 or planted == n * D)) return try std.fmt.bufPrint(&self.msg, "the planted values make {d} of {d} reference outputs non-finite: no proof", .{ planted, n * D }); + return null; + } + + /// Float64 softmax(s q.k) v of one output row, and its terms' magnitude sum p |v| / sum p. + fn one(self: *const Attention, i: usize, p: []f64, want: []f64, mag: []f64) void { + const row = i / self.heads(); + const head = i % self.heads(); + const q = self.rows(0, head)[row * D ..][0..D]; + const k = self.rows(1, head); + const v = self.rows(2, head); + var m: f64 = -std.math.inf(f64); + for (p, 0..) |*x, j| { + var s: f64 = 0; + for (0..D) |e| s += q[e] * k[j * D + e]; + x.* = s * scale(false); + m = @max(m, x.*); + } + var l: f64 = 0; + for (p) |*x| { + x.* = @exp(x.* - m); + l += x.*; + } + for (0..D) |e| { + var s: f64 = 0; + var abs: f64 = 0; + for (p, 0..) |x, j| { + s += x * v[j * D + e]; + abs += x * @abs(v[j * D + e]); + } + want[i * D + e] = s / l; + mag[i * D + e] = abs / l; + } + } + + /// Gate 4 reads these; under its stress every key scores alike, so a head's rows share one output row. + pub fn reference(self: *Attention, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + const p = try a.alloc(f64, self.shape.k); + defer a.free(p); + const n = self.shape.k * self.heads(); + for (0..n) |i| { + if (self.stressed and i >= self.heads()) { + @memcpy(want[i * D ..][0..D], want[(i % self.heads()) * D ..][0..D]); + @memcpy(mag[i * D ..][0..D], mag[(i % self.heads()) * D ..][0..D]); + } else self.one(i, p, want, mag); + } + } + + /// Gate 4's sums in an accumulator: its keys score alike, so every p is 1 and the sums are V's terms and l's ones. + pub fn simulate(self: *Attention, acc: c.Accum, order: g.Order, out: []f64) !void { + if (!self.stressed) return error.SumsNeedStress; + const a = self.rig.gpu.gpa; + const L = self.shape.k; + const terms = try a.alloc(f64, L); + defer a.free(terms); + const ones = try a.alloc(f64, L); + defer a.free(ones); + @memset(ones, 1); + const l = core.contract.rows.sumIn(acc, order, ones); + for (0..self.heads()) |h| for (0..D) |e| { + const v = self.rows(2, h); + for (terms, 0..) |*x, j| x.* = v[j * D + e]; + out[h * D + e] = core.contract.rows.sumIn(acc, order, terms) / l; + }; + for (self.heads()..L * self.heads()) |i| @memcpy(out[i * D ..][0..D], out[(i % self.heads()) * D ..][0..D]); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_experts_grouped.zig b/zig/tests/cuda/contract_inkling2_experts_grouped.zig new file mode 100644 index 00000000000..1d82f7c6a2f --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_grouped.zig @@ -0,0 +1,296 @@ +//! tf_ink2x_rows, tf_ink2x_wide and tf_ink2x_group under the contract: each bit-equal to the main kernel it replaces. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_experts_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +fn i32s(v: usize) i32 { + return @intCast(v); +} + +/// One projection as experts.run launches it, on the lists tf_exl3_group writes; the baseline runs tf_exl3_grouped_2. +pub const Grouped = struct { + rig: rig_.Rig, + k: *const ink.experts.Kernels, + form: ref.Form, + fault: ref.Fault = .none, + fix: ?ref.Fixture = null, + tp: [2]u64 = .{ 0, 0 }, + k2: [2]u64 = .{ 0, 0 }, + x: [2]u64 = .{ 0, 0 }, + uids: u64 = 0, + ucount: u64 = 0, + members: u64 = 0, + items: u64 = 0, + nitems: u64 = 0, + out: u64 = 0, + base: u64 = 0, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Grouped) void { + self.drop(); + self.rig.deinit(); + } + + fn drop(self: *Grouped) void { + if (self.fix) |*f| f.deinit(); + self.fix = null; + self.rig.reset(); + } + + pub fn kernel(self: *Grouped) g.Kernel { + return .{ .spec = ref.spec(self.form, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(Grouped); + + fn put(self: *Grouped, x: anytype) !u64 { + return self.rig.input(std.mem.sliceAsBytes(x)); + } + + pub fn prepare(self: *Grouped, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!ref.Fixture.valid(shape)) return false; + self.drop(); + const a = self.rig.gpu.gpa; + self.fix = try ref.Fixture.init(a, shape, fill, seed); + const f = &self.fix.?; + var pool: [f.trellis.len]u64 = undefined; + for (&pool, f.trellis) |*p, t| p.* = try self.put(t); + const m = ref.mats(shape); + for (0..2) |mat| { + var tp: [ref.experts]u64 = undefined; + var k2: [ref.experts]i32 = undefined; + for (&tp, &k2, 0..) |*t, *h, e| { + const i = ref.Fixture.entry(e, @min(mat, m - 1)); + t.* = pool[i]; + h.* = ref.halves(i); + } + self.tp[mat] = try self.put(&tp); + self.k2[mat] = try self.put(&k2); + } + const p = f.pairs(); + const xs = p * shape.k; + self.x[0] = try self.put(f.x[0..xs]); + self.x[1] = if (m == 2) try self.put(f.x[xs..]) else self.x[0]; + var l = try ref.Lists.init(a, f.pick, shape.rows); + defer l.deinit(a); + self.uids = try self.put(l.uids); + self.ucount = try self.put(&[1]i32{l.count}); + self.members = try self.put(l.members); + const items = try a.alloc(i32, 3 * ref.maxItems(p)); + defer a.free(items); + const n = l.items(shape.rows, ref.per(self.form), items); + self.items = try self.put(items); + const listed = ref.listed(self.form, shape.rows); + const short: i32 = @intFromBool(self.fault == .short); + self.nitems = try self.put(&[1]i32{(if (listed) n else l.count) - short}); + self.out = try self.rig.output(f.outputs() * 4); + self.base = try self.rig.scratch(f.outputs() * 4); + return true; + } + + /// experts.zig's launch: WideArgs in its add order, items and their count (rows kernel below 17 rows: the groups). + fn launch(self: *Grouped) !void { + const sh = self.fix.?.shape; + const p = self.fix.?.pairs(); + const sk = self.fix.?.sk; + const listed = ref.listed(self.form, sh.rows); + const per = ref.per(self.form); + const x0 = if (self.fault == .swapped) self.x[1] else self.x[0]; + var a: cuda.Args = .{}; + for ([_]u64{ x0, self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.uids, if (listed) self.items else 0, self.nitems, self.members, self.out }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, sh.rows, ref.slots }) |v| a.add(i32s(v)); + const maxu = @min(p, ref.experts); + const gy = if (listed) (p + per - 1) / per + maxu else maxu; + const cols: usize = if (self.form == .wide) 64 else 128; + const f = if (self.form == .wide) self.k.wide else self.k.rows; + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.n / cols), .y = @intCast(gy), .z = @intCast(ref.mats(sh) * sk) }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + pub fn run(self: *Grouped) !void { + try self.launch(); + try self.rig.s.synchronize(); + } + + /// exl3_experts.Experts.run's grouped launch on the same lists: GroupedArgs, one member tile a grid z step. + pub fn replaced(self: *Grouped) ![]const u8 { + const sh = self.fix.?.shape; + const p = self.fix.?.pairs(); + const sk = self.fix.?.sk; + const maxu = @min(p, ref.experts); + const m = ref.mats(sh); + var a: cuda.Args = .{}; + for ([_]u64{ self.x[0], self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.uids, self.ucount, self.members, self.base }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, sh.rows, ref.slots, maxu, m, 0, 0 }) |v| a.add(i32s(v)); + a.add(@as(i32, -1)); + const mt = (sh.rows + 15) / 16; + try cuda.launch.launch(self.k.main.grouped[2], .{ .grid = .{ .x = @intCast(maxu), .y = @intCast(sh.n / 128), .z = @intCast(m * sk * mt) }, .block = .{ .x = 128 } }, self.rig.s, &a); + return self.rig.bytes(self.base, self.outputs() * 4); + } + + /// Gate 1: tf_exl3_grouped_2's bytes, and some output non-finite: the planted values. + pub fn check(self: *Grouped, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from tf_exl3_grouped_2's", .{ at, got.len }); + for (0..got.len / 4) |i| if (c.classOf(c.read(.f32, got, i)) != .finite) return null; + return try std.fmt.bufPrint(&self.msg, "no output is non-finite: the planted values prove nothing", .{}); + } + + fn outputs(self: *Grouped) usize { + return self.fix.?.outputs(); + } + + pub fn count(self: *Grouped) usize { + return self.outputs(); + } + + pub fn reference(self: *Grouped, want: []f64, mag: []f64) !void { + return self.fix.?.reference(want, mag); + } + + pub fn simulate(self: *Grouped, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.fix.?.simulate(acc, order, out); + } +}; + +/// Shape: token rows x slots (8) x experts (384); short calls pad members with -1, longer ones list item runs. +fn groupSpec(control: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 8, .n = ref.slots, .k = ref.experts }, .{ .rows = 1, .n = ref.slots, .k = ref.experts }, .{ .rows = 15, .n = ref.slots, .k = ref.experts }, .{ .rows = 16, .n = ref.slots, .k = ref.experts }, .{ .rows = 17, .n = ref.slots, .k = ref.experts }, .{ .rows = 128, .n = ref.slots, .k = ref.experts }, .{ .rows = 511, .n = ref.slots, .k = ref.experts }, .{ .rows = 512, .n = ref.slots, .k = ref.experts }, .{ .rows = 2048, .n = ref.slots, .k = ref.experts } }; + const name = if (control) "inkling2 experts control: tf_ink2x_group listing 16-member runs for the prompt kernel" else "inkling2 experts tf_ink2x_group (tf_exl3_group's lists, then item runs)"; + return .{ .name = name, .accum = .none, .depth = noSums, .out = .raw, .replaces = "tf_exl3_group (main's grouping), the runs its counts give", .nan = .{ .stated = "picks outside [0, experts) are left out, as tf_exl3_group leaves them" }, .tiles = .{ .{ .size = 16 }, .{}, .{} }, .served = served }; +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// tf_ink2x_group as experts.run launches it; the baseline runs tf_exl3_group and adds the runs on the host. +pub const Group = struct { + rig: rig_.Rig, + k: *const ink.experts.Kernels, + wrong_run: bool = false, + shape: c.Shape = undefined, + pick: []i32 = &.{}, + dev: u64 = 0, + outs: [5]u64 = @splat(0), // uids, count, members, items, item count + base: [3]u64 = @splat(0), + want: std.ArrayList(u8) = .empty, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Group) void { + const a = self.rig.gpu.gpa; + a.free(self.pick); + self.want.deinit(a); + self.rig.deinit(); + } + + pub fn kernel(self: *Group) g.Kernel { + return .{ .spec = groupSpec(self.wrong_run), .ctx = self, .vt = &vt, .control = if (self.wrong_run) .shapes else null }; + } + + const vt = g.hooks(Group); + + fn maxu(self: *const Group) usize { + return @min(self.shape.rows * ref.slots, ref.experts); + } + + fn sizes(self: *const Group) [5]usize { + const p = self.shape.rows * ref.slots; + return .{ self.maxu() * 4, 4, self.maxu() * self.shape.rows * 4, 3 * ref.maxItems(p) * 4, 4 }; + } + + pub fn prepare(self: *Group, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != ref.slots or shape.k != ref.experts or shape.rows * shape.n * 4 > 64 * 1024) return false; + self.rig.reset(); + const a = self.rig.gpu.gpa; + self.shape = shape; + a.free(self.pick); + self.pick = &.{}; + self.pick = try a.alloc(i32, shape.rows * ref.slots); + var prng = std.Random.DefaultPrng.init(seed); + ref.picks(prng.random(), self.pick); + if (fill == .nonfinite) { + const put = [_]i32{ -1, ref.experts, 1 << 20 }; + for (put, 0..) |v, i| self.pick[(i * 5 + 1) % self.pick.len] = v; + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.pick)); + for (&self.outs, self.sizes()) |*o, n| o.* = try self.rig.output(n); + for (&self.base, self.sizes()[0..3]) |*o, n| o.* = try self.rig.scratch(n); + return true; + } + + pub fn run(self: *Group) !void { + const rows = self.shape.rows; + const listed = rows >= ink.experts.listed_from; + const run_: usize = if (rows >= ink.experts.wide_from and !self.wrong_run) 32 else 16; + var b: cuda.Args = .{}; + for ([_]u64{ self.dev, self.outs[0], self.outs[1], self.outs[2], self.outs[3], self.outs[4] }) |v| b.add(v); + for ([_]usize{ rows, ref.slots, ref.experts, rows, if (listed) run_ else 0, @intFromBool(!listed) }) |v| b.add(i32s(v)); + const shared: u32 = @intCast(ref.experts * (32 * 2 + 2 * 4)); + try cuda.launch.launch(self.k.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = shared }, self.rig.s, &b); + try self.rig.s.synchronize(); + } + + /// tf_exl3_group's lists as written, words no launch writes as the rig poisons them, and the runs from its counts. + pub fn replaced(self: *Group) ![]const u8 { + const a = self.rig.gpu.gpa; + const rows = self.shape.rows; + var m: cuda.Args = .{}; + for ([_]u64{ self.dev, self.base[0], self.base[1], self.base[2] }) |v| m.add(v); + for ([_]usize{ rows, ref.slots, ref.experts, rows }) |v| m.add(i32s(v)); + try cuda.launch.launch(self.k.main.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = @intCast(rows * ref.slots * 4) }, self.rig.s, &m); + const sz = self.sizes(); + self.want.clearRetainingCapacity(); + try self.want.appendNTimes(a, 0xff, sz[0] + sz[1] + sz[2] + sz[3] + sz[4]); + const w = self.want.items; + const cnt = std.mem.readInt(i32, (try self.rig.bytes(self.base[1], 4))[0..4], .little); + if (cnt < 0 or @as(usize, @intCast(cnt)) > self.maxu()) return error.BadBaselineCount; + const used: usize = @intCast(cnt); + @memcpy(w[0 .. used * 4], (try self.rig.bytes(self.base[0], sz[0]))[0 .. used * 4]); + std.mem.writeInt(i32, w[sz[0]..][0..4], cnt, .little); + const mem = w[sz[0] + 4 ..][0..sz[2]]; + @memcpy(mem[0 .. used * rows * 4], (try self.rig.bytes(self.base[2], sz[2]))[0 .. used * rows * 4]); + if (rows >= ink.experts.listed_from) { + const members = try a.alloc(i32, sz[2] / 4); + defer a.free(members); + @memcpy(std.mem.sliceAsBytes(members), mem); + const l: ref.Lists = .{ .uids = &.{}, .count = cnt, .members = members }; + const items = try a.alloc(i32, sz[3] / 4); + defer a.free(items); + const n = l.items(rows, if (rows >= ink.experts.wide_from) 32 else 16, items); + const start = sz[0] + 4 + sz[2]; + for (items, 0..) |v, i| if (v >= 0) std.mem.writeInt(i32, w[start + 4 * i ..][0..4], v, .little); + std.mem.writeInt(i32, w[start + sz[3] ..][0..4], n, .little); + } + return w; + } + + /// Gate 1: the baseline's bytes with picks outside the experts planted. + pub fn check(self: *Group, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from tf_exl3_group's lists and their runs", .{ at, got.len }); + return null; + } + + pub fn count(self: *Group) usize { + var n: usize = 0; + for (self.sizes()) |s| n += s; + return n; + } + + pub fn reference(_: *Group, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_experts_ref.zig b/zig/tests/cuda/contract_inkling2_experts_ref.zig new file mode 100644 index 00000000000..9549c2b112e --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_ref.zig @@ -0,0 +1,293 @@ +//! Inkling 2's grouped experts on the host: specs, Inkling's routing and trellises, float64 sums, replays. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); + +const fmt = core.exl3_format; +const c = core.contract.spec; +const rows_ = core.contract.rows; + +pub const experts = 384; +pub const slots = 8; // top 8 +pub const hidden = 4608; +pub const width = 1152; // a rank's intermediate at TP=2: 2304 cut in 128-column blocks +const pool = 16; // distinct trellises a shape: expert e's gate takes pool[e % 16], its up pool[(7e + 3) % 16] +const warps = 4; // wide_body's W +const step: f32 = 256; // gate 4's x: multiples of 256 to 8,192, so fp16 sums of the products overflow + +/// The served kernels: decode rows and short windows (128 columns, 16 members), prompt chunks (64 columns, 32). +pub const Form = enum { rows, wide }; +/// Gate 3's planted faults, both launch arguments: the call's last item dropped, the up rows read as gate rows. +pub const Fault = enum { none, short, swapped }; + +/// Half-bits a value of pool entry i: the release's 2- and 3-bit trellises in turn. +pub fn halves(i: usize) u16 { + return if (i % 2 == 0) 4 else 6; +} + +/// exl3_experts.plan's K splits as experts.run takes them: gate and up where K > N, down otherwise. +pub fn split(s: c.Shape) usize { + return cuda.exl3_experts.plan(s.k, s.n, s.k > s.n) catch 1; +} + +/// Gate and up (two matrices, K > N), or down (one). +pub fn mats(s: c.Shape) usize { + return if (s.k > s.n) 2 else 1; +} + +/// Whether a call takes an item list: the prompt kernel always, the rows kernel from experts.listed_from rows. +pub fn listed(form: Form, rows: usize) bool { + return form == .wide or rows >= ink.experts.listed_from; +} + +/// Members a run: the prompt kernel's 32, the rows kernel's 16. +pub fn per(form: Form) usize { + return if (form == .wide) 32 else 16; +} + +/// Items experts.zig makes room for: runs of 16 members, plus one partial run a distinct expert. +pub fn maxItems(p: usize) usize { + return (p + 15) / 16 + @min(p, experts); +} + +/// A split's 16-input mma steps, the 16 products inside one, then the 4 warps' partials added in warp order. +fn depth(s: c.Shape) usize { + return s.k / split(s) / 16 + 16 + warps; +} + +fn served(rows: []const usize, comptime n: usize) [2 * n]c.Shape { + var out: [2 * n]c.Shape = undefined; + for (rows[0..n], 0..) |r, i| { + out[2 * i] = .{ .rows = r, .n = width, .k = hidden }; + out[2 * i + 1] = .{ .rows = r, .n = hidden, .k = width }; + } + return out; +} + +const rows_served = served(&.{ 8, 1, 15, 16, 17, 128, 511 }, 7); +const wide_served = served(&.{ 512, 513, 2048 }, 3); +const rule = "as tf_exl3_grouped_2 gives them: NaN and infinite inputs"; + +pub fn spec(form: Form, fault: Fault) c.Spec { + const name = switch (fault) { + .none => if (form == .rows) "inkling2 experts tf_ink2x_rows (decode rows to 511, 128 columns by 16 members)" else "inkling2 experts tf_ink2x_wide (prompt chunks from 512, 64 columns by 32 members)", + .short => "inkling2 experts control: tf_ink2x_rows launched one item short", + .swapped => "inkling2 experts control: tf_ink2x_wide reading the up rows as gate rows", + }; + const edge: c.Tile = if (form == .rows) .{ .size = 16 } else .{ .size = ink.experts.wide_from, .min = ink.experts.wide_from }; + const tiles = [3]c.Tile{ edge, .{ .size = 128, .step = 128, .min = 128 }, .{ .size = 256, .step = 64, .min = 64 } }; + const list: []const c.Shape = if (form == .rows) &rows_served else &wide_served; + return .{ .name = name, .accum = .f32, .depth = depth, .out = .f32, .replaces = "tf_exl3_grouped_2 (main's grouped experts, mul1)", .nan = .{ .stated = rule }, .tiles = tiles, .served = list, .sums = .{ .exact = false } }; +} + +/// Each row's 8 distinct experts: expert 0 in every row (long runs and a partial one), the rest at random. +pub fn picks(rng: std.Random, out: []i32) void { + for (0..out.len / slots) |r| { + const row = out[r * slots ..][0..slots]; + row[0] = 0; + var i: usize = 1; + while (i < slots) { + const e: i32 = @intCast(rng.uintLessThan(u32, experts)); + if (std.mem.indexOfScalar(i32, row[0..i], e) != null) continue; + row[i] = e; + i += 1; + } + } +} + +/// One projection's host side: the pool's trellises, the pairs' fp16 rows per matrix, each pair's expert. +pub const Fixture = struct { + a: std.mem.Allocator, + shape: c.Shape, + sk: usize, + trellis: [pool][]i16, + x: []u16, // fp16 bits [mats][pairs][k], the rotated rows + pick: []i32, // [pairs]: pair p = row * slots + slot + w: [pool][]f16 = @splat(@as([]f16, &.{})), // each entry's W_q [k][n], decoded on first use + + /// false: a shape the kernels are not built for (plan() finds no split, N not a whole number of 128s). + pub fn valid(s: c.Shape) bool { + if (s.rows == 0 or s.n == 0 or s.k == 0 or s.n % 128 != 0) return false; + _ = cuda.exl3_experts.plan(s.k, s.n, s.k > s.n) catch return false; + return true; + } + + pub fn init(a: std.mem.Allocator, s: c.Shape, fill: rows_.Fill, seed: u64) !Fixture { + var f: Fixture = .{ .a = a, .shape = s, .sk = split(s), .trellis = @splat(@as([]i16, &.{})), .x = &.{}, .pick = &.{} }; + errdefer f.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (&f.trellis, 0..) |*t, i| { + t.* = try a.alloc(i16, s.k / 16 * (s.n / 16) * @as(usize, halves(i)) * 8); + for (t.*) |*v| v.* = rng.int(i16); + } + const p = f.pairs(); + f.pick = try a.alloc(i32, p); + picks(rng, f.pick); + f.x = try a.alloc(u16, mats(s) * p * s.k); + for (f.x) |*v| v.* = bits(rng.float(f32) * 4 - 2); + switch (fill) { + .random => {}, + .nonfinite => { + const k = s.k; + const at = [_][2]usize{ .{ 0, k / 3 }, .{ 1, k / 2 }, .{ 2, k - 1 }, .{ 3, 0 }, .{ 3, k - 1 } }; + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (at, put) |q, v| if (q[0] < p) { + f.x[q[0] * k + q[1]] = bits(v); + }; + }, + .stress => for (f.x) |*v| { + v.* = bits(step * @as(f32, @floatFromInt(1 + rng.uintLessThan(u32, 32)))); + }, + } + return f; + } + + pub fn deinit(f: *Fixture) void { + for (f.trellis) |t| f.a.free(t); + for (f.w) |w| f.a.free(w); + f.a.free(f.x); + f.a.free(f.pick); + f.* = undefined; + } + + pub fn pairs(f: *const Fixture) usize { + return f.shape.rows * slots; + } + + pub fn outputs(f: *const Fixture) usize { + return mats(f.shape) * f.sk * f.pairs() * f.shape.n; + } + + /// The pool entry matrix `mat` of expert e reads. + pub fn entry(e: usize, mat: usize) usize { + return if (mat == 0) e % pool else (7 * e + 3) % pool; + } + + fn weights(f: *Fixture, i: usize) ![]const f16 { + if (f.w[i].len > 0) return f.w[i]; + const s = f.shape; + f.w[i] = try f.a.alloc(f16, s.k * s.n); + fmt.unpack(.{ .halves = halves(i) }, .mul1, f.trellis[i], s.k / 16, s.n / 16, f.w[i]); + return f.w[i]; + } + + /// The terms output (mat, split, pair, column) sums: x times W_q over the split's K range, in K order. + fn terms(f: *Fixture, mat: usize, sp: usize, p: usize, j: usize, t: []f64) !void { + const s = f.shape; + const e: usize = @intCast(f.pick[p]); + const w = try f.weights(entry(e, mat)); + const per_split = s.k / f.sk; + const x = f.x[(mat * f.pairs() + p) * s.k ..]; + for (t, sp * per_split..) |*o, i| o.* = value(x[i]) * @as(f64, w[i * s.n + j]); + } + + fn each(f: *Fixture, ctx: anytype, comptime body: fn (@TypeOf(ctx), usize, []const f64) void) !void { + const t = try f.a.alloc(f64, f.shape.k / f.sk); + defer f.a.free(t); + for (0..mats(f.shape)) |mat| for (0..f.sk) |sp| for (0..f.pairs()) |p| for (0..f.shape.n) |j| { + try f.terms(mat, sp, p, j, t); + body(ctx, (((mat * f.sk) + sp) * f.pairs() + p) * f.shape.n + j, t); + }; + } + + pub fn reference(f: *Fixture, want: []f64, mag: []f64) !void { + const Ctx = struct { want: []f64, mag: []f64 }; + try f.each(Ctx{ .want = want, .mag = mag }, struct { + fn body(x: Ctx, o: usize, t: []const f64) void { + var sum: f64 = 0; + var abs: f64 = 0; + for (t) |v| { + sum += v; + abs += @abs(v); + } + x.want[o] = sum; + x.mag[o] = abs; + } + }.body); + } + + pub fn simulate(f: *Fixture, acc: c.Accum, order: rows_.Order, out: []f64) !void { + const Ctx = struct { acc: c.Accum, order: rows_.Order, out: []f64 }; + try f.each(Ctx{ .acc = acc, .order = order, .out = out }, struct { + fn body(x: Ctx, o: usize, t: []const f64) void { + x.out[o] = rows_.sumIn(x.acc, x.order, t); + } + }.body); + } +}; + +/// The lists tf_exl3_group writes for `pick`: distinct experts in id order, members row * 32 + slot, -1 after them. +pub const Lists = struct { + uids: []i32, + count: i32, + members: []i32, // [min(pairs, experts)][rows] + + pub fn init(a: std.mem.Allocator, pick: []const i32, rows: usize) !Lists { + const maxu = @min(pick.len, experts); + const uids = try a.alloc(i32, maxu); + errdefer a.free(uids); + const members = try a.alloc(i32, maxu * rows); + @memset(members, -1); + var used: usize = 0; + for (0..experts) |e| { + var m: usize = 0; + for (pick, 0..) |pe, p| if (pe == e) { + members[used * rows + m] = @intCast(p / slots * 32 + p % slots); + m += 1; + }; + if (m == 0) continue; + uids[used] = @intCast(e); + used += 1; + } + return .{ .uids = uids, .count = @intCast(used), .members = members }; + } + + pub fn deinit(l: *Lists, a: std.mem.Allocator) void { + a.free(l.uids); + a.free(l.members); + } + + /// tf_ink2x_group's items for runs of `run` members: (u, first, count) in expert order, -1 words after them. + pub fn items(l: Lists, rows: usize, run: usize, out: []i32) i32 { + @memset(out, -1); + var n: usize = 0; + for (0..@intCast(l.count)) |u| { + const m = l.members[u * rows ..][0..rows]; + const cnt = std.mem.indexOfScalar(i32, m, -1) orelse rows; + var first: usize = 0; + while (first < cnt) : (first += run) { + out[3 * n ..][0..3].* = .{ @intCast(u), @intCast(first), @intCast(@min(run, cnt - first)) }; + n += 1; + } + } + return @intCast(n); + } +}; + +fn bits(v: f32) u16 { + return @bitCast(@as(f16, @floatCast(v))); +} + +fn value(h: u16) f64 { + return @as(f16, @bitCast(h)); +} + +test "inkling2 experts contract: every served shape has a split, items fit experts.zig's room" { + for (rows_served ++ wide_served) |s| { + try std.testing.expect(Fixture.valid(s)); + try std.testing.expectEqual(@as(usize, 0), s.k % (split(s) * 16 * warps)); + } + try std.testing.expectEqual(@as(usize, 4), split(rows_served[0])); + var prng = std.Random.DefaultPrng.init(1); + const pick = try std.testing.allocator.alloc(i32, 2048 * slots); + defer std.testing.allocator.free(pick); + picks(prng.random(), pick); + var l = try Lists.init(std.testing.allocator, pick, 2048); + defer l.deinit(std.testing.allocator); + const out = try std.testing.allocator.alloc(i32, 3 * maxItems(pick.len)); + defer std.testing.allocator.free(out); + try std.testing.expect(l.items(2048, 16, out) <= maxItems(pick.len)); + try std.testing.expectEqual(@as(i32, 0), l.uids[0]); +} diff --git a/zig/tests/cuda/contract_inkling2_experts_vision.zig b/zig/tests/cuda/contract_inkling2_experts_vision.zig new file mode 100644 index 00000000000..976a8ce7448 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_vision.zig @@ -0,0 +1,275 @@ +//! Inkling 2's tower glue (vision.cu) under the contract: patch rows to the sequence, axial rotary, layer-scaled adds. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; +const Kernels = ink.vision.Kernels; + +const width = ink.vision.width; +const qkv_width = 3 * width; +const pairs = ink.vision.head_dim / 2; +const grid = 1024; // the position table's rows (32 x 32) + +/// Sequence rows R = 4 T + 1 (the class row, then four patches a token): 1, 4, 256, 1,024 and 4,096 tokens. +fn tower(comptime n: usize, comptime k: usize) [5]c.Shape { + var out: [5]c.Shape = undefined; + for (&out, [_]usize{ 17, 5, 1025, 4097, 16385 }) |*s, r| s.* = .{ .rows = r, .n = n, .k = k }; + return out; +} + +const embed_served = tower(width, 4); +const rope_served = tower(qkv_width, 1); +const add_served = tower(width, 1); + +fn four(_: c.Shape) usize { + return 4; +} + +fn launch(f: cuda.Function, s: cuda.Stream, blocks: usize, args: []const u64, tail: ?i64) !void { + var a: cuda.Args = .{}; + for (args) |v| a.add(v); + if (tail) |t| a.add(t); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(blocks) }, .block = .{ .x = 256 } }, s, &a); +} + +/// Row 0 bf16(cls + cls_pos); row r bf16(pe + bf16(sum of four table rows times their bilinear weights, in fp32)). +pub const Embed = struct { + kern: *const Kernels, + late: bool = false, // control: each weight read one tap late + shape: c.Shape = undefined, + pe: []u16 = &.{}, + table: []u16 = &.{}, + taps: []u32 = &.{}, + wts: []f32 = &.{}, + cls: []u16 = &.{}, + pos: []u16 = &.{}, + dev: [6]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Embed) c.Spec { + const name = if (self.late) "inkling2 experts control: tf_ink2v_embed reading each weight one tap late" else "inkling2 experts vision tf_ink2v_embed (class row, patches plus resampled positions)"; + return .{ .name = name, .accum = .f32, .depth = four, .out = .bf16, .served = &embed_served, .sums = .{ .f16 = 0, .bf16 = 0, .why = "four taps a value, rounded to bf16: no sum long enough to tell fp32 from half" } }; + } + + pub fn control(self: *const Embed) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *Embed, a: std.mem.Allocator) void { + inline for (.{ "pe", "table", "taps", "wts", "cls", "pos" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + pub fn prepare(self: *Embed, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows < 2 or shape.n != width or shape.k != 4) return false; + self.free(a); + self.shape = shape; + const p = shape.rows - 1; + const stress = fill == .stress; + self.pe = try ref.bfs(a, rng, p * width, -2, 2); + self.table = try ref.bfs(a, rng, grid * width, -1, 1); + self.cls = try ref.bfs(a, rng, width, -1, 1); + self.pos = try ref.bfs(a, rng, width, -1, 1); + self.taps = try a.alloc(u32, p * 4); + self.wts = try a.alloc(f32, p * 4); + for (0..p) |i| { + const x = rng.float(f32); + const y = rng.float(f32); + self.wts[4 * i ..][0..4].* = if (stress) .{ ref.int(rng, 0, 3), ref.int(rng, 0, 3), ref.int(rng, 0, 3), ref.int(rng, 0, 3) } else .{ (1 - x) * (1 - y), x * (1 - y), (1 - x) * y, x * y }; + for (self.taps[4 * i ..][0..4]) |*t| t.* = rng.uintLessThan(u32, grid); + } + if (stress) for ([_][]u16{ self.pe, self.table, self.cls, self.pos }) |v| { + for (v) |*e| e.* = c.toBf16(ref.int(rng, -8, 8)); + }; + if (fill == .nonfinite) { + self.pe[3] = c.toBf16(ref.nan); // patch 0 + self.table[self.taps[4] * width + 5] = c.toBf16(ref.inf); // every patch that taps patch 1's first row + self.cls[7] = c.toBf16(-ref.inf); + if (p > 2) self.pe[2 * width + 9] = c.toBf16(-ref.inf); + } + self.dev = .{ try ref.input(rig, self.pe), try ref.input(rig, self.table), try ref.input(rig, self.taps), try ref.input(rig, self.wts), try ref.input(rig, self.cls), try ref.input(rig, self.pos) }; + self.out = try rig.output(shape.rows * width * 2); + return true; + } + + pub fn run(self: *Embed, rig: *rig_.Rig) !void { + const d = self.dev; + try launch(self.kern.embed, rig.s, self.shape.rows, &.{ d[0], d[1], d[2], d[3] + @as(u64, if (self.late) 4 else 0), d[4], d[5], self.out }, null); + } + + pub fn count(self: *const Embed) usize { + return self.shape.rows * width; + } + + pub fn solve(self: *const Embed, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var terms: [4]Iv = undefined; + var scratch: [4]f64 = undefined; + for (0..width) |e| out[e] = Iv.of(ref.bf(self.cls[e])).add(Iv.of(ref.bf(self.pos[e]))).bf(); + for (1..self.shape.rows) |r| for (0..width) |e| { + const p = r - 1; + for (&terms, 0..) |*t, i| t.* = Iv.of(ref.bf(self.table[self.taps[4 * p + i] * width + e])).mul(Iv.of(self.wts[4 * p + i])); + const pos = s.sum(&terms, 4, &scratch).bf(); + out[r * width + e] = Iv.of(ref.bf(self.pe[p * width + e])).add(pos).bf(); + }; + } +}; + +/// q and k heads of qkv [R, 3 x 1024] turned in place, pair (2j, 2j + 1) of each head by fp32 cos and sin of row r. +pub const Rope = struct { + kern: *const Kernels, + swapped: bool = false, // control: cos and sin swapped + shape: c.Shape = undefined, + qkv: []u16 = &.{}, + cs: []f32 = &.{}, + sn: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Rope) c.Spec { + const name = if (self.swapped) "inkling2 experts control: tf_ink2v_rope with cos and sin swapped" else "inkling2 experts vision tf_ink2v_rope (2D rotary of q and k, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &rope_served }; + } + + pub fn control(self: *const Rope) ?g.Gate { + return if (self.swapped) .shapes else null; + } + + pub fn free(self: *Rope, a: std.mem.Allocator) void { + a.free(self.qkv); + a.free(self.cs); + a.free(self.sn); + self.qkv = &.{}; + self.cs = &.{}; + self.sn = &.{}; + } + + pub fn prepare(self: *Rope, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != qkv_width) return false; + self.free(a); + self.shape = shape; + const r = shape.rows; + self.qkv = try ref.bfs(a, rng, r * qkv_width, -3, 3); + self.cs = try a.alloc(f32, r * pairs); + self.sn = try a.alloc(f32, r * pairs); + for (self.cs, self.sn) |*x, *y| { + const angle = rng.float(f32) * 64; + x.* = @cos(angle); + y.* = @sin(angle); + } + if (fill == .nonfinite) { + self.qkv[3] = c.toBf16(ref.nan); // row 0, q head 0, pair 1's second value + self.qkv[qkv_width + width + 64 + 10] = c.toBf16(ref.inf); // row 1, k head 1 + self.qkv[2 * qkv_width + 2 * width + 5] = c.toBf16(-ref.inf); // row 2, v: as it is + if (r > 3) self.qkv[3 * qkv_width + 63] = c.toBf16(-ref.inf); + } + self.dev = .{ try ref.input(rig, self.cs), try ref.input(rig, self.sn) }; + self.out = try rig.output(self.qkv.len * 2); + return true; + } + + pub fn run(self: *Rope, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.qkv)); // in place: every run from the same rows + const cs = if (self.swapped) self.dev[1] else self.dev[0]; + const sn = if (self.swapped) self.dev[0] else self.dev[1]; + try launch(self.kern.rope, rig.s, self.shape.rows, &.{ self.out, cs, sn }, null); + } + + pub fn count(self: *const Rope) usize { + return self.qkv.len; + } + + pub fn solve(self: *const Rope, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.qkv, 0..) |*o, x, at| { + const col = at % qkv_width; + if (col >= 2 * width) { + o.* = Iv.of(ref.bf(x)); + continue; + } + const d = col % 64; + const first = at - d % 2; + const r = at / qkv_width; + const cv = Iv.of(self.cs[r * pairs + d / 2]); + const sv = Iv.of(self.sn[r * pairs + d / 2]); + const av = Iv.of(ref.bf(self.qkv[first])); + const bv = Iv.of(ref.bf(self.qkv[first + 1])); + o.* = (if (d % 2 == 0) av.mul(cv).add(bv.neg().mul(sv)) else bv.mul(cv).add(av.mul(sv))).bf(); + } + } +}; + +/// x = bf16(x + bf16(gamma[i % 1024] y)) over [R, 1024] in place: torch's `residual + lambda * h` in bf16. +pub const ScaleAdd = struct { + kern: *const Kernels, + late: bool = false, // control: gamma read one column late + shape: c.Shape = undefined, + x: []u16 = &.{}, + y: []u16 = &.{}, + gamma: []u16 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const ScaleAdd) c.Spec { + const name = if (self.late) "inkling2 experts control: tf_ink2v_scale_add reading gamma one column late" else "inkling2 experts vision tf_ink2v_scale_add (layer-scaled residual add, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &add_served }; + } + + pub fn control(self: *const ScaleAdd) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *ScaleAdd, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.y); + a.free(self.gamma); + self.x = &.{}; + self.y = &.{}; + self.gamma = &.{}; + } + + pub fn prepare(self: *ScaleAdd, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != width) return false; + self.free(a); + self.shape = shape; + const n = shape.rows * width; + self.x = try ref.bfs(a, rng, n, -4, 4); + self.y = try ref.bfs(a, rng, n, -4, 4); + self.gamma = try ref.bfs(a, rng, width, -0.5, 0.5); + if (fill == .nonfinite) { + self.x[0] = c.toBf16(ref.nan); + self.y[1] = c.toBf16(ref.inf); + self.gamma[2] = c.toBf16(-ref.inf); // column 2 of every row + self.x[width + 3] = c.toBf16(ref.inf); + } + self.dev = .{ try ref.input(rig, self.y), try ref.input(rig, self.gamma) }; + self.out = try rig.output(n * 2); + return true; + } + + pub fn run(self: *ScaleAdd, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.x)); + const n = self.count(); + try launch(self.kern.scale_add, rig.s, (n + 255) / 256, &.{ self.out, self.dev[0], self.dev[1] + @as(u64, if (self.late) 2 else 0) }, @intCast(n)); + } + + pub fn count(self: *const ScaleAdd) usize { + return self.shape.rows * width; + } + + pub fn solve(self: *const ScaleAdd, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.x, self.y, 0..) |*o, x, y, i| { + const scaled = Iv.of(ref.bf(self.gamma[i % width])).mul(Iv.of(ref.bf(y))).bf(); + o.* = Iv.of(ref.bf(x)).add(scaled).bf(); + } + } +}; diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig new file mode 100644 index 00000000000..524accd67b3 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -0,0 +1,463 @@ +//! Mini's packed NVFP4/MXFP8 expert pipeline on BF16 activations, against a sampled full-width host reference. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const mo = ink.modelopt; +const experts = 8; +const slots = 8; + +const CombineArgs = extern struct { + experts: u64, + pick: u64, + weights: u64, + out: u64, + rows: i32, + h: i32, + slots: i32, +}; + +const TensorActArgs = extern struct { + gateup: u64, + out: u64, + n: i32, +}; + +const Baseline = struct { + mod: cuda.Module, + tensor_mod: cuda.Module, + pack: cuda.Function, + project: cuda.Function, + act: cuda.Function, + combine: cuda.Function, +}; + +fn bf(x: f32) f32 { + return c.fromBf16(c.toBf16(x)); +} + +fn e2m1(n: u8) f32 { + const table = [8]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = table[n & 7]; + return if ((n & 8) != 0) -v else v; +} + +fn e4m3(n: u8) f32 { + const e = (n >> 3) & 15; + const m: f32 = @floatFromInt(n & 7); + var v: f32 = undefined; + if (e == 0) { + v = m * 0x1p-9; + } else if (e == 15 and n & 7 == 7) { + v = std.math.nan(f32); + } else { + v = std.math.pow(f32, 2, @as(f32, @floatFromInt(e)) - 7) * (1 + m / 8); + } + return if ((n & 128) != 0) -v else v; +} + +fn route(slot: usize) u32 { + const ids = [8]u32{ 7, 7, 2, 5, 0, 6, 3, 4 }; + return ids[slot]; +} + +fn routeWeight(token: usize, slot: usize) f32 { + _ = token; + // Route order loses the unit between opposite large terms; expert order keeps it. + return switch (slot) { + 0 => 0x1p24, + 1 => 1, + 2 => -0x1p24, + else => 0, + }; +} + +const test_amax: f32 = 1.0039; // bf16: 1 +const test_den: f32 = 2696.001; // bf16: 2704 + +fn nvfp4Weight(code: u8, scale: u8) u16 { + const factor = bf(test_amax) / bf(test_den); + return c.toBf16(e2m1(code) * e4m3(scale) * factor); +} + +fn ue8m0(n: u8) f32 { + return std.math.pow(f32, 2, @as(f32, @floatFromInt(@as(i32, n) - 127))); +} + +fn mxfp8Weight(code: u8, scale: u8) u16 { + return c.toBf16(e4m3(code) * ue8m0(scale)); +} + +const Fault = enum { none, wrong_combine, wrong_plan, wrong_up, wrong_act }; + +fn rawSpec(format: mo.Format, fault: Fault) c.Spec { + const served = &[_]c.Shape{ + .{ .rows = 1, .n = 2304, .k = 1152 }, + .{ .rows = 16, .n = 2304, .k = 1152 }, + .{ .rows = 31, .n = 2304, .k = 1152 }, + .{ .rows = 32, .n = 2304, .k = 1152 }, + .{ .rows = 2048, .n = 2304, .k = 1152 }, + }; + const name = switch (fault) { + .none => if (format == .nvfp4) "inkling2 Mini NVFP4 w13/w2 tensor-core experts" else "inkling2 Mini MXFP8 w13/w2 tensor-core experts", + .wrong_combine => if (format == .nvfp4) "control: inkling2 Mini NVFP4 int32 route IDs reinterpreted as FP32 weights" else "control: inkling2 Mini MXFP8 int32 route IDs reinterpreted as FP32 weights", + .wrong_plan => "control: inkling2 Mini MXFP8 plan routes to the next expert IDs", + .wrong_up => "control: inkling2 Mini MXFP8 up projection clears the planted up-row code", + .wrong_act => "control: inkling2 Mini MXFP8 activation uses gate cap eight", + }; + return .{ + .name = name, + .accum = .none, + .depth = noSums, + .out = .raw, + .replaces = "host-dequantized BF16 tensor projections, softcapped SwiGLU, ascending FP32 routing", + .nan = .{ .stated = "a non-finite BF16 input row propagates through its selected experts" }, + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{ .size = 32 } }, + .served = if (fault == .none) served else served[0..2], + }; +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +pub const ModelOpt = struct { + rig: rig_.Rig, + k: *const mo.Kernels, + format: mo.Format, + shape: c.Shape = undefined, + fault: Fault = .none, + arena: ?std.heap.ArenaAllocator = null, + x: []const u16 = &.{}, + w13: []const u16 = &.{}, + w2: []const u16 = &.{}, + l: mo.Layer = undefined, + dev_x: u64 = 0, + pick: u64 = 0, + weights: u64 = 0, + out: u64 = 0, + scratch: u64 = 0, + base_pick: u64 = 0, + base_w13: u64 = 0, + base_w2: u64 = 0, + base_pack13: u64 = 0, + base_pack2: u64 = 0, + base_gateup: u64 = 0, + base_act: u64 = 0, + base_down: u64 = 0, + base_out: u64 = 0, + baseline: ?Baseline = null, + msg: [200]u8 = undefined, + + pub fn kernel(self: *ModelOpt) g.Kernel { + return .{ .spec = rawSpec(self.format, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(ModelOpt); + + pub fn deinit(self: *ModelOpt) void { + self.drop(); + if (self.baseline) |*b| { + b.tensor_mod.unload(); + b.mod.unload(); + } + self.baseline = null; + self.rig.deinit(); + } + + fn drop(self: *ModelOpt) void { + if (self.arena) |*a| a.deinit(); + self.arena = null; + self.rig.reset(); + } + + fn projectionRef(a: std.mem.Allocator, format: mo.Format, nexperts: usize, n: usize, k: usize, gate_up: bool) !struct { codes: []u8, scales: []u8, amax: []f32, den: [1]f32, ref: []u16 } { + const values = nexperts * n * k; + const raw = try a.alloc(u8, if (format == .nvfp4) values / 2 else values); + const ref = try a.alloc(u16, values); + const group: usize = if (format == .nvfp4) 16 else 32; + const scales = try a.alloc(u8, values / group); + const amax = try a.alloc(f32, if (format == .nvfp4) nexperts else 0); + if (format == .nvfp4) @memset(amax, test_amax); + const codes = [16]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + const fp8 = [16]u8{ 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8 }; + const nv_scales = [4]u8{ 0x38, 0x30, 0x40, 0x34 }; + // General controls stay finite; the dedicated scale-255 test covers +inf without masking faults as shared NaNs. + const mx_scales = [4]u8{ 127, 128, 126, 129 }; + for (0..nexperts) |e| for (0..n) |row| { + const base = (e * n + row) * k; + const scale_base = (e * n + row) * (k / group); + if (format == .nvfp4) { + for (0..k / 2) |cb| { + var n0 = codes[(2 * (base / 2 + cb) * 5 + 3) & 15]; + const n1 = if (cb == 0) 0 else codes[(2 * (base / 2 + cb) * 5 + 7) & 15]; + if (cb == 0) n0 = if (!gate_up or row < 2) (if (gate_up) 2 else 7) else 0; + raw[base / 2 + cb] = n0 | (n1 << 4); + const gi = cb / 8; + scales[scale_base + gi] = if (gi == 0) 0x38 else nv_scales[(scale_base + gi) & 3]; + const scale = scales[scale_base + gi]; + ref[base + 2 * cb] = nvfp4Weight(n0, scale); + ref[base + 2 * cb + 1] = nvfp4Weight(n1, scale); + } + } else { + for (0..k) |col| { + var code = fp8[((base + col) * 5 + 3) & 15]; + // Gate six makes caps four and eight differ deterministically on the one-token control. + if (col == 0) code = if (!gate_up) 0x40 else if (row == 0) 0x4c else if (row == 1) 0x38 else 0; + raw[base + col] = code; + const gi = col / 32; + scales[scale_base + gi] = if (gi == 0) 127 else mx_scales[(scale_base + gi) % mx_scales.len]; + ref[base + col] = mxfp8Weight(code, scales[scale_base + gi]); + } + } + }; + return .{ .codes = raw, .scales = scales, .amax = amax, .den = .{test_den}, .ref = ref }; + } + + pub fn prepare(self: *ModelOpt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + _ = seed; + if (shape.n != 2304 or shape.k != 1152 or shape.rows == 0 or shape.rows > 2048) return false; + self.drop(); + self.shape = shape; + self.arena = std.heap.ArenaAllocator.init(self.rig.gpu.gpa); + const a = self.arena.?.allocator(); + const h = shape.n; + const m = shape.k; + const pairs = shape.rows * slots; + const x = try a.alloc(u16, shape.rows * h); + for (x, 0..) |*v, i| { + const q: f32 = @as(f32, @floatFromInt(@as(i32, @intCast(i % 17)) - 8)) / 64; + v.* = c.toBf16(q); + } + @memset(x[0..h], 0); + x[0] = c.toBf16(1); // One gate/up activation and one down product make token zero a decode probe. + if (fill == .nonfinite) x[0] = 0x7fc0; + self.x = x; + const p13 = try projectionRef(a, self.format, experts, 2 * m, h, true); + const p2 = try projectionRef(a, self.format, experts, h, m, false); + self.w13 = p13.ref; + self.w2 = p2.ref; + self.dev_x = try self.rig.input(std.mem.sliceAsBytes(x)); + const dev13 = if (self.fault == .wrong_up) blk: { + const wrong = try a.dupe(u8, p13.codes); + for (0..experts) |e| { + const code_stride: usize = if (self.format == .nvfp4) 2 else 1; + const z = (e * 2 * m + 1) * h / code_stride; + if (self.format == .nvfp4) wrong[z] &= 0xf0 else wrong[z] = 0; + } + break :blk try self.rig.input(wrong); + } else try self.rig.input(p13.codes); + const dev13s = try self.rig.input(p13.scales); + const dev2 = try self.rig.input(p2.codes); + const dev2s = try self.rig.input(p2.scales); + var amax13: u64 = 0; + var amax2: u64 = 0; + var den13: u64 = 0; + var den2: u64 = 0; + if (self.format == .nvfp4) { + amax13 = try self.rig.input(std.mem.sliceAsBytes(p13.amax)); + amax2 = try self.rig.input(std.mem.sliceAsBytes(p2.amax)); + den13 = try self.rig.input(std.mem.asBytes(&p13.den)); + den2 = try self.rig.input(std.mem.asBytes(&p2.den)); + } + self.l = .{ + .format = self.format, + .experts = experts, + .w13 = .{ .codes = dev13, .scales = dev13s, .amax = amax13, .denominator = den13, .n = @intCast(2 * m), .k = @intCast(h) }, + .w2 = .{ .codes = dev2, .scales = dev2s, .amax = amax2, .denominator = den2, .n = @intCast(h), .k = @intCast(m) }, + }; + const picks = try a.alloc(i32, pairs); + const weights = try a.alloc(f32, pairs); + for (picks, weights, 0..) |*p, *w, i| { + const slot = i % slots; + const id = if (self.fault == .wrong_plan) (route(slot) + 1) % experts else route(slot); + p.* = @intCast(id); + w.* = routeWeight(i / slots, slot); + } + const base_picks = try a.alloc(i32, pairs); + for (base_picks, 0..) |*p, i| p.* = @intCast(route(i % slots)); + self.pick = try self.rig.input(std.mem.sliceAsBytes(picks)); + self.weights = try self.rig.input(std.mem.sliceAsBytes(weights)); + self.out = try self.rig.output(shape.rows * h * 2); + self.scratch = try self.rig.scratch(try mo.scratchBytes(shape.rows, slots, h, m)); + self.base_pick = try self.rig.input(std.mem.sliceAsBytes(base_picks)); + self.base_w13 = try self.rig.input(std.mem.sliceAsBytes(p13.ref)); + self.base_w2 = try self.rig.input(std.mem.sliceAsBytes(p2.ref)); + self.base_pack13 = try self.rig.scratch(experts * 2 * m * h * 2); + self.base_pack2 = try self.rig.scratch(experts * h * m * 2); + self.base_gateup = try self.rig.scratch(pairs * 2 * m * 2); + self.base_act = try self.rig.scratch(pairs * m * 2); + self.base_down = try self.rig.scratch(pairs * h * 2); + self.base_out = try self.rig.scratch(shape.rows * h * 2); + return true; + } + + pub fn run(self: *ModelOpt) !void { + const route_weights = if (self.fault == .wrong_combine) self.pick else self.weights; + const caps = if (self.fault == .wrong_act) ink.experts.Caps{ .gate = 8, .up = 25 } else ink.experts.Caps{ .gate = 4, .up = 25 }; + try mo.run(self.k, self.rig.s, self.l, caps, self.dev_x, self.shape.n, self.pick, route_weights, self.shape.rows, slots, self.out, self.scratch); + } + + fn pack(self: *ModelOpt, b: *const Baseline, src: u64, n: usize, k: usize, dst: u64) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(@as(i64, @intCast(n * k))); + a.add(@as(i32, @intCast(k))); + for ([_]i32{ 0, 0, 0 }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(@as(i32, @intCast(k))); + a.add(dst); + const q = (n / 32) * (k / 32) * 128; + try cuda.launch.launch(b.pack, .{ .grid = .{ .x = @intCast((q + 255) / 256), .y = experts, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + } + + fn tensorProjection(self: *ModelOpt, b: *const Baseline, x: u64, x_stride: usize, slot_count: usize, w: u64, n: usize, k: usize, plan: mo.Layout, out: u64, item_bound: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i32, @intCast(x_stride))); + a.add(@as(i32, @intCast(slot_count))); + a.add(w); + a.add(@as(i32, @intCast(k / 32))); + a.add(@as(i32, @intCast(n / 32))); + for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(@as(i32, -1)); + const nb = n / 32; + const grid = (item_bound * nb + 3) / 4; + try cuda.launch.launch(b.project, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + /// Tensor projections over host-dequantized weights, the baseline epilogue and the original ascending combine. + pub fn replaced(self: *ModelOpt) ![]const u8 { + if (self.baseline == null) { + var mod = try cuda.Module.load(self.rig.gpu.d, cuda.kernels.inkling2_experts); + errdefer mod.unload(); + var tensor_mod = try cuda.Module.load(self.rig.gpu.d, cuda.kernels.experts_bf16); + errdefer tensor_mod.unload(); + self.baseline = .{ + .mod = mod, + .tensor_mod = tensor_mod, + .pack = try tensor_mod.function("tf_bf16_experts_pack"), + .project = try tensor_mod.function("tf_bf16_experts_down_bf16"), + .act = try mod.function("tf_ink2moe_tensor_act"), + .combine = try mod.function("tf_ink2moe_combine"), + }; + } + const b = &self.baseline.?; + const pairs = self.shape.rows * slots; + const h = self.shape.n; + const m = self.shape.k; + const plan = mo.layout(self.scratch, self.shape.rows, slots, h, m); + const tile: usize = if (self.shape.rows < 32) 16 else 64; + const item_bound = (pairs + tile - 1) / tile + @min(pairs, experts); + var pa: cuda.Args = .{}; + for ([_]u64{ self.base_pick, plan.items, plan.members, plan.item_count }) |v| pa.add(v); + for ([_]i32{ @intCast(self.shape.rows), slots, experts, @intCast(tile) }) |v| pa.add(v); + try cuda.launch.launch(self.k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, self.rig.s, &pa); + try self.pack(b, self.base_w13, 2 * m, h, self.base_pack13); + try self.pack(b, self.base_w2, h, m, self.base_pack2); + try self.tensorProjection(b, self.dev_x, h, slots, self.base_pack13, 2 * m, h, plan, self.base_gateup, item_bound); + var aa: cuda.Args = .{}; + aa.add(TensorActArgs{ .gateup = self.base_gateup, .out = self.base_act, .n = @intCast(pairs * m) }); + try cuda.launch.launch(b.act, .{ .grid = .{ .x = @intCast((pairs * m + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &aa); + try self.tensorProjection(b, self.base_act, m, 0, self.base_pack2, h, m, plan, self.base_down, item_bound); + var ca: cuda.Args = .{}; + ca.add(CombineArgs{ .experts = self.base_down, .pick = self.base_pick, .weights = self.weights, .out = self.base_out, .rows = @intCast(self.shape.rows), .h = @intCast(h), .slots = slots }); + const outputs = self.shape.rows * h; + try cuda.launch.launch(b.combine, .{ .grid = .{ .x = @intCast((outputs + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); + return self.rig.bytes(self.base_out, self.count()); + } + + fn dot(x: []const u16, w: []const u16) f32 { + var sum: f32 = 0; + for (x, w) |xv, wv| sum += c.fromBf16(xv) * c.fromBf16(wv); + return sum; + } + + fn one(self: *const ModelOpt, a: std.mem.Allocator, token: usize, col: usize) !f32 { + const h = self.shape.n; + const m = self.shape.k; + const x = self.x[token * h ..][0..h]; + const act = try a.alloc(u16, m); + defer a.free(act); + var total: f32 = 0; + for (0..experts) |e| { + for (0..slots) |slot| { + if (route(slot) != e) continue; + for (0..m) |j| { + const x13 = self.w13[e * 2 * m * h ..]; + const gate = bf(dot(x, x13[(2 * j) * h ..][0..h])); + const up = bf(dot(x, x13[(2 * j + 1) * h ..][0..h])); + const gc = 4 * @as(f32, @floatCast(std.math.tanh(gate / 4))); + const uc = 25 * @as(f32, @floatCast(std.math.tanh(up / 25))); + const sigmoid: f32 = 1 / (1 + @exp(-gate)); + act[j] = c.toBf16(gc * sigmoid * uc); + } + const x2 = self.w2[e * h * m + col * m ..][0..m]; + total += routeWeight(token, slot) * bf(dot(act, x2)); + } + } + return bf(total); + } + + pub fn check(self: *ModelOpt, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const samples = [2][2]usize{ .{ 0, 0 }, .{ self.shape.rows - 1, self.shape.n - 1 } }; + for (samples) |at| { + const got_bytes = try self.rig.bytes(self.out + 2 * (at[0] * self.shape.n + at[1]), 2); + const got = c.fromBf16(std.mem.readInt(u16, got_bytes[0..2], .little)); + const want = try self.one(a, at[0], at[1]); + if (got == want or (std.math.isNan(want) and std.math.isNan(got))) continue; + // The token-zero one-product probe separates A2's roughly 1.4% error from reduction noise. + const tolerance = if (at[0] == 0) @abs(want) * 0.001 else @max(@as(f32, 0.02), @abs(want) * 0.02); + if (!std.math.isFinite(got) or @abs(got - want) > tolerance) { + return try std.fmt.bufPrint(&self.msg, "row {d} col {d}: got {d}, full-width host reference {d} (allowance {d})", .{ at[0], at[1], got, want, tolerance }); + } + } + return null; + } + + pub fn count(self: *const ModelOpt) usize { + return self.shape.rows * self.shape.n * 2; + } + + pub fn reference(_: *ModelOpt, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +test "A2: amax and denominator are BF16 before the FP32 quotient" { + // code=6, scale=1: rounded sources give 0x3b11; f32 sources give 0x3b12. + try std.testing.expectEqual(@as(u16, 0x3b11), nvfp4Weight(7, 0x38)); + const factor = bf(test_amax) / bf(test_den); + try std.testing.expectEqual(@as(f32, 1) / 2704, factor); + const unrounded = c.toBf16(e2m1(7) * e4m3(0x38) * (test_amax / test_den)); + try std.testing.expectEqual(@as(u16, 0x3b12), unrounded); +} + +test "MXFP8 UE8M0 scale 255 decodes to positive infinity" { + try std.testing.expectEqual(std.math.inf(f32), ue8m0(255)); + try std.testing.expectEqual(@as(u16, 0x7f80), mxfp8Weight(0x38, 255)); +} + +test "A12: ascending experts retain the unit cancelled in route order" { + var route_sum: f32 = 0; + for (0..slots) |slot| route_sum += routeWeight(0, slot); + try std.testing.expectEqual(@as(f32, 0), route_sum); + var expert_sum: f32 = 0; + for (0..experts) |e| for (0..slots) |slot| { + if (route(slot) == e) expert_sum += routeWeight(0, slot); + }; + try std.testing.expectEqual(@as(f32, 1), expert_sum); +} + +test "the independent baseline's CUDA structs match experts.cu" { + try std.testing.expectEqual(@as(usize, 48), @sizeOf(CombineArgs)); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(TensorActArgs)); + try std.testing.expectEqual(@as(usize, 16), @offsetOf(TensorActArgs, "n")); +} diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index 22fc073bf40..8c86f2e6ed8 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -10,7 +10,8 @@ const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const C = ref.hidden; +const small_hidden = ref.hidden; +const mini_hidden = 2304; /// forward.zig's mixes: attention's (q, k and v queries, bf16 stream), the MLP's (fp32 residual), layer 0's (no query). pub const Form = enum { attn, mlp, first }; @@ -23,16 +24,16 @@ fn nq(f: Form) usize { } /// A thread's columns 512 apart, then the block's two shuffle stages. -fn depth(_: c.Shape) usize { - return ref.blockDepth(C, 512); +fn depth(s: c.Shape) usize { + return ref.blockDepth(s.n, 512); } /// Rows x hidden x blocks (completed blocks + the partial): mix_rows takes calls of more than 16 rows, mix the rest. pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { - const wide = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 9 }, .{ .rows = 64, .n = C, .k = 5 }, .{ .rows = 2048, .n = C, .k = 9 }, .{ .rows = 128, .n = C, .k = 1 }, .{ .rows = 32, .n = C, .k = 2 } }; - const decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 9 }, .{ .rows = 16, .n = C, .k = 9 }, .{ .rows = 8, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 1 }, .{ .rows = 4, .n = C, .k = 2 } }; - const one = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 1 }, .{ .rows = 2048, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 1 } }; - const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 5, .n = C, .k = 1 } }; + const wide = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 9 }, .{ .rows = 64, .n = small_hidden, .k = 5 }, .{ .rows = 2048, .n = small_hidden, .k = 9 }, .{ .rows = 128, .n = small_hidden, .k = 1 }, .{ .rows = 32, .n = small_hidden, .k = 2 }, .{ .rows = 17, .n = mini_hidden, .k = 5 }, .{ .rows = 64, .n = mini_hidden, .k = 3 }, .{ .rows = 2048, .n = mini_hidden, .k = 5 }, .{ .rows = 128, .n = mini_hidden, .k = 1 }, .{ .rows = 32, .n = mini_hidden, .k = 2 } }; + const decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 9 }, .{ .rows = 16, .n = small_hidden, .k = 9 }, .{ .rows = 8, .n = small_hidden, .k = 5 }, .{ .rows = 2, .n = small_hidden, .k = 1 }, .{ .rows = 4, .n = small_hidden, .k = 2 }, .{ .rows = 1, .n = mini_hidden, .k = 5 }, .{ .rows = 16, .n = mini_hidden, .k = 5 }, .{ .rows = 8, .n = mini_hidden, .k = 3 }, .{ .rows = 2, .n = mini_hidden, .k = 1 }, .{ .rows = 4, .n = mini_hidden, .k = 2 } }; + const one = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 1 }, .{ .rows = 2048, .n = small_hidden, .k = 1 }, .{ .rows = 64, .n = small_hidden, .k = 1 }, .{ .rows = 17, .n = mini_hidden, .k = 1 }, .{ .rows = 2048, .n = mini_hidden, .k = 1 }, .{ .rows = 64, .n = mini_hidden, .k = 1 } }; + const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 1 }, .{ .rows = 16, .n = small_hidden, .k = 1 }, .{ .rows = 5, .n = small_hidden, .k = 1 }, .{ .rows = 1, .n = mini_hidden, .k = 1 }, .{ .rows = 16, .n = mini_hidden, .k = 1 }, .{ .rows = 5, .n = mini_hidden, .k = 1 } }; const names = [2][3][]const u8{ .{ "inkling2 ops tf_ink2_mix_rows attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix_rows MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix_rows layer 0 (no query)" }, .{ "inkling2 ops tf_ink2_mix attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix layer 0 (no query)" }, @@ -93,10 +94,11 @@ pub const Mix = struct { /// Values in [-2, 2) with one in 61 eight times larger, queries in [-1, 1); stress: integers in [-16, 16]. pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != C or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; + if (shape.rows == 0 or (shape.n != small_hidden and shape.n != mini_hidden) or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; self.free(a); self.shape = shape; - const rows = shape.rows; + const C = self.shape.n; + const rows = self.shape.rows; const nb = shape.k - 1; const q = nq(self.form); const stress = fill == .stress; @@ -116,7 +118,7 @@ pub const Mix = struct { if (nb == 0) ref.plant(f32, self.part, 1, C, ref.asF32); if (rows > 1) ref.plant(f32, self.part[C..], @min(rows - 1, 3), C, ref.asF32); } - var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = C, .eps = ref.eps }; + var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = @intCast(C), .eps = ref.eps }; for (0..nb) |j| m.blocks[j] = try ref.input(rig, self.blocks[j * rows * C ..][0 .. rows * C]); if (self.bf16Part()) { const h = try a.alloc(u16, rows * C); @@ -153,16 +155,19 @@ pub const Mix = struct { } pub fn count(self: *const Mix) usize { + const C = self.shape.n; return nq(self.form) * self.shape.rows * C; } fn at(self: *const Mix, j: usize, r: usize, col: usize) f64 { + const C = self.shape.n; const nb = self.shape.k - 1; return if (j < nb) ref.bf(self.blocks[(j * self.shape.rows + r) * C + col]) else self.part[r * C + col]; } /// Each row as the kernels compute it: every block's RMS and query dots, a softmax a query, the mix, its norm. pub fn solve(self: *const Mix, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const C = self.shape.n; const rows = self.shape.rows; const n = self.shape.k; const q = nq(self.form); @@ -173,7 +178,7 @@ pub const Mix = struct { const h = try a.alloc(Iv, q * C); defer a.free(h); const d = depth(self.shape); - const root = Iv.of(C).rsqrt(); + const root = Iv.of(@as(f64, @floatFromInt(C))).rsqrt(); for (0..rows) |r| { var rr: [ops.max_blocks + 1]Iv = undefined; var w: [ops.max_queries][ops.max_blocks + 1]Iv = undefined; diff --git a/zig/tests/cuda/contract_inkling2_ops_route.zig b/zig/tests/cuda/contract_inkling2_ops_route.zig index c17be9c5860..8e04891dab9 100644 --- a/zig/tests/cuda/contract_inkling2_ops_route.zig +++ b/zig/tests/cuda/contract_inkling2_ops_route.zig @@ -21,7 +21,7 @@ const topk_rule = "the 8 largest score + bias, the lower id on ties, a NaN never /// Rows x experts x picks: every row of a call, a block each. pub fn topkSpec(unbiased: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top } }; + const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top }, .{ .rows = 16, .n = 128, .k = top }, .{ .rows = 1, .n = 128, .k = top }, .{ .rows = 128, .n = 128, .k = top }, .{ .rows = 2048, .n = 128, .k = top } }; const name = if (unbiased) "control: inkling2 ops tf_ink2_topk without the selection bias" else "inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)"; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = topk_rule }, .served = if (unbiased) served[0..2] else served }; } @@ -122,7 +122,7 @@ pub const Topk = struct { const had: f64 = @as(f32, 0.08838834764831845); // exl3_decode.cuh's HAD_SCALE, as fp32 holds it const gate_cap: f32 = 4; const up_cap: f32 = 25; -const width = 1152; // a rank's 2,304-wide expert intermediate at TP=2 +const width = 1152; // Small's width at TP=2; Mini runs one rank with the same full width. const fixture_experts = 8; /// fwht128 and tf_exl3_fwht alike: butterflies (lo + hi, lo - hi) at strides 1, 2, ..., 64 of the 128 values. @@ -142,7 +142,7 @@ fn gateDepth(s: c.Shape) usize { /// (row, slot) pairs x a rank's width x the gate/up's K splits: 1 row, 16, a 128-row window, a 2,048-row window. pub fn gateupSpec(swapped: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 8, .n = width, .k = 4 }, .{ .rows = 128, .n = width, .k = 4 }, .{ .rows = 1024, .n = width, .k = 4 }, .{ .rows = 16384, .n = width, .k = 4 } }; + const served = &[_]c.Shape{ .{ .rows = 8, .n = width, .k = 4 }, .{ .rows = 128, .n = width, .k = 4 }, .{ .rows = 1024, .n = width, .k = 4 }, .{ .rows = 16384, .n = width, .k = 4 }, .{ .rows = 8, .n = width, .k = 2 }, .{ .rows = 128, .n = width, .k = 2 }, .{ .rows = 1024, .n = width, .k = 2 }, .{ .rows = 16384, .n = width, .k = 2 } }; const name = if (swapped) "control: inkling2 ops tf_ink2_gateup with the caps swapped" else "inkling2 ops tf_ink2_gateup (softcapped SwiGLU, gate cap 4, up cap 25)"; return .{ .name = name, .accum = .f32, .depth = gateDepth, .out = .f16, .tiles = .{ .{}, .{ .size = 128, .step = 128, .min = 128 }, .{} }, .served = if (swapped) served[0..2] else served }; } diff --git a/zig/tests/cuda/contract_inkling2_ops_rows.zig b/zig/tests/cuda/contract_inkling2_ops_rows.zig index cb17ac6cbe0..953f54fb68a 100644 --- a/zig/tests/cuda/contract_inkling2_ops_rows.zig +++ b/zig/tests/cuda/contract_inkling2_ops_rows.zig @@ -21,7 +21,7 @@ fn embedDepth(s: c.Shape) usize { /// Rows x hidden x hidden: a prompt chunk, a verify window, one decode row (the drafter's anchor embeds one too). pub fn embedSpec(shifted: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C } }; + const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C }, .{ .rows = 16, .n = 2304, .k = 2304 }, .{ .rows = 1, .n = 2304, .k = 2304 }, .{ .rows = 128, .n = 2304, .k = 2304 }, .{ .rows = 2048, .n = 2304, .k = 2304 } }; if (shifted) return .{ .name = "control: inkling2 ops tf_ink2_embed gathering the next row", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; return .{ .name = "inkling2 ops tf_ink2_embed (embed_norm, rounded once)", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; } @@ -114,14 +114,14 @@ fn dotDepth(s: c.Shape) usize { /// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. pub fn dotSpec(d: Dot, tiles: bool, short: bool) c.Spec { const plain: []const c.Shape = switch (d) { // comptime arrays: a spec outlives this call - .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C } }, - .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C } }, - .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C } }, + .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C }, .{ .rows = 16, .n = 128, .k = 2304 }, .{ .rows = 1, .n = 128, .k = 2304 }, .{ .rows = 31, .n = 128, .k = 2304 }, .{ .rows = 7, .n = 128, .k = 2304 } }, + .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C }, .{ .rows = 16, .n = 24, .k = 2304 }, .{ .rows = 1, .n = 24, .k = 2304 }, .{ .rows = 128, .n = 24, .k = 2304 }, .{ .rows = 2048, .n = 24, .k = 2304 } }, + .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C }, .{ .rows = 16, .n = 16, .k = 2304 }, .{ .rows = 1, .n = 16, .k = 2304 }, .{ .rows = 31, .n = 16, .k = 2304 } }, }; const wide: []const c.Shape = if (d == .router) - &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C } } + &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C }, .{ .rows = 64, .n = 128, .k = 2304 }, .{ .rows = 32, .n = 128, .k = 2304 }, .{ .rows = 100, .n = 128, .k = 2304 }, .{ .rows = 2048, .n = 128, .k = 2304 } } else - &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C } }; + &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C }, .{ .rows = 64, .n = 16, .k = 2304 }, .{ .rows = 32, .n = 16, .k = 2304 }, .{ .rows = 100, .n = 16, .k = 2304 }, .{ .rows = 2048, .n = 16, .k = 2304 } }; const names = [3][2][]const u8{ .{ "inkling2 ops tf_ink2_rowdot router (fp32 sigmoid scores)", "inkling2 ops tf_ink2_rowdot_tiles router (fp32 sigmoid scores)" }, .{ "inkling2 ops tf_ink2_rowdot attention sinks (bf16 sigmoid)", "" }, diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 9198c30174a..f8dac6388e4 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -32,7 +32,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; } diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 3b20c3dbacc..d3fad1a5c2d 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -145,6 +145,33 @@ fn arg(rest: []const [:0]const u8, i: usize) ![]const u8 { return rest[i]; } +fn compileInkling2Contracts() !void { + const shape: @import("core").contract.spec.Shape = .{ .rows = 1, .n = 2304, .k = 2 }; + const a: std.mem.Allocator = undefined; + const gpu: check.Gpu = undefined; + const stream: cuda.Stream = undefined; + var list: std.ArrayList(@import("core").contract.gates.Kernel) = .empty; + const set = try @import("contract_inkling2.zig").Set.init(gpu, stream, a, &list); + set.deinit(); + var rig: @import("contract_rig.zig").Rig = undefined; + const rng: std.Random = undefined; + var mix: @import("contract_inkling2_ops_mix.zig").Mix = undefined; + _ = try mix.prepare(a, &rig, shape, .random, rng); + try mix.run(&rig); + _ = try mix.replaced(&rig); + const sums: @import("contract_inkling2_ops_ref.zig").Sums = undefined; + const solved: []@import("contract_inkling2_ops_ref.zig").Iv = undefined; + try mix.solve(a, sums, solved); + var modelopt: @import("contract_inkling2_modelopt.zig").ModelOpt = undefined; + _ = try modelopt.prepare(shape, .random, 0); + try modelopt.run(); + _ = try modelopt.check(.shapes); + _ = modelopt.count(); + const want: []f64 = undefined; + const mag: []f64 = undefined; + try modelopt.reference(want, mag); +} + fn compileContractGlue() !void { // the contract glue's device path, built with the runner: prepare through the vtable const cores = std.Thread.getCpuCount() catch 1; if (cores != 0) return; @@ -152,6 +179,7 @@ fn compileContractGlue() !void { // the contract glue's device path, built with g.kind = .chain; const kernels = [_]@import("core").contract.gates.Kernel{g.kernel()}; for (kernels) |k| _ = try k.vt.prepare(k.ctx, .{ .rows = 0, .n = 0, .k = 0 }, .random, 0); + try compileInkling2Contracts(); } fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ac9b6b9dd82..e401808d50a 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 0303722961597dd1d155363059dbac5ba88ccf42094deed894a81e33706b10c9 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered +zig/src/cuda/kernels.zig 195d3693f3c72e8d2c011088cd34d7839bc0111dfe1a213a2a7c7b62ef8a4031 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt image registered; #1858: the idol_decoder image registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw From 7ce4e9cb4be561e4bde021feb3e8136e619df0e4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:38:47 +0000 Subject: [PATCH 12/84] inkling2: run Mini loop math on CUDA Launch cross-pass messages, rank-64 gates, residual steps and split QKV with FP32 reductions, BF16 rounding controls and per-launch resource records. --- zig/build/cuda_kernels.zig | 1 + zig/kernels/cuda/inkling2/loop_math.cu | 278 ++++++++++ .../contract/inkling2_experts_records.zig | 5 + zig/src/core/contract/registry_union.zig | 4 +- zig/src/cuda/kernels.zig | 1 + zig/src/families/inkling2/inkling2.zig | 2 + zig/src/families/inkling2/loop_math_cuda.zig | 158 ++++++ zig/tests/cuda/contract_inkling2.zig | 3 + .../cuda/contract_inkling2_loop_math.zig | 479 ++++++++++++++++++ .../contract_inkling2_loop_math_extra.zig | 408 +++++++++++++++ zig/tests/cuda/contract_limits.zig | 2 +- zig/tests/fixtures/gradient-serving.tsv | 2 +- 12 files changed, 1339 insertions(+), 4 deletions(-) create mode 100644 zig/kernels/cuda/inkling2/loop_math.cu create mode 100644 zig/src/families/inkling2/loop_math_cuda.zig create mode 100644 zig/tests/cuda/contract_inkling2_loop_math.zig create mode 100644 zig/tests/cuda/contract_inkling2_loop_math_extra.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index dd80b81d0d3..673cf887e67 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -166,6 +166,7 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // ours: Inkling 2's grouped experts .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations + .{ .name = "inkling2_loop_math", .src = "inkling2/loop_math", .flags = &.{"-O3"} }, // Mini residuals, cross-pass messages, gates and split QKV .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family .{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5 diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu new file mode 100644 index 00000000000..64b5cfce451 --- /dev/null +++ b/zig/kernels/cuda/inkling2/loop_math.cu @@ -0,0 +1,278 @@ +// Inkling 2 Mini: raw block residuals, two-bank messages, rank-64 gates and three-input QKV projection. +#include +#include + +namespace ink2l { + +constexpr int kRank = 64; +constexpr int kMaxBlocks = 8; +constexpr int kMaxQueries = 3; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } +__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } + +__device__ __forceinline__ float warpSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// Every call has the same reduction tree: lanes' strided chains, each warp's butterfly, then warp 0 over partials. +template +__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); + __syncthreads(); + if (lane == 0) + for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; + __syncthreads(); + for (int i = 0; i < N; ++i) { + const float t = lane < nw ? sh[i * 32 + lane] : 0.0f; + v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); + } +} + +// A14(a): Mini's queried residual and message dot products scale after the dot, by binary32(1 / 48). +__device__ __forceinline__ float queryScale(int c) { + return c == 2304 ? 1.0f / 48.0f : rsqrtf(static_cast(c)); +} + +__device__ __forceinline__ void softmax2(float l0, float l1, float* w) { + const float m = fmaxf(l0, l1); + const float e0 = expf(l0 - m), e1 = expf(l1 - m); + const float d = __fadd_rn(e0, e1); + w[0] = __fdiv_rn(e0, d); + w[1] = __fdiv_rn(e1, d); +} + +struct ArArgs { + const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C], one completed state a pointer + const void* partial; // the final source, BF16 or FP32 according to partial_bf16 + const float* query; // fp32 [nq, C] + float* out; // fp32 [nq, rows, C], deliberately neither normalized nor rounded + int n_blocks, partial_bf16, nq, rows, C; + float eps; +}; + +// The AR half of Small's residual mix, without its fused RMSNorm. Needed before Mini's controller, not just after it. +__device__ void ar(const ArArgs a) { + __shared__ float sh[32 * (1 + kMaxQueries)]; + __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; + __shared__ float rr[kMaxBlocks + 1]; + const size_t row = blockIdx.x; + const int n = a.n_blocks + 1; + auto entry = [&](int j, int c) -> float { + if (j < a.n_blocks) return bf(a.blocks[j][row * a.C + c]); + return a.partial_bf16 ? bf(static_cast(a.partial)[row * a.C + c]) + : static_cast(a.partial)[row * a.C + c]; + }; + for (int j = 0; j < n; ++j) { + float v[1 + kMaxQueries] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + const float x = entry(j, c); + v[0] = __fmaf_rn(x, x, v[0]); + for (int q = 0; q < a.nq; ++q) v[1 + q] = __fmaf_rn(x, a.query[static_cast(q) * a.C + c], v[1 + q]); + } + blockSums<1 + kMaxQueries>(v, sh); + if (threadIdx.x == 0) { + rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(v[0], static_cast(a.C)), a.eps)); + for (int q = 0; q < a.nq; ++q) + wts[q][j] = __fmul_rn(__fmul_rn(v[1 + q], rr[j]), queryScale(a.C)); + } + } + __syncthreads(); + if (threadIdx.x < a.nq) { + float* l = wts[threadIdx.x]; + float m = -INFINITY, d = 0.0f; + for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); + for (int j = 0; j < n; ++j) d = __fadd_rn(d, expf(l[j] - m)); + for (int j = 0; j < n; ++j) l[j] = __fdiv_rn(expf(l[j] - m), d); + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float* out = a.out + (static_cast(q) * a.rows + row) * a.C; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + float h = 0.0f; + for (int j = 0; j < n; ++j) { + const float z = __fmul_rn(entry(j, c), rr[j]); + h = __fmaf_rn(wts[q][j], z, h); + } + out[c] = h; + } + } +} + +} // namespace ink2l + +extern "C" __global__ void __launch_bounds__(512) tf_ink2_loop_ar(const ink2l::ArArgs a) { + ink2l::ar(a); +} + +namespace ink2l { + +// One block handles one token and role, sharing each bank's normalization across all 12 core queries. +__device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, + const float* __restrict__ qm, const float* __restrict__ qkv, + float* __restrict__ out, int core_layers, int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv[2], w[2]; + const size_t row = blockIdx.x; + const int role = blockIdx.y; // q, k, v, mlp + const uint16_t* banks[2] = {bank0 + row * c, bank1 + row * c}; + const float* role_queries = role == 0 || role == 3 ? qm : qkv; + const int odd = role == 3 || role == 2; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float x0 = bf(banks[0][i]), x1 = bf(banks[1][i]); + ss[0] = __fmaf_rn(x0, x0, ss[0]); + ss[1] = __fmaf_rn(x1, x1, ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv[0] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv[1] = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + for (int j = 0; j < core_layers; ++j) { + const float* query = role_queries + static_cast(2 * j + odd) * c; + float dots[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float q = query[i]; + const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); + const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); + dots[0] = __fmaf_rn(q, b0, dots[0]); + dots[1] = __fmaf_rn(q, b1, dots[1]); + } + blockSums<2>(dots, sh); + if (threadIdx.x == 0) + softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); + __syncthreads(); + float* dst = out + ((static_cast(row * core_layers + j) * 4 + role) * static_cast(c)); + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); + const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); + const float m0 = __fmul_rn(w[0], b0), m1 = __fmul_rn(w[1], b1); + dst[i] = __fadd_rn(m0, m1); + } + } +} + +// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). +__device__ void gate(const float* __restrict__ h, const float* __restrict__ m, + const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, + const uint16_t* __restrict__ gain, float* __restrict__ out, + int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv_h, inv_m; + __shared__ uint16_t zeta[kRank]; + const size_t row = blockIdx.x; + const float* hr = h + row * c; + const float* mr = m + row * c; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); + ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + // Pair ranks to reuse each normalized input, but keep every dot's 256-thread chains and two-level reduction tree. + for (int r = 0; r < kRank; r += 2) { + float acc[2] = {0.0f, 0.0f}; + const uint16_t* d0 = down + static_cast(r) * (2 * c); + const uint16_t* d1 = d0 + 2 * c; + for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { + const bool message = i >= c; + const float x = message ? mr[i - c] : hr[i]; + const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); + acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); + acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); + } + blockSums<2>(acc, sh); + if (threadIdx.x == 0) { + zeta[r] = tobf(acc[0]); + zeta[r + 1] = tobf(acc[1]); + } + } + __syncthreads(); + float* dst = out + row * c; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const uint16_t* f = forget + static_cast(i) * kRank; + const uint16_t* g = gain + static_cast(i) * kRank; + float sf = 0.0f, sg = 0.0f; + for (int r = 0; r < kRank; ++r) { + const float z = bf(zeta[r]); + sf = __fmaf_rn(bf(f[r]), z, sf); + sg = __fmaf_rn(bf(g[r]), z, sg); + } + const float fg = tanhf(sf), gg = tanhf(sg); + // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. + const float keep = __fsub_rn(1.0f, fg); + const float old = __fmul_rn(keep, hr[i]); + const float added = __fmul_rn(gg, mr[i]); + dst[i] = __fadd_rn(old, added); + } +} + +} // namespace ink2l + +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, + const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, + int rows, int core_layers, int c, float eps) { + (void)rows; // grid x is rows * core_layers; row derives from pair/core_layers, explicitly visit-local. + ink2l::messages(bank0, bank1, qm, qkv, out, core_layers, c, eps); +} + +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, + const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, + int rows, int c, float eps) { + (void)rows; + ink2l::gate(h, m, down, forget, gain, out, c, eps); +} + +// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, + const uint16_t* __restrict__ uv, const uint16_t* __restrict__ wq, + const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wv, + uint16_t* __restrict__ raw_q, uint16_t* __restrict__ raw_k, + uint16_t* __restrict__ raw_v, int rows, int c, int q_width, int kv_width) { + constexpr int kRows = 16, kOutputs = 16, kSlice = 32; + __shared__ uint16_t sx[kRows * kSlice], sw[kOutputs * kSlice]; + const int role = blockIdx.z; // q=0, k=1, v=2 + const int width = role == 0 ? q_width : kv_width; + const int row0 = static_cast(blockIdx.x) * kRows; + const int j0 = static_cast(blockIdx.y) * kOutputs; + if (j0 >= width) return; + const uint16_t* x = role == 0 ? uq : role == 1 ? uk : uv; + const uint16_t* w = role == 0 ? wq : role == 1 ? wk : wv; + const int tr = threadIdx.x / kOutputs, tj = threadIdx.x % kOutputs; + const int row = row0 + tr, j = j0 + tj; + float sum = 0.0f; + // A block reuses each normalized tile for 16 outputs and each weight tile for 16 prompt rows. + for (int k0 = 0; k0 < c; k0 += kSlice) { + for (int e = threadIdx.x; e < kRows * kSlice; e += blockDim.x) { + const int r = e / kSlice, k = k0 + e % kSlice; + sx[e] = row0 + r < rows && k < c ? x[static_cast(row0 + r) * c + k] : 0; + sw[e] = j0 + r < width && k < c ? w[static_cast(j0 + r) * c + k] : 0; + } + __syncthreads(); + for (int k = 0; k < kSlice && k0 + k < c; ++k) + sum = __fmaf_rn(ink2l::bf(sx[tr * kSlice + k]), ink2l::bf(sw[tj * kSlice + k]), sum); + __syncthreads(); + } + uint16_t* out = role == 0 ? raw_q : role == 1 ? raw_k : raw_v; + if (row < rows && j < width) out[static_cast(row) * width + j] = ink2l::tobf(sum); +} + +// Global dynamic taps: dot in FP32, store as BF16, and widen to FP32 before the convolution. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_round_bf16(const float* __restrict__ in, float* __restrict__ out, long long n) { + const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) out[i] = ink2l::bf(ink2l::tobf(in[i])); +} diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index c8189365e75..7e4277db00f 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -15,6 +15,11 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 272, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, }; /// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. pub const cuda_132 = [_]registry.Override{}; diff --git a/zig/src/core/contract/registry_union.zig b/zig/src/core/contract/registry_union.zig index fa4deb8fd85..41dff1701e2 100644 --- a/zig/src/core/contract/registry_union.zig +++ b/zig/src/core/contract/registry_union.zig @@ -5,7 +5,7 @@ fn has(comptime prior: anytype, comptime record: anytype) bool { return false; } fn count(comptime prior: anytype, comptime additional: anytype) usize { - @setEvalBranchQuota(4000000); + @setEvalBranchQuota(5000000); var n: usize = 0; for (additional) |r| if (!has(prior, r)) { n += 1; @@ -13,7 +13,7 @@ fn count(comptime prior: anytype, comptime additional: anytype) usize { return n; } pub fn extra(comptime prior: anytype, comptime additional: anytype) [count(prior, additional)]@TypeOf(additional[0]) { - @setEvalBranchQuota(4000000); + @setEvalBranchQuota(5000000); var out: [count(prior, additional)]@TypeOf(additional[0]) = undefined; var n: usize = 0; for (additional) |r| if (!has(prior, r)) { diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index c365ca57ba0..b1071d1275c 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -116,6 +116,7 @@ pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops") pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; +pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index d55f6ae813b..0a3eb7b848b 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -8,6 +8,7 @@ pub const experts = @import("experts.zig"); pub const modelopt = @import("modelopt.zig"); pub const loop = @import("loop.zig"); pub const loop_model = @import("loop_model.zig"); +pub const loop_math_cuda = @import("loop_math_cuda.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -21,4 +22,5 @@ test { _ = modelopt; _ = loop; _ = loop_model; + _ = loop_math_cuda; } diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig new file mode 100644 index 00000000000..9a0d4cc4b63 --- /dev/null +++ b/zig/src/families/inkling2/loop_math_cuda.zig @@ -0,0 +1,158 @@ +//! Inkling 2 Mini loop math (inkling2/loop_math.cu): raw AR, two-bank messages, rank-64 gates and split QKV inputs. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const rank = 64; +pub const max_blocks = 8; +pub const max_queries = 3; + +/// loop_math.cu's ArArgs, field for field. `out[q][row][c]` is FP32 AR output before any controller or RMSNorm. +pub const ArArgs = extern struct { + blocks: [max_blocks]u64 = @splat(0), // BF16 [rows][c], each a completed block state + partial: u64, // BF16 when partial_bf16 != 0, otherwise FP32; always the final AR source + query: u64, // FP32 [nq][c] + out: u64, // FP32 [nq][rows][c] + n_blocks: i32, + partial_bf16: i32, + nq: i32, + rows: i32, + c: i32, + eps: f32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + ar_fn: cuda.Function, + messages_fn: cuda.Function, + gate_fn: cuda.Function, + project_qkv_fn: cuda.Function, + round_bf16_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop_math); + errdefer mod.unload(); + return .{ + .mod = mod, + .ar_fn = try mod.function("tf_ink2_loop_ar"), + .messages_fn = try mod.function("tf_ink2_loop_messages"), + .gate_fn = try mod.function("tf_ink2_loop_gate"), + .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), + .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +fn int(x: anytype) i32 { + return @intCast(x); +} + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); +} + +/// Unnormalized block attention residual. No scratch; nq <= 3 and at most 8 completed blocks plus `partial`. +pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { + if (a.n_blocks < 0 or a.n_blocks > max_blocks or a.nq <= 0 or a.nq > max_queries or a.rows <= 0 or a.c <= 0) + return error.Inkling2LoopArShape; + var args: cuda.Args = .{}; + args.add(a); + try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); +} + +/// Messages: BF16 banks, even/odd qm/kv FP32 queries/output; row-local q/k/v/mlp, no scratch/position/mask/cache. +pub fn messages( + k: *const Kernels, + s: cuda.Stream, + bank0_bf16: u64, + bank1_bf16: u64, + queries_qm_f32: u64, + queries_kv_f32: u64, + out_f32: u64, + rows: usize, + core_layers: usize, + c: usize, + eps: f32, +) !void { + if (rows == 0 or core_layers == 0 or c == 0) return error.Inkling2LoopMessageShape; + var a: cuda.Args = .{}; + for ([_]u64{ bank0_bf16, bank1_bf16, queries_qm_f32, queries_kv_f32, out_f32 }) |v| a.add(v); + for ([_]i32{ int(rows), int(core_layers), int(c) }) |v| a.add(v); + a.add(eps); + try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); +} + +/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. +pub fn gate( + k: *const Kernels, + s: cuda.Stream, + state_f32: u64, + message_f32: u64, + down_bf16: u64, + forget_bf16: u64, + gain_bf16: u64, + out_f32: u64, + rows: usize, + c: usize, + eps: f32, +) !void { + if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; + var a: cuda.Args = .{}; + for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); + for ([_]i32{ int(rows), int(c) }) |v| a.add(v); + a.add(eps); + try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); +} + +/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. +pub fn projectQkv( + k: *const Kernels, + s: cuda.Stream, + u_q: u64, + u_k: u64, + u_v: u64, + wq: u64, + wk: u64, + wv: u64, + raw_q: u64, + raw_k: u64, + raw_v: u64, + rows: usize, + c: usize, + q_width: usize, + kv_width: usize, +) !void { + if (rows == 0 or c == 0 or q_width == 0 or kv_width == 0) return error.Inkling2LoopQkvShape; + var a: cuda.Args = .{}; + for ([_]u64{ u_q, u_k, u_v, wq, wk, wv, raw_q, raw_k, raw_v }) |v| a.add(v); + for ([_]i32{ int(rows), int(c), int(q_width), int(kv_width) }) |v| a.add(v); + try go(k.project_qkv_fn, s, .{ .x = @intCast((rows + 15) / 16), .y = @intCast((@max(q_width, kv_width) + 15) / 16), .z = 3 }, 256, &a); +} + +/// BF16-round FP32 then widen, preserving section 6.3 unlike rowdot(false); in/out may alias, no scratch, n=0 no-op. +pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n: usize) !void { + if (n == 0) return; + var a: cuda.Args = .{}; + for ([_]u64{ in_f32, out_f32 }) |v| a.add(v); + a.add(@as(i64, @intCast(n))); + try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); +} + +test "loop math argument ABI and message role offsets" { + try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); + const c = 2304; + const j = 7; + const row = 3; + const core_layers = 12; + const base = ((row * core_layers + j) * 4) * c; + for ([_]usize{ 0, 1, 2, 3 }, 0..) |role, i| { + const at = base + role * c; + const queries = @as(usize, 2 * j + @as(usize, @intFromBool(i == 2 or i == 3))) * c; + try std.testing.expect(at >= base and queries < 24 * c); + } +} diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index 57b41e050ae..1ab486edf31 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -10,6 +10,7 @@ pub const Set = struct { attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, experts: @import("contract_inkling2_experts.zig").Set = .{}, + loop_math: @import("contract_inkling2_loop_math_extra.zig").Set = .{}, /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -22,10 +23,12 @@ pub const Set = struct { errdefer set.ops.deinit(); try set.experts.init(gpu, s, a, list); errdefer set.experts.deinit(); + try set.loop_math.init(gpu, s, a, list); return set; } pub fn deinit(set: *Set) void { + set.loop_math.deinit(); set.experts.deinit(); set.ops.deinit(); set.attn.deinit(); diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig new file mode 100644 index 00000000000..37fe14871a2 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop_math.zig @@ -0,0 +1,479 @@ +//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. +const std = @import("std"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lm = ink.loop_math_cuda; +pub const eps = ref.eps; +pub const mini_h = 2304; + +/// Exact raw-output checks, with interval references and accumulator simulations for gate 4. +pub fn Checked(comptime T: type) type { + return struct { + const Self = @This(); + inner: ref.Gated(T), + rig: *rig_.Rig = undefined, + msg: [200]u8 = undefined, + + pub fn deinit(self: *Self) void { + self.inner.deinit(); + } + + pub fn kernel(self: *Self) g.Kernel { + self.rig = &self.inner.rig; + return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; + } + + const vt = g.hooks(Self); + + pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return self.inner.prepare(shape, fill, seed); + } + + pub fn run(self: *Self) !void { + try self.inner.run(); + } + + pub fn count(self: *Self) usize { + return self.inner.count(); + } + + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + try self.inner.reference(want, mag); + } + + pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { + try self.inner.bounds(want, mag, allow); + } + + pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.inner.simulate(acc, order, out); + } + + pub fn check(self: *Self, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + return self.inner.k.check(a, got, &self.msg); + } + }; +} + +pub fn queryScale(cols: usize) ref.Iv { + return if (cols == mini_h) ref.Iv.of(scale(cols)) else ref.Iv.of(@floatFromInt(cols)).rsqrt(); +} + +pub fn softmax(logits: []ref.Iv) void { + var m = logits[0]; + for (logits[1..]) |v| m = .{ .m = @max(m.m, v.m), .lo = @max(m.lo, v.lo), .hi = @max(m.hi, v.hi) }; + var den = ref.Iv.of(0); + for (logits) |*v| { + v.* = v.sub(m).exp(); + den = den.add(v.*); + } + for (logits) |*v| v.* = v.div(den); +} + +/// Irregular integer squares stay exact in FP32 for gate 4, but overflow FP16 and round in every BF16 order. +fn stressBank(i: usize) f32 { + return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; +} + +/// Messages nearly cancel two normalized banks; the unmatched first tap keeps FP16 normalization overflow visible. +fn messageStressBank(bank: usize, col: usize, cols: usize) f32 { + if (bank == 0) return stressBank(col); + if (col == 0) return 0; + return -stressBank((col + 1) % cols); +} + +/// AR cyclically assigns [x, -x, 0] over its sources so zero-query outputs expose RMS-sum differences. +pub fn arStressSource(source: usize, col: usize) f32 { + if (source == 0 and col == 0) return 0; + const value = stressBank(col - col % 3); + return switch ((col + 2 * source) % 3) { + 0 => value, + 1 => -value, + 2 => 0, + else => unreachable, + }; +} + +pub fn close(got: f32, want: f32) bool { + if (std.math.isNan(want)) return std.math.isNan(got); + if (!std.math.isFinite(want)) return got == want; + if (!std.math.isFinite(got)) return false; + const tolerance = 1e-4 * (1.0 + @abs(want)); + return @abs(got - want) <= tolerance; +} + +pub fn bf(x: u16) f32 { + return @floatCast(ref.bf(x)); +} + +pub fn bfRound(x: f32) f32 { + return bf(c.toBf16(x)); +} +pub fn cudaMax(a: f32, b: f32) f32 { + if (std.math.isNan(a)) return b; + if (std.math.isNan(b)) return a; + return @max(a, b); +} + +pub fn sameBf(got: u16, want: u16) bool { + if ((want & 0x7fff) > 0x7f80) return (got & 0x7fff) > 0x7f80; // NaN payload is not part of the math rule + return got == want; +} + +pub fn scale(cols: usize) f32 { + return if (cols == mini_h) 1.0 / 48.0 else 1.0 / @sqrt(@as(f32, @floatFromInt(cols))); +} + +fn warp(v: *[32]f32) f32 { + var offset: usize = 16; + while (offset != 0) : (offset >>= 1) { + const old = v.*; + for (0..32) |lane| v.*[lane] = old[lane] + old[lane ^ offset]; + } + return v.*[0]; +} + +/// The exact lane chains and butterfly tree of loop_math.cu. Terms are fused into each lane's accumulator. +pub fn reduce(a: []const f32, b: []const f32, threads: usize) f32 { + var partial: [32]f32 = @splat(0); + for (0..threads / 32) |w| { + var lanes: [32]f32 = undefined; + for (0..32) |lane| { + const tid = w * 32 + lane; + var sum: f32 = 0; + var i = tid; + while (i < a.len) : (i += threads) sum = @mulAdd(f32, a[i], b[i], sum); + lanes[lane] = sum; + } + partial[w] = warp(&lanes); + } + return warp(&partial); +} + +pub fn fail(msg: []u8, comptime fmt: []const u8, args: anytype) !?[]const u8 { + return try std.fmt.bufPrint(msg, fmt, args); +} + +const message_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 4 * 12 * mini_h, .k = mini_h }, + .{ .rows = 16, .n = 4 * 128, .k = 128 }, + .{ .rows = 2048, .n = 4 * 128, .k = 128 }, +}; + +/// Two normalized banks and the checkpoint's even/odd q,mlp and k,v queries, compared element by element. +pub const Messages = struct { + kern: *const lm.Kernels, + aliased: bool = false, + shape: c.Shape = undefined, + banks: [2][]u16 = .{ &.{}, &.{} }, + queries: [2][]f32 = .{ &.{}, &.{} }, + dev: [5]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Messages) c.Spec { + return .{ .name = if (self.aliased) "control: inkling2 loop messages with both previous-pass inputs wired to bank zero" else "inkling2 loop tf_ink2_loop_messages (two normalized banks, post-dot 1/48, four roles)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) message_shapes[0..2] else &message_shapes }; + } + + fn depth(s: c.Shape) usize { + return 2 * ((s.k + 255) / 256 + 10); + } + + pub fn control(self: *const Messages) ?g.Gate { + return if (self.aliased) .shapes else null; + } + + pub fn free(self: *Messages, a: std.mem.Allocator) void { + for (&self.banks) |*x| a.free(x.*); + for (&self.queries) |*x| a.free(x.*); + self.banks = .{ &.{}, &.{} }; + self.queries = .{ &.{}, &.{} }; + } + + pub fn prepare(self: *Messages, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.n % (4 * shape.k) != 0) return false; + self.free(a); + self.shape = shape; + const cols = shape.k; + const layers = shape.n / (4 * cols); + for (&self.banks, 0..) |*x, bank| { + x.* = try a.alloc(u16, shape.rows * cols); + if (fill == .stress) { + for (x.*, 0..) |*v, i| v.* = c.toBf16(messageStressBank(bank, i % cols, cols)); + } else for (x.*) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + } + for (&self.queries) |*x| { + x.* = try ref.f32s(a, rng, 2 * layers * cols, -0.25, 0.25); + if (fill == .stress) @memset(x.*, 0); + } + if (fill == .nonfinite) { + ref.plant(u16, self.banks[0], shape.rows, cols, ref.asBf); + ref.plant(u16, self.banks[1], shape.rows, cols, ref.asBf); + } + for (self.banks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + for (self.queries, 0..) |x, i| self.dev[2 + i] = try ref.input(rig, x); + self.out = try rig.output(shape.rows * shape.n * 4); + return true; + } + + pub fn run(self: *Messages, rig: *rig_.Rig) !void { + const b1 = if (self.aliased) self.dev[0] else self.dev[1]; + const layers = self.shape.n / (4 * self.shape.k); + try lm.messages(self.kern, rig.s, self.dev[0], b1, self.dev[2], self.dev[3], self.out, self.shape.rows, layers, self.shape.k, eps); + } + + pub fn count(self: *const Messages) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Messages, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.k; + const layers = self.shape.n / (4 * cols); + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + const later = ref.later(s); + for (0..self.shape.rows) |row| { + var inv: [2]ref.Iv = undefined; + for (0..2) |b| { + for (terms, self.banks[b][row * cols ..][0..cols]) |*t, v| { + const x = ref.Iv.of(ref.bf(v)); + t.* = x.mul(x); + } + inv[b] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); + } + for (0..layers) |j| for (0..4) |role| { + const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; + var logits: [2]ref.Iv = undefined; + for (0..2) |b| { + for (terms, query, self.banks[b][row * cols ..][0..cols]) |*t, q, v| t.* = ref.Iv.of(q).mul(ref.Iv.of(ref.bf(v)).mul(inv[b])); + logits[b] = later.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); + } + softmax(&logits); + for (0..cols) |i| { + var value = ref.Iv.of(0); + for (0..2) |b| { + const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); + value = value.add(logits[b].mul(beta)); + } + const at = ((row * layers + j) * 4 + role) * cols + i; + out[at] = value; + } + }; + } + } + + pub fn check(self: *const Messages, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.k; + const layers = self.shape.n / (4 * cols); + const raw0 = try a.alloc(f32, cols); + defer a.free(raw0); + const raw1 = try a.alloc(f32, cols); + defer a.free(raw1); + const beta0 = try a.alloc(f32, cols); + defer a.free(beta0); + const beta1 = try a.alloc(f32, cols); + defer a.free(beta1); + for (0..self.shape.rows) |row| { + for (raw0, self.banks[0][row * cols ..][0..cols]) |*x, v| x.* = bf(v); + for (raw1, self.banks[1][row * cols ..][0..cols]) |*x, v| x.* = bf(v); + const inv0 = 1.0 / @sqrt(reduce(raw0, raw0, 256) / @as(f32, @floatFromInt(cols)) + eps); + const inv1 = 1.0 / @sqrt(reduce(raw1, raw1, 256) / @as(f32, @floatFromInt(cols)) + eps); + for (beta0, raw0) |*x, v| x.* = v * inv0; + for (beta1, raw1) |*x, v| x.* = v * inv1; + for (0..layers) |j| for (0..4) |role| { + const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; + const l0 = reduce(query, beta0, 256) * scale(cols); + const l1 = reduce(query, beta1, 256) * scale(cols); + const m = cudaMax(l0, l1); + const e0 = @exp(l0 - m); + const e1 = @exp(l1 - m); + const den = e0 + e1; + const w0 = e0 / den; + const w1 = e1 / den; + for (0..cols) |i| { + const want = w0 * beta0[i] + w1 * beta1[i]; + const at = ((row * layers + j) * 4 + role) * cols + i; + const value = ref.readF32(got, at); + if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); + } + }; + } + return null; + } +}; + +const gate_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 2 * mini_h }, + .{ .rows = 16, .n = mini_h, .k = 2 * mini_h }, + .{ .rows = 2048, .n = 128, .k = 256 }, +}; + +/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. +pub const Gate = struct { + kern: *const lm.Kernels, + wrong_gain: bool = false, + shape: c.Shape = undefined, + h: []f32 = &.{}, + m: []f32 = &.{}, + d: []u16 = &.{}, + f: []u16 = &.{}, + gain: []u16 = &.{}, + dev: [5]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Gate) c.Spec { + return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; + } + + fn depth(s: c.Shape) usize { + return (s.k + 255) / 256 + 10 + lm.rank; + } + + pub fn control(self: *const Gate) ?g.Gate { + return if (self.wrong_gain) .shapes else null; + } + + pub fn free(self: *Gate, a: std.mem.Allocator) void { + a.free(self.h); + a.free(self.m); + a.free(self.d); + a.free(self.f); + a.free(self.gain); + self.h = &.{}; + self.m = &.{}; + self.d = &.{}; + self.f = &.{}; + self.gain = &.{}; + } + + pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != 2 * shape.n) return false; + self.free(a); + self.shape = shape; + const cols = shape.n; + self.h = try ref.f32s(a, rng, shape.rows * cols, -1, 1); + self.m = try ref.f32s(a, rng, shape.rows * cols, -1, 1); + self.d = try ref.bfs(a, rng, lm.rank * 2 * cols, -0.1, 0.1); + self.f = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); + self.gain = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); + if (fill == .stress) { + for (self.h, 0..) |*v, i| v.* = stressBank(i % cols); + for (self.m, 0..) |*v, i| v.* = stressBank(i % cols); + for (self.d) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.f) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + } + if (fill == .nonfinite) { + ref.plant(f32, self.h, shape.rows, cols, ref.asF32); + ref.plant(f32, self.m, shape.rows, cols, ref.asF32); + } + self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; + self.out = try rig.output(shape.rows * cols * 4); + return true; + } + + pub fn run(self: *Gate, rig: *rig_.Rig) !void { + try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); + } + + pub fn count(self: *const Gate) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Gate, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.n; + const n = try a.alloc(ref.Iv, 2 * cols); + defer a.free(n); + const terms = try a.alloc(ref.Iv, 2 * cols); + defer a.free(terms); + const scratch = try a.alloc(f64, 2 * cols); + defer a.free(scratch); + const zeta = try a.alloc(ref.Iv, lm.rank); + defer a.free(zeta); + const later = ref.later(s); + const zeta_depth = (2 * cols + 31) / 32 + 5; + for (0..self.shape.rows) |row| { + const h = self.h[row * cols ..][0..cols]; + const m = self.m[row * cols ..][0..cols]; + var inv: [2]ref.Iv = undefined; + for (0..2) |b| { + const x = if (b == 0) h else m; + for (terms[0..cols], x) |*t, v| { + const e = ref.Iv.of(v); + t.* = e.mul(e); + } + inv[b] = ref.rms(s.sum(terms[0..cols], depth(self.shape), scratch), cols, eps); + } + for (n[0..cols], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); + for (n[cols..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); + for (0..lm.rank) |r| { + for (terms, n, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); + zeta[r] = later.sum(terms, zeta_depth, scratch).bf(); + } + for (0..cols) |i| { + for (terms[0..lm.rank], zeta, self.f[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const forget = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); + for (terms[0..lm.rank], zeta, self.gain[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const gain = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); + const keep = ref.Iv.of(1).sub(forget); + const old = keep.mul(ref.Iv.of(h[i])); + const added = gain.mul(ref.Iv.of(m[i])); + out[row * cols + i] = old.add(added); + } + } + } + + pub fn check(self: *const Gate, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.n; + const n = try a.alloc(f32, 2 * cols); + defer a.free(n); + const weights = try a.alloc(f32, 2 * cols); + defer a.free(weights); + const zeta = try a.alloc(f32, lm.rank); + defer a.free(zeta); + const zf = try a.alloc(f32, lm.rank); + defer a.free(zf); + const zg = try a.alloc(f32, lm.rank); + defer a.free(zg); + for (0..self.shape.rows) |row| { + const h = self.h[row * cols ..][0..cols]; + const m = self.m[row * cols ..][0..cols]; + const ih = 1.0 / @sqrt(reduce(h, h, 256) / @as(f32, @floatFromInt(cols)) + eps); + const im = 1.0 / @sqrt(reduce(m, m, 256) / @as(f32, @floatFromInt(cols)) + eps); + for (n[0..cols], h) |*v, x| v.* = bfRound(x * ih); + for (n[cols..], m) |*v, x| v.* = bfRound(x * im); + for (0..lm.rank) |r| { + for (weights, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*v, w| v.* = bf(w); + zeta[r] = bfRound(reduce(weights, n, 256)); + } + for (0..cols) |i| { + for (zf, self.f[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); + for (zg, self.gain[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); + var sf: f32 = 0; + var sg: f32 = 0; + for (0..lm.rank) |r| { + sf = @mulAdd(f32, zf[r], zeta[r], sf); + sg = @mulAdd(f32, zg[r], zeta[r], sg); + } + const forget = std.math.tanh(sf); + const gain = std.math.tanh(sg); + const keep: f32 = 1.0 - forget; + const old: f32 = keep * h[i]; + const added: f32 = gain * m[i]; + const want: f32 = old + added; + const value = ref.readF32(got, row * cols + i); + if (!close(value, want)) return fail(msg, "row {d} col {d}: {e} where {e} is due", .{ row, i, value, want }); + } + } + return null; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig new file mode 100644 index 00000000000..38e3b3d9a4c --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig @@ -0,0 +1,408 @@ +//! Mini QKV projection, raw AR and BF16 tap rounding, with the loop suites' shared registration. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); +const base = @import("contract_inkling2_loop_math.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lm = ink.loop_math_cuda; +const K = base.Checked; +const eps = base.eps; +const mini_h = base.mini_h; +const queryScale = base.queryScale; +const softmax = base.softmax; +const arStressSource = base.arStressSource; +const close = base.close; +const bf = base.bf; +const bfRound = base.bfRound; +const cudaMax = base.cudaMax; +const sameBf = base.sameBf; +const scale = base.scale; +const reduce = base.reduce; +const fail = base.fail; +const Messages = base.Messages; +const Gate = base.Gate; +const qkv_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 3072, .k = mini_h }, + .{ .rows = 16, .n = 384, .k = 128 }, + .{ .rows = 2048, .n = 384, .k = 128 }, +}; + +/// Distinct q/k/v rows, with the Small single-input aliasing bug planted as the control. +pub const ProjectQkv = struct { + kern: *const lm.Kernels, + shared_input: bool = false, + shape: c.Shape = undefined, + u: [3][]u16 = .{ &.{}, &.{}, &.{} }, + w: [3][]u16 = .{ &.{}, &.{}, &.{} }, + dev: [6]u64 = @splat(0), + out: [3]u64 = @splat(0), + + pub fn spec(self: *const ProjectQkv) c.Spec { + return .{ .name = if (self.shared_input) "control: Mini split QKV projection using Small's one normalized input for all roles" else "inkling2 loop tf_ink2_loop_project_qkv (distinct normalized q/k/v inputs, unchanged raw layouts)", .accum = .f32, .depth = depth, .out = .bf16, .served = if (self.shared_input) qkv_shapes[0..2] else &qkv_shapes }; + } + + fn depth(s: c.Shape) usize { + return s.k; + } + + pub fn control(self: *const ProjectQkv) ?g.Gate { + return if (self.shared_input) .shapes else null; + } + + pub fn free(self: *ProjectQkv, a: std.mem.Allocator) void { + for (&self.u) |*x| a.free(x.*); + for (&self.w) |*x| a.free(x.*); + self.u = .{ &.{}, &.{}, &.{} }; + self.w = .{ &.{}, &.{}, &.{} }; + } + + pub fn prepare(self: *ProjectQkv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 3 != 0 or shape.k == 0) return false; + self.free(a); + self.shape = shape; + for (&self.u) |*x| x.* = try ref.bfs(a, rng, shape.rows * shape.k, -1, 1); + for (&self.w, 0..) |*x, role| x.* = try ref.bfs(a, rng, (if (role == 0) shape.n else shape.n / 3) * shape.k, -0.1, 0.1); + if (fill == .stress) { + // Mirrored products cancel to eight small FP32 terms; lower precisions lose their large partials. + const half = shape.k / 2; + for (self.u) |bank| for (0..shape.rows) |row| { + const values = bank[row * shape.k ..][0..shape.k]; + for (0..half) |i| { + values[i] = c.toBf16(ref.int(rng, 8, 16)); + values[half + i] = values[i]; + } + if (shape.k % 2 != 0) values[shape.k - 1] = 0; + }; + for (self.w) |bank| for (0..bank.len / shape.k) |row| { + const values = bank[row * shape.k ..][0..shape.k]; + for (0..half) |i| { + const v = ref.int(rng, 8, 16); + values[i] = c.toBf16(v); + values[half + i] = c.toBf16(-v); + } + for (0..@min(8, half)) |i| values[half + i] = c.toBf16(1 - bf(values[i])); + if (shape.k % 2 != 0) values[shape.k - 1] = 0; + }; + } + if (fill == .nonfinite) for (&self.u) |*x| ref.plant(u16, x.*, shape.rows, shape.k, ref.asBf); + for (self.u, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + for (self.w, 0..) |x, i| self.dev[3 + i] = try ref.input(rig, x); + for (0..3) |role| self.out[role] = try rig.output(shape.rows * (if (role == 0) shape.n else shape.n / 3) * 2); + return true; + } + + pub fn run(self: *ProjectQkv, rig: *rig_.Rig) !void { + const k = if (self.shared_input) self.dev[0] else self.dev[1]; + const v = if (self.shared_input) self.dev[0] else self.dev[2]; + try lm.projectQkv(self.kern, rig.s, self.dev[0], k, v, self.dev[3], self.dev[4], self.dev[5], self.out[0], self.out[1], self.out[2], self.shape.rows, self.shape.k, self.shape.n, self.shape.n / 3); + } + + pub fn count(self: *const ProjectQkv) usize { + return self.shape.rows * self.shape.n * 5 / 3; + } + + pub fn solve(self: *const ProjectQkv, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.k; + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + var offset: usize = 0; + for (0..3) |role| { + const width = if (role == 0) self.shape.n else self.shape.n / 3; + for (0..self.shape.rows) |row| for (0..width) |j| { + for (terms, self.u[role][row * cols ..][0..cols], self.w[role][j * cols ..][0..cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(x) * ref.bf(w)); + out[offset + row * width + j] = s.sum(terms, depth(self.shape), scratch).bf(); + }; + offset += self.shape.rows * width; + } + } + + pub fn check(self: *const ProjectQkv, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.k; + const x = try a.alloc(f32, cols); + defer a.free(x); + const w = try a.alloc(f32, cols); + defer a.free(w); + var byte_at: usize = 0; + for (0..3) |role| { + const width = if (role == 0) self.shape.n else self.shape.n / 3; + for (0..self.shape.rows) |row| for (0..width) |j| { + for (x, self.u[role][row * cols ..][0..cols]) |*v, u| v.* = bf(u); + for (w, self.w[role][j * cols ..][0..cols]) |*v, u| v.* = bf(u); + var sum: f32 = 0; + for (0..cols) |i| sum = @mulAdd(f32, x[i], w[i], sum); + const want = c.toBf16(sum); + const at = byte_at + (row * width + j) * 2; + const value = std.mem.readInt(u16, got[at..][0..2], .little); + if (!sameBf(value, want)) return fail(msg, "role {d} row {d} output {d}: {x} where {x} is due", .{ role, row, j, value, want }); + }; + byte_at += self.shape.rows * width * 2; + } + return null; + } +}; + +const ar_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 1 }, + .{ .rows = 16, .n = 128, .k = 3 }, + .{ .rows = 2048, .n = 128, .k = 3 }, +}; + +/// Raw AR before controllers. Two completed blocks plus a partial; control omits the second completed block. +pub const Ar = struct { + kern: *const lm.Kernels, + partial_bf16: bool, + short: bool = false, + shape: c.Shape = undefined, + blocks: [2][]u16 = .{ &.{}, &.{} }, + partial32: []f32 = &.{}, + partial16: []u16 = &.{}, + query: []f32 = &.{}, + dev: [4]u64 = @splat(0), // two blocks, partial, query + out: u64 = 0, + + pub fn spec(self: *const Ar) c.Spec { + return .{ .name = if (self.short) "control: inkling2 loop raw AR omitting its second completed block" else if (self.partial_bf16) "inkling2 loop tf_ink2_loop_ar (BF16 partial, FP32 unnormalized output)" else "inkling2 loop tf_ink2_loop_ar (FP32 partial, FP32 unnormalized output)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.short) ar_shapes[1..2] else &ar_shapes }; + } + + fn depth(s: c.Shape) usize { + return (s.n + 511) / 512 + 10 + 3; + } + + pub fn control(self: *const Ar) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *Ar, a: std.mem.Allocator) void { + for (&self.blocks) |*x| a.free(x.*); + a.free(self.partial32); + a.free(self.partial16); + a.free(self.query); + self.blocks = .{ &.{}, &.{} }; + self.partial32 = &.{}; + self.partial16 = &.{}; + self.query = &.{}; + } + + pub fn prepare(self: *Ar, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > lm.max_queries) return false; + self.free(a); + self.shape = shape; + for (&self.blocks, 0..) |*x, source| { + x.* = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (x.*, 0..) |*v, i| v.* = c.toBf16(arStressSource(source, i % shape.n)); + } + } + if (self.partial_bf16) { + self.partial16 = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (self.partial16, 0..) |*v, i| v.* = c.toBf16(arStressSource(2, i % shape.n)); + } + self.dev[2] = try ref.input(rig, self.partial16); + } else { + self.partial32 = try ref.f32s(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (self.partial32, 0..) |*v, i| v.* = arStressSource(2, i % shape.n); + } + self.dev[2] = try ref.input(rig, self.partial32); + } + self.query = try ref.f32s(a, rng, shape.k * shape.n, -0.25, 0.25); + if (fill == .stress) @memset(self.query, 0); + if (fill == .nonfinite) for (&self.blocks) |*x| ref.plant(u16, x.*, shape.rows, shape.n, ref.asBf); + for (self.blocks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + self.dev[3] = try ref.input(rig, self.query); + self.out = try rig.output(shape.rows * shape.n * shape.k * 4); + return true; + } + + pub fn run(self: *Ar, rig: *rig_.Rig) !void { + var args: lm.ArArgs = .{ .partial = self.dev[2], .query = self.dev[3], .out = self.out, .n_blocks = if (self.short) 1 else 2, .partial_bf16 = @intFromBool(self.partial_bf16), .nq = @intCast(self.shape.k), .rows = @intCast(self.shape.rows), .c = @intCast(self.shape.n), .eps = eps }; + args.blocks[0] = self.dev[0]; + args.blocks[1] = self.dev[1]; + try lm.ar(self.kern, rig.s, args); + } + + pub fn count(self: *const Ar) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + fn entry(self: *const Ar, source: usize, row: usize, col: usize) f32 { + const at = row * self.shape.n + col; + return if (source < 2) bf(self.blocks[source][at]) else if (self.partial_bf16) bf(self.partial16[at]) else self.partial32[at]; + } + + pub fn solve(self: *const Ar, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.n; + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + for (0..self.shape.rows) |row| { + var inv: [3]ref.Iv = undefined; + for (0..3) |j| { + for (terms, 0..) |*t, i| { + const x = ref.Iv.of(self.entry(j, row, i)); + t.* = x.mul(x); + } + inv[j] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); + } + for (0..self.shape.k) |q| { + var logits: [3]ref.Iv = undefined; + for (0..3) |j| { + for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(ref.Iv.of(self.query[q * cols + i])); + logits[j] = s.sum(terms, depth(self.shape), scratch).mul(inv[j]).mul(queryScale(cols)); + } + softmax(&logits); + for (0..cols) |i| { + var value = ref.Iv.of(0); + for (0..3) |j| { + const beta = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]); + value = value.add(logits[j].mul(beta)); + } + out[(q * self.shape.rows + row) * cols + i] = value; + } + } + } + } + + pub fn check(self: *const Ar, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.n; + const sources = 3; + const raw = try a.alloc(f32, cols); + defer a.free(raw); + const beta = try a.alloc(f32, sources * cols); + defer a.free(beta); + const weights = try a.alloc(f32, sources); + defer a.free(weights); + for (0..self.shape.rows) |row| { + var invs: [3]f32 = undefined; + for (0..sources) |j| { + for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); + invs[j] = 1.0 / @sqrt(reduce(raw, raw, 512) / @as(f32, @floatFromInt(cols)) + eps); + for (beta[j * cols ..][0..cols], raw) |*v, x| v.* = x * invs[j]; + } + for (0..self.shape.k) |q| { + var logits: [3]f32 = undefined; + var m = -std.math.inf(f32); + for (0..sources) |j| { + const query = self.query[q * cols ..][0..cols]; + for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); + logits[j] = reduce(query, raw, 512) * invs[j] * scale(cols); + m = cudaMax(m, logits[j]); + } + var den: f32 = 0; + for (0..sources) |j| { + weights[j] = @exp(logits[j] - m); + den += weights[j]; + } + for (0..sources) |j| weights[j] /= den; + for (0..cols) |i| { + var want: f32 = 0; + for (0..sources) |j| want = @mulAdd(f32, weights[j], beta[j * cols + i], want); + const at = (q * self.shape.rows + row) * cols + i; + const value = ref.readF32(got, at); + if (!close(value, want)) return fail(msg, "query {d} row {d} col {d}: {e} where {e} is due", .{ q, row, i, value, want }); + } + } + } + return null; + } +}; + +const round_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 1 }, + .{ .rows = 2048, .n = 32, .k = 1 }, +}; + +/// Dynamic taps' required BF16 storage rounding, followed by exact widening for the FP32 convolution. +pub const RoundBf16 = struct { + kern: *const lm.Kernels, + short: bool = false, + shape: c.Shape = undefined, + x: []f32 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const RoundBf16) c.Spec { + return .{ .name = if (self.short) "control: inkling2 loop dynamic taps leave the final value unrounded" else "inkling2 loop tf_ink2_loop_round_bf16 (global dynamic taps, BF16 then FP32)", .accum = .none, .depth = ref.noSums, .out = .f32, .served = if (self.short) round_shapes[0..1] else &round_shapes }; + } + + pub fn control(self: *const RoundBf16) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *RoundBf16, a: std.mem.Allocator) void { + a.free(self.x); + self.x = &.{}; + } + + pub fn prepare(self: *RoundBf16, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + self.x = try ref.f32s(a, rng, shape.rows * shape.n, -32, 32); + if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); + self.dev = try ref.input(rig, self.x); + self.out = try rig.output(self.x.len * 4); + return true; + } + + pub fn run(self: *RoundBf16, rig: *rig_.Rig) !void { + try lm.roundBf16(self.kern, rig.s, self.dev, self.out, self.x.len - @intFromBool(self.short)); + } + + pub fn count(self: *const RoundBf16) usize { + return self.x.len; + } + + pub fn solve(self: *const RoundBf16, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { + for (out, self.x) |*o, x| o.* = ref.Iv.of(x).bf(); + } + + pub fn check(self: *const RoundBf16, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + for (self.x, 0..) |x, i| { + const want = bfRound(x); + const value = ref.readF32(got, i); + if (!ref.sameF32(value, want)) return fail(msg, "tap {d}: {e} where {e} is due", .{ i, value, want }); + } + return null; + } +}; + +pub const Set = struct { + k: lm.Kernels = undefined, + loaded: bool = false, + messages: [2]K(Messages) = undefined, + gates: [2]K(Gate) = undefined, + qkvs: [2]K(ProjectQkv) = undefined, + ars: [3]K(Ar) = undefined, + rounds: [2]K(RoundBf16) = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.k = try lm.Kernels.load(gpu.d); + set.loaded = true; + const k = &set.k; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; + for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; + for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; + for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; + inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.loaded) return; + inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| x.deinit(); + set.k.unload(); + set.loaded = false; + } +}; diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index f8dac6388e4..acbb9b75998 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -32,7 +32,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; } diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index e401808d50a..38b6f21e94f 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 195d3693f3c72e8d2c011088cd34d7839bc0111dfe1a213a2a7c7b62ef8a4031 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt image registered; #1858: the idol_decoder image registered +zig/src/cuda/kernels.zig 883d432ebce183cc554d6f0d61944a4d87df845f3eae3174d6f6307fed7e7612 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw From a775a32cfbb291ac5bccb7286ca8b8aea016779e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:38:53 +0000 Subject: [PATCH 13/84] inkling2: serve Mini text on one CUDA rank Run all 48 visits with per-visit cache state, prompt snapshots and exact rollback. Refuse TP, vision and DSpark loading until those engines exist. --- CHANGELOG.md | 1 + THIRD_PARTY_NOTICES.md | 1 - zig/build/cuda_engines.zig | 1 + zig/build/inkling2_host.zig | 9 +- zig/src/families/inkling2/cuda_native.zig | 171 +++++++ zig/src/families/inkling2/inkling2.zig | 2 + zig/src/families/inkling2/loop_backend.zig | 297 +++++++++++ zig/src/families/inkling2/loop_engine.zig | 570 +++++++++++++++++++++ zig/src/families/inkling2/loop_weights.zig | 226 ++++++++ zig/src/families/inkling2/names.zig | 2 +- zig/src/families/inkling2/names_test.zig | 2 +- zig/src/native/cuda_families.zig | 7 +- 12 files changed, 1281 insertions(+), 8 deletions(-) create mode 100644 zig/src/families/inkling2/cuda_native.zig create mode 100644 zig/src/families/inkling2/loop_backend.zig create mode 100644 zig/src/families/inkling2/loop_engine.zig create mode 100644 zig/src/families/inkling2/loop_weights.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 9387b7e7e8f..890b7ec31fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -146,6 +146,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds each 512-key chunk's two pages once instead of reading the page table at every 32-key step, with every token and cache row unchanged (#3180, part of #1293). Thanks to @CodingEmil. - Nemotron 3.5 Lightning on HIP: the MTP head file is read at the width its own metadata states, so it drafts beside an oQ checkpoint of any width, and a head at a width the launches do not read is refused by name (#3251, part of #3061). Thanks to @gilby. +- Inkling 2 Mini (`inkling2_loop`) on one CUDA rank: the 48-visit text loop now runs its cross-pass messages, rank-64 gates and separate sliding Q/K/V inputs, with per-visit KV and convolution state, prompt snapshots and exact rollback. Routed experts decode stored NVFP4 and MXFP8 weights to bf16 with the reference's rounding and ascending-expert FP32 accumulation; activation quantization is not used. TP, vision and DSpark loading remain refused by name. - Inkling 2 on CUDA: the family's grouped-expert launches match main's `tf_exl3_grouped_2` bit for bit under the kernel contract, and the vision tower's kernels pass gates 1 to 4 (refs #3476). Thanks to @ajensenwaud. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 18458a70310..c653a7a7531 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -582,4 +582,3 @@ arithmetic. `zig/kernels/cuda/inkling2/vision.cu` and `zig/src/families/inkling2 vision tower: `Inkling2VisionEmbeddings`, `Inkling2VisionRotaryEmbedding`, `Inkling2VisionAttention`, `Inkling2VisionMLP` and `Inkling2VisionMerger`. `zig/src/families/inkling2/image.zig` follows `Inkling2ImageProcessor` in `image_processing_inkling2.py` at the same commit for its 40-pixel patches and the tower's input tables. - diff --git a/zig/build/cuda_engines.zig b/zig/build/cuda_engines.zig index 62081da2cbc..e6aef168928 100644 --- a/zig/build/cuda_engines.zig +++ b/zig/build/cuda_engines.zig @@ -86,6 +86,7 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .{ .name = "gemma4_cuda", .module = @import("gemma4_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "spark25", .module = @import("spark25.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "lfm2_moe_cuda", .module = @import("lfm2_moe_cuda.zig").module(b, target, optimize, cuda, core, lanes) }, + .{ .name = "inkling2", .module = @import("inkling2.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "dory", .module = @import("dory.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "dots_mocr_cuda", .module = @import("dots_mocr_cuda.zig").module(b, target, optimize, cuda, core, lanes, @import("cuda_dense.zig").module(b, target, optimize, cuda, core, lanes)) }, .{ .name = "muse_spark", .module = @import("muse.zig").moduleOver(b, target, optimize, cuda, core, lanes, @import("tp.zig").moduleWith(b, target, optimize, cuda, verbs)) }, diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 423dd15b0fc..3212e0f94c6 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -4,8 +4,13 @@ const std = @import("std"); fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, root: []const u8) *std.Build.Module { const m = b.createModule(.{ .root_source_file = b.path(root), .target = target, .optimize = optimize, .link_libc = true }); const dir = "zig/src/core/"; - m.addImport("tokenizer", b.createModule(.{ .root_source_file = b.path(dir ++ "tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true })); - m.addImport("safetensors", b.createModule(.{ .root_source_file = b.path(dir ++ "safetensors.zig"), .target = target, .optimize = optimize, .link_libc = true })); + const tokenizer = b.createModule(.{ .root_source_file = b.path(dir ++ "tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); + m.addImport("tokenizer", tokenizer); + const core = b.createModule(.{ .root_source_file = b.path(dir ++ "root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); + core.addImport("tokenizer", tokenizer); + core.addImport("living", b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true })); + m.addImport("core", core); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); return m; } diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig new file mode 100644 index 00000000000..6ab676368a9 --- /dev/null +++ b/zig/src/families/inkling2/cuda_native.zig @@ -0,0 +1,171 @@ +//! Inkling 2 Mini's complete one-rank, text-only CUDA engine and checkpoint/snapshot admission. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const loop = @import("loop.zig"); +const engine = @import("loop_engine.zig"); +const backend = @import("loop_backend.zig"); + +pub const model_type = "inkling2_loop"; +pub const formats: []const []const u8 = &.{"modelopt-mixed"}; +pub const default_context: i64 = 1_048_576; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = engine.prompt_rows; +pub const window_rows: u32 = engine.window_rows; +pub const explains_open = true; + +pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; +pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; +pub const Options = struct { + context: usize, + drafts: bool, + segments: usize = 1, + slide: bool = false, + vision: ?VisionOptions = null, + precision: ?enum { full } = null, + room: ?Room = null, + drafter: ?[]const u8 = null, + tp: usize = 1, + rank: usize = 0, + master: ?[]const u8 = null, + master_port: u16 = 29551, +}; + +pub const Owned = struct { + gpa: std.mem.Allocator, + admission: loop.Admission, + kernels: engine.Kernels, + stream: cuda.Stream, + weights: @import("loop_weights.zig").Weights, + model: engine.Model, + backend: backend.Backend, +}; + +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32 = 1, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + target: *Owned, +}; + +fn own(ptr: *anyopaque) *Owned { + return @ptrCast(@alignCast(ptr)); +} + +fn release(p: *anyopaque) void { + const o = own(p); + o.stream.synchronize() catch {}; + o.backend.deinit(); + o.stream.deinit(); + o.model.deinit(); + o.kernels.deinit(); + o.weights.deinit(); + const gpa = o.gpa; + gpa.destroy(o); +} + +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const o: *const Owned = @ptrCast(@alignCast(p)); + return o.admission.fits(prompt, max_tokens) and o.backend.admits(prompt, max_tokens); +} + +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + if (kernels != null) return error.Inkling2CapturedKernels; + if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; + if (o.vision != null) return error.Inkling2LoopTextOnly; + if (o.drafter != null) return error.Inkling2DSparkPending; + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(bytes); + var why: config.Why = .{}; + const c = config.parse(gpa, bytes, &why) catch |err| { + std.log.err("Inkling 2 Mini config refused: {s}", .{why.text()}); + return err; + }; + try loop.validateLoad(&c, 1, false); + if (o.context == 0 or o.context > c.text.max_context or o.context > std.math.maxInt(u32)) return error.BadLoopCache; + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer ck.close(); + try ck.skip("model.visual."); // The checkpoint carries Small's tower; text-only Mini never loads or executes it. + var precisions: [config.max_layers]plan_.Precision = undefined; + @memset(&precisions, .nvfp4); + var header_arena = std.heap.ArenaAllocator.init(gpa); + defer header_arena.deinit(); + var merged: core.safetensors.Header = .empty; + for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); + try @import("names.zig").precisions(merged, c.text.layers, &precisions); + const p = try plan_.build(&c.text, &precisions); + var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); + errdefer w.deinit(); + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + ck.release(); + var k = try engine.Kernels.load(ctx); + errdefer k.deinit(); + var stream = try cuda.Stream.init(ctx.d, true); + errdefer stream.deinit(); + var m = try engine.Model.init(gpa, ctx.d, stream, &w, o.context); + errdefer m.deinit(); + var be = try backend.Backend.init(gpa, ctx.d, &m, &k, stream); + errdefer be.deinit(); + const out = try gpa.create(Owned); + errdefer gpa.destroy(out); + out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; + // The value copies above own pointers to their old stack homes; retarget the live model/backend now. + out.model.w = &out.weights; + out.backend.m = &out.model; + out.backend.k = &out.kernels; + return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = out.model.layout.bytes, .ctx = out, .deinit = release, .target = out }; +} + +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + return own(ptr).model.snapshotBytes(at); +} + +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try own(ptr).backend.saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return own(ptr).backend.restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + own(ptr).backend.dropState(@ptrCast(@alignCast(saved))); +} + +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", + error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", + error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", + error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", + error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", + else => null, + }; +} + +test "Mini native registration and refusal wording are explicit" { + try std.testing.expectEqualStrings("inkling2_loop", model_type); + try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); + for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels }) |err| { + try std.testing.expect(explain(null, err) != null); + } +} + +test "the complete prompt snapshot hooks match the store vtable" { + const pc: struct { + bytes: *const fn (*anyopaque, u32) u64, + save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, + restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, + drop: *const fn (*anyopaque, *anyopaque) void, + } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; + try std.testing.expect(@intFromPtr(pc.save) != 0); +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 0a3eb7b848b..f311dc17d35 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -9,6 +9,7 @@ pub const modelopt = @import("modelopt.zig"); pub const loop = @import("loop.zig"); pub const loop_model = @import("loop_model.zig"); pub const loop_math_cuda = @import("loop_math_cuda.zig"); +pub const native = @import("cuda_native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -20,6 +21,7 @@ test { _ = ops; _ = experts; _ = modelopt; + _ = native; _ = loop; _ = loop_model; _ = loop_math_cuda; diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig new file mode 100644 index 00000000000..1053526de10 --- /dev/null +++ b/zig/src/families/inkling2/loop_backend.zig @@ -0,0 +1,297 @@ +//! Inkling 2 Mini lane execution and snapshot adapter. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const engine = @import("loop_engine.zig"); +const ops = @import("ops.zig"); + +const Model = engine.Model; +const Kernels = engine.Kernels; +const prompt_rows = engine.prompt_rows; +const window_rows = engine.window_rows; +const token_ring = 1024; + +const Lane = struct { + len: usize = 0, + fill: ?usize = null, + base: usize = 0, + rows: std.ArrayList(u32) = .empty, + last: u64, + rule: u64, + sampled: bool = false, +}; + +pub const Backend = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + m: *Model, + k: *const Kernels, + s: cuda.Stream, + lane: ?Lane = null, + stream: ?*lanes.Stream = null, + tokens: cuda.DeviceBuffer, + logits16: cuda.DeviceBuffer, + meta: cuda.DeviceBuffer, + slot: [2]cuda.DeviceBuffer, + next: u64 = 0, + + const be = lanes.backend; + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *Model, k: *const Kernels, s: cuda.Stream) !Backend { + const v = m.w.c.text.unpadded_vocab; + var tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + window_rows) * 4); + errdefer tokens.free(); + var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); + errdefer logits16.free(); + var meta = try cuda.DeviceBuffer.alloc(d, 16); + errdefer meta.free(); + var last = try cuda.DeviceBuffer.alloc(d, v * 4); + errdefer last.free(); + var rule = try cuda.DeviceBuffer.alloc(d, @sizeOf(cuda.sample.Rule)); + errdefer rule.free(); + return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .tokens = tokens, .logits16 = logits16, .meta = meta, .slot = .{ last, rule } }; + } + + pub fn deinit(b: *Backend) void { + if (b.lane) |*l| l.rows.deinit(b.gpa); + for (&b.slot) |*x| x.free(); + b.meta.free(); + b.logits16.free(); + b.tokens.free(); + b.* = undefined; + } + + pub fn backend(b: *Backend) be.Backend { + return .{ .ptr = b, .vtable = &vtable }; + } + + pub fn facts(_: *const Backend) lanes.Model { + return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = 1, .streams_exact = true }; + } + + pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { + return b.stream == null and prompt <= b.m.context and max_new <= b.m.context - prompt; + } + + fn self(ptr: *anyopaque) *Backend { + return @ptrCast(@alignCast(ptr)); + } + + fn upload(b: *Backend, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(b.d, dst, bytes, b.s); + } + + fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { + if (b.stream != s) return error.UnknownStream; + return if (b.lane) |*l| l else error.UnknownStream; + } + + fn resumeSaved(b: *Backend, s: *lanes.Stream) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const Model.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { + s.reuse_failed = true; + return 0; + } + b.m.restore(b.s, k) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = k.at; + return k.at; + } + + fn opening(b: *Backend, s: *lanes.Stream) !*Lane { + const prompt = s.prompt(); + if (prompt.len == 0) return error.EmptyPrompt; + if (prompt.len > b.m.context or s.max_new > b.m.context - prompt.len) return error.PastContext; + if (b.stream != null and b.stream != s) return error.NoFreeSlot; + if (b.stream == null) { + b.lane = .{ .last = b.slot[0].ptr, .rule = b.slot[1].ptr }; + b.stream = s; + } + const l = try b.laneOf(s); + l.sampled = false; + if (cuda.sample.ruleFor(s.sampling)) |r| { + try b.upload(l.rule, std.mem.asBytes(&r)); + l.sampled = true; + } + l.len = 0; + try b.m.reset(b.s); + const at = b.resumeSaved(s); + l.len = at; + l.fill = at; + s.fill_at.store(@intCast(at), .monotonic); + return l; + } + + fn chunk(b: *Backend, s: *lanes.Stream, l: *Lane) !bool { + const prompt = s.prompt(); + const at = l.fill.?; + if (s.isCancelled()) return error.Cancelled; + var end = @min(prompt.len, (at / prompt_rows + 1) * prompt_rows); + for (s.reuse.marks) |mark| { + if (mark > at and mark < end) end = mark; + } + const done = end == prompt.len; + try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); + if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); + l.len = end; + l.fill = if (done) null else end; + s.fill_at.store(@intCast(end), .monotonic); + if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) + hook.at(hook.ptr, s, @intCast(end)); + return done; + } + + fn handle(b: *Backend) usize { + const h = b.next; + b.next += 1; + return @intCast(h % token_ring); + } + + fn drawRows(b: *Backend, l: *const Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { + const v = b.m.w.c.text.unpadded_vocab; + if (!l.sampled) return ops.top1(&b.k.glue, b.s, logits, rows, v, v, 0, b.m.s.t + at * 4, b.tokens.ptr + at * 4); + try ops.tobf(&b.k.glue, b.s, logits, rows, v, v, b.logits16.ptr, v, 0, v); + const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; + try b.upload(b.meta.ptr, std.mem.asBytes(&metadata)); + try b.k.draws.draw(b.s, b.logits16.ptr, v, l.rule, b.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); + } + + fn read(ptr: *anyopaque, h: u64) anyerror!u32 { + const b = self(ptr); + if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; + var out: [1]u32 = undefined; + try b.s.synchronize(); + try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); + return out[0]; + } + + const vtable: be.Backend.VTable = .{ + .prefill = prefill, + .prefill_step = prefillStep, + .first = first, + .first_masked = firstMasked, + .queue = queue, + .read = read, + .verify = verify, + .keep = keep, + .draft = draft, + .release = release, + .reports_fill = true, + }; + + fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + const b = self(ptr); + const l = try b.opening(s); + errdefer release(ptr, s); + while (!try b.chunk(s, l)) {} + } + + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const b = self(ptr); + const going = b.stream == s and b.lane != null and b.lane.?.fill != null; + const l = if (going) try b.laneOf(s) else try b.opening(s); + errdefer release(ptr, s); + return b.chunk(s, l); + } + + fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const b = self(ptr); + const l = try b.laneOf(s); + if (position != l.len or l.fill != null) return error.PositionMismatch; + const h = b.next; + try b.drawRows(l, l.last, 1, position, b.handle()); + return h; + } + + fn firstMasked(_: *anyopaque, _: *lanes.Stream, _: u64, _: []const u32) anyerror!u64 { + return error.StructuresUnsupported; + } + + fn feed(b: *Backend, value: be.Feed) !u32 { + return switch (value) { + .value => |v| v, + .handle => |h| read(b, h), + }; + } + + fn queue(ptr: *anyopaque, s: *lanes.Stream, value: be.Feed, position: u64) anyerror!u64 { + const b = self(ptr); + const l = try b.laneOf(s); + const token = try b.feed(value); + if (position != l.len + 1) return error.PositionMismatch; + try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); + l.len += 1; + const h = b.next; + try b.drawRows(l, b.m.s.logits, 1, position, b.handle()); + return h; + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const b = self(ptr); + if (windows.len != 1 or out.len != 1) return error.OneStreamOnly; + const w = windows[0]; + if (w.held != 0) return error.NoHeldDrafts; + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = try b.laneOf(w.stream); + const n = w.rows(); + if (n == 0 or n > window_rows) return error.WindowTooWide; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(b.gpa, w.pending); + try l.rows.appendSlice(b.gpa, w.tokens); + for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; + try b.m.forward(b.k, b.s, l.rows.items, l.base, 0, n, true); + try b.drawRows(l, b.m.s.logits, n, w.positions[0], token_ring); + var got: [window_rows]u32 = undefined; + try b.s.synchronize(); + try b.tokens.download(token_ring * 4, std.mem.sliceAsBytes(got[0..n])); + @memcpy(out[0].sampled[0..n], got[0..n]); + @memcpy(out[0].drafts[0 .. n - 1], l.rows.items[1..n]); + l.len = l.base + n; + } + + fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const b = self(ptr); + if (windows.len != 1 or paths.len != 1) return error.OneStreamOnly; + const l = try b.laneOf(windows[0].stream); + const path = paths[0]; + if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; + for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; + try b.m.rewind(b.k, b.s, path.len); + l.len = l.base + path.len; + } + + fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; + } + + pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { + const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = try b.laneOf(s); + if ((l.fill orelse l.len) != at) return error.NotAtMark; + return b.m.save(b.s, at); + } + + pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { + const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = try b.laneOf(s); + try b.m.restore(b.s, saved); + l.len = saved.at; + } + + pub fn dropState(b: *Backend, saved: *Model.Saved) void { + b.m.drop(b.s, saved); + } + + fn release(ptr: *anyopaque, s: *lanes.Stream) void { + const b = self(ptr); + if (b.stream != s) return; + if (b.lane) |*l| l.rows.deinit(b.gpa); + b.lane = null; + b.stream = null; + } +}; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig new file mode 100644 index 00000000000..0605b92c428 --- /dev/null +++ b/zig/src/families/inkling2/loop_engine.zig @@ -0,0 +1,570 @@ +//! One-rank, text-only Inkling 2 Mini: the complete 48-visit CUDA forward. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const loop = @import("loop.zig"); +const weights_ = @import("loop_weights.zig"); +const ops = @import("ops.zig"); +const attention = @import("kernels.zig"); +const modelopt = @import("modelopt.zig"); +const loop_math = @import("loop_math_cuda.zig"); + +pub const prompt_rows: usize = 2048; +pub const window_rows: usize = 16; + +pub const Kernels = struct { + glue: ops.Kernels, + attn: attention.Kernels, + moe: modelopt.Kernels, + loop: loop_math.Kernels, + sample_mod: cuda.Module, + draws: cuda.sample.Draws, + + pub fn load(ctx: *const cuda.Context) !Kernels { + const d = ctx.d; + var glue = try ops.Kernels.load(d); + errdefer glue.unload(); + var attn = try attention.Kernels.load(d); + errdefer attn.unload(); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + var moe = try modelopt.Kernels.load(d, sms); + errdefer moe.unload(); + var lm = try loop_math.Kernels.load(d); + errdefer lm.unload(); + var sample_mod = try cuda.Module.load(d, cuda.kernels.sample); + errdefer sample_mod.unload(); + return .{ + .glue = glue, + .attn = attn, + .moe = moe, + .loop = lm, + .sample_mod = sample_mod, + .draws = try cuda.sample.Draws.resolve(sample_mod), + }; + } + + pub fn deinit(k: *Kernels) void { + k.sample_mod.unload(); + k.loop.unload(); + k.moe.unload(); + k.attn.unload(); + k.glue.unload(); + k.* = undefined; + } +}; + +const Scratch = struct { + ids: u64, + pos: u64, + seg_of: u64, + segs: u64, + tiles: u64, + blocks: [ops.max_blocks]u64 = @splat(0), + partial_a: u64, + partial_b: u64, + prelude: u64, + bank0: u64, + bank1: u64, + raw: u64, // three FP32 AR/gate rows per token + messages: u64, // four FP32 message rows per token + normalized: u64, // three BF16 rows per token + t: u64, + q_raw: u64, + rel_raw: u64, + sink: u64, + gate: u64, + k_raw: u64, + v_raw: u64, + k_conv: u64, + v_conv: u64, + k_dynamic: u64, + v_dynamic: u64, + q_prepared: u64, + rel_prepared: u64, + rel_table: u64, + part_o: u64, + part_ml: u64, + attn_heads: u64, + attn_out: u64, + route_scores: u64, + route_pick: u64, + route_weights: u64, + moe_out: u64, + moe_scratch: u64, + hidden: u64, + logits: u64, + backup: u64, + hist: u64, + rewind_sites: u64, +}; + +pub const Model = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + w: *const weights_.Weights, + context: usize, + layout: loop.CacheLayout, + cache: cuda.DeviceBuffer, + s: Scratch = undefined, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + fn alloc(m: *Model, bytes: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(m.d, @max(bytes, 256)); + errdefer b.free(); + try m.buffers.append(m.gpa, b); + return b.ptr; + } + + fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(m.d, dst, bytes, s); + } + + fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); + } + + fn zeros(m: *const Model, s: cuda.Stream, ptr: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemsetD8Async(ptr, 0, bytes, s.handle), "cuMemsetD8Async"); + } + + fn layerGeometry(m: *const Model, layer: u32) attention.Layer { + return if (config.isGlobal(layer)) + attention.Layer.global(@intCast(m.context)) + else + attention.Layer.sliding(m.w.c.text.window, @intCast(@min(prompt_rows, m.context))); + } + + fn cacheOf(m: *const Model, visit: u32) attention.Cache { + const slot = m.layout.at(visit); + const base = m.cache.ptr + slot.kv_offset; + return .{ .k = base, .v = base + slot.kv_bytes / 2 }; + } + + fn convOf(m: *const Model, visit: u32, site: usize) u64 { + const c = m.w.c.text; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const h: usize = c.hidden; + const widths = [4]usize{ kv, kv, h, h }; + var at = m.cache.ptr + m.layout.at(visit).conv_offset; + for (0..site) |i| at += 3 * widths[i] * 4; + return at; + } + + fn histOf(m: *const Model, visit: u32, site: usize) u64 { + const c = m.w.c.text; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const h: usize = c.hidden; + const widths = [4]usize{ kv, kv, h, h }; + var at = m.s.hist + visit * window_rows * (2 * kv + 2 * h) * 4; + for (0..site) |i| at += window_rows * widths[i] * 4; + return at; + } + + fn backupOf(m: *const Model, visit: u32, site: usize) usize { + return m.convOf(visit, site) - (m.cache.ptr + m.layout.at(0).conv_offset); + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const weights_.Weights, context: usize) !Model { + const layout = try loop.CacheLayout.init(&w.c.text, &w.p, @intCast(context)); + var m: Model = .{ + .gpa = gpa, + .d = d, + .w = w, + .context = context, + .layout = layout, + .cache = try cuda.DeviceBuffer.alloc(d, layout.bytes), + }; + errdefer m.cache.free(); + errdefer m.deinitBuffers(); + const c = w.c.text; + const h: usize = c.hidden; + const q: usize = @as(usize, c.global.q) * c.global.dim; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const rows = prompt_rows; + const rel_rows = rows * c.global.q * attention.extent; + const local = attention.Layer.sliding(c.window, @intCast(@min(prompt_rows, context))); + const global = attention.Layer.global(@intCast(context)); + const local_slots = attention.slotsFor(local, context); + const global_slots = attention.slotsFor(global, context); + const part_slots = @max(rows * c.local.q * local_slots, rows * c.global.q * global_slots); + const hist_values = @as(usize, w.p.n_visits) * (2 * kv + 2 * h) * window_rows; + m.s = .{ + .ids = try m.alloc(rows * 4), + .pos = try m.alloc(rows * 4), + .seg_of = try m.alloc(rows * 4), + .segs = try m.alloc(@sizeOf(attention.Seg)), + .tiles = try m.alloc(128 * @sizeOf(attention.Tile)), + .partial_a = try m.alloc(rows * h * 2), + .partial_b = try m.alloc(rows * h * 2), + .prelude = try m.alloc(rows * h * 2), + .bank0 = try m.alloc(rows * h * 2), + .bank1 = try m.alloc(rows * h * 2), + .raw = try m.alloc(3 * rows * h * 4), + .messages = try m.alloc(4 * rows * h * 4), + .normalized = try m.alloc(3 * rows * h * 2), + .t = try m.alloc(rows * h * 4), + .q_raw = try m.alloc(rows * q * 2), + .rel_raw = try m.alloc(rows * c.global.q * c.d_rel * 2), + .sink = try m.alloc(rows * c.global.q * 2), + .gate = try m.alloc(rows * q * 2), + .k_raw = try m.alloc(rows * kv * 2), + .v_raw = try m.alloc(rows * kv * 2), + .k_conv = try m.alloc(rows * kv * 2), + .v_conv = try m.alloc(rows * kv * 2), + .k_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), + .v_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), + .q_prepared = try m.alloc(rows * q * 2), + .rel_prepared = try m.alloc(rows * c.global.q * c.d_rel * 2), + .rel_table = try m.alloc(rel_rows * 2), + .part_o = try m.alloc(part_slots * attention.head_dim * 4), + .part_ml = try m.alloc(part_slots * 8), + .attn_heads = try m.alloc(rows * q * 2), + .attn_out = try m.alloc(rows * h * 2), + .route_scores = try m.alloc(rows * c.experts * 4), + .route_pick = try m.alloc(rows * c.experts * 4), + .route_weights = try m.alloc(rows * c.experts * 4), + .moe_out = try m.alloc(rows * h * 2), + .moe_scratch = try m.alloc(try modelopt.scratchBytes(rows, c.topk, h, c.expert_inter)), + .hidden = try m.alloc(rows * h * 2), + .logits = try m.alloc(window_rows * c.unpadded_vocab * 4), + .backup = try m.alloc(layout.bytes - layout.at(0).conv_offset), + .hist = try m.alloc(hist_values * 4), + .rewind_sites = try m.alloc(w.p.n_visits * 4 * @sizeOf(ops.RewindSite)), + }; + for (0..ops.max_blocks) |i| m.s.blocks[i] = try m.alloc(rows * h * 2); + var sites: [config.max_visits * 4]ops.RewindSite = undefined; + for (0..w.p.n_visits) |v| for (0..4) |site| { + const kv_site = site < 2; + sites[v * 4 + site] = .{ + .state = m.convOf(@intCast(v), site), + .hist = @intCast(m.histOf(@intCast(v), site) - m.s.hist), + .backup = @intCast(m.backupOf(@intCast(v), site)), + .c = @intCast(if (kv_site) kv else h), + }; + }; + try m.upload(s, m.s.rewind_sites, std.mem.sliceAsBytes(sites[0 .. w.p.n_visits * 4])); + try m.zeros(s, m.cache.ptr + m.layout.at(0).conv_offset, layout.bytes - m.layout.at(0).conv_offset); + try s.synchronize(); + return m; + } + + fn deinitBuffers(m: *Model) void { + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + } + + pub fn deinit(m: *Model) void { + m.deinitBuffers(); + m.cache.free(); + m.* = undefined; + } + + pub fn reset(m: *const Model, s: cuda.Stream) !void { + try m.zeros(s, m.cache.ptr + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); + } + + pub fn rewind(m: *const Model, k: *const Kernels, s: cuda.Stream, kept: usize) !void { + if (kept > window_rows) return error.WindowTooWide; + try ops.rewind(&k.glue, s, m.s.rewind_sites, m.w.p.n_visits * 4, m.w.c.text.hidden, m.s.backup, m.s.hist, 0, 0, kept); + } + + fn arBlocks(m: *const Model, blocks: []const u64, partial: u64, query: u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) loop_math.ArArgs { + var a: loop_math.ArArgs = .{ + .partial = partial, + .query = query, + .out = out, + .n_blocks = @intCast(blocks.len), + .partial_bf16 = @intFromBool(partial_bf16), + .nq = @intCast(nq), + .rows = @intCast(rows), + .c = @intCast(m.w.c.text.hidden), + .eps = m.w.c.text.eps, + }; + for (blocks, 0..) |b, i| a.blocks[i] = b; + return a; + } + + fn mixArgs(m: *const Model, blocks: []const u64, partial: u64, query: u64, norms: [3]u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) ops.MixArgs { + var a: ops.MixArgs = .{ + .partial = partial, + .query = query, + .out = out, + .n_blocks = @intCast(blocks.len), + .partial_bf16 = @intFromBool(partial_bf16), + .nq = @intCast(nq), + .rows = @intCast(rows), + .c = @intCast(m.w.c.text.hidden), + .eps = m.w.c.text.eps, + }; + for (blocks, 0..) |b, i| a.blocks[i] = b; + a.norm = norms; + return a; + } + + /// One prompt chunk or one decode window. `record` retains every convolution input for exact prefix rollback. + pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, tokens: []const u32, p0: usize, head0: usize, heads: usize, record: bool) !void { + const c = m.w.c.text; + const rows = tokens.len; + const h: usize = c.hidden; + if (rows == 0 or rows > prompt_rows or p0 + rows > m.context or (!record and heads > window_rows) or head0 + heads > rows) + return error.BadLoopRows; + if (record and rows > window_rows) return error.WindowTooWide; + var ids: [prompt_rows]i32 = undefined; + var pos: [prompt_rows]i32 = undefined; + var seg_of: [prompt_rows]i32 = @splat(0); + for (tokens, 0..) |token, i| { + ids[i] = @intCast(token); + pos[i] = @intCast(p0 + i); + } + try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ids[0..rows])); + try m.upload(s, m.s.pos, std.mem.sliceAsBytes(pos[0..rows])); + try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(seg_of[0..rows])); + const seg: attention.Seg = .{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p0), .off = 0 }; + try m.upload(s, m.s.segs, std.mem.asBytes(&seg)); + if (record) try m.copy(s, m.s.backup, m.cache.ptr + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); + + try ops.embed(&k.glue, s, m.s.ids, rows, m.w.embed, m.w.embed_norm, m.s.partial_a, h, c.eps); + var partial = m.s.partial_a; + var next = m.s.partial_b; + var n_blocks: usize = 0; + const lp = c.loop.?; + + for (m.w.p.visits[0..m.w.p.n_visits]) |visit| { + const layer = m.w.p.at(visit.layer); + const lw = &m.w.layers[visit.layer]; + if (visit.pass >= 2 and visit.layer == lp.core_start) { + try m.copy(s, partial, m.s.prelude, rows * h * 2); + n_blocks = 1; // block zero is the embedding; later passes never inherit completed blocks + } + const messages = visit.hasMessages(); + if (messages) { + const core_j = visit.layer - lp.core_start; + try loop_math.messages(&k.loop, s, m.s.bank0, m.s.bank1, m.w.cross_qm + 2 * core_j * h * 4, m.w.cross_kv + 2 * core_j * h * 4, m.s.messages, rows, 1, h, c.eps); + } + const nq: usize = if (layer.kind == .global) 3 else 1; + const query = m.w.attn_queries[visit.layer]; + const blocks = m.s.blocks[0..n_blocks]; + const raw_stride = rows * h * 4; + const norm_stride = rows * h * 2; + if (messages) { + if (nq == 3) { + try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw, 3, true, rows)); + } else { + // A sliding layer stores one query; each gated role gets its own AR result from that query. + for (0..3) |role| try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw + role * raw_stride, 1, true, rows)); + } + for (0..3) |role| { + const ctl = lw.controllers[role]; + try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); + const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; + try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); + } + } else { + try ops.mix(&k.glue, s, m.mixArgs(blocks, partial, query, lw.attn.norms, m.s.normalized, nq, true, rows)); + } + const u_q = m.s.normalized; + const u_k = if (layer.kind == .global or messages) m.s.normalized + norm_stride else u_q; + const u_v = if (layer.kind == .global or messages) m.s.normalized + 2 * norm_stride else u_q; + const q_width: usize = @as(usize, layer.heads.q) * layer.heads.dim; + const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; + try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); + try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); + try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, true); + try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, true); + + const geometry = m.layerGeometry(visit.layer); + const cache = m.cacheOf(visit.cache_slot); + const dynamic = layer.kind == .global; + for (0..2) |kind| { + const input = if (kind == 0) u_k else u_v; + const dyn_out = if (kind == 0) m.s.k_dynamic else m.s.v_dynamic; + if (dynamic) { + try ops.rowdot(&k.glue, s, input, if (kind == 0) lw.attn.k_dynamic else lw.attn.v_dynamic, dyn_out, rows, layer.heads.kv * config.conv_taps, h, false, false); + try loop_math.roundBf16(&k.loop, s, dyn_out, dyn_out, rows * layer.heads.kv * config.conv_taps); + } + try ops.conv(&k.glue, s, .{ + .x = if (kind == 0) m.s.k_raw else m.s.v_raw, + .state = m.convOf(visit.cache_slot, kind), + .w = if (kind == 0) lw.attn.k_conv else lw.attn.v_conv, + .dyn = if (dynamic) dyn_out else 0, + .out = if (kind == 0) m.s.k_conv else m.s.v_conv, + .hist = if (record) m.histOf(visit.cache_slot, kind) else 0, + .x_bf16 = 1, + .heads = @intCast(layer.heads.kv), + .c = @intCast(kv_width), + .rows = @intCast(rows), + .mode = 0, + }, 1); + } + var tiles: [128]attention.Tile = undefined; + const n_tiles = try attention.tiles(&.{seg}, layer.heads.q / layer.heads.kv, &tiles); + try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); + const stride = attention.slotsFor(geometry, m.context); + const part_capacity = prompt_rows * layer.heads.q * stride; + const r: attention.Rows = .{ + .rows = @intCast(rows), + .heads = layer.heads.q, + .kv_heads = layer.heads.kv, + .pos = m.s.pos, + .seg_of = m.s.seg_of, + .segs = m.s.segs, + .tiles = m.s.tiles, + .n_tiles = @intCast(n_tiles), + .last_pos = @intCast(p0 + rows - 1), + }; + const prep: attention.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = @floatFromInt(c.log_floor), .alpha = c.log_alpha, .eps = c.eps }; + try attention.prep(&k.attn, s, r, geometry, prep, .{ m.s.q_raw, m.s.k_conv, m.s.v_conv, m.s.rel_raw }, .{ lw.attn.q_scale, lw.attn.rel_scale }, m.s.q_prepared, m.s.rel_prepared, cache); + try attention.relTable(&k.attn, s, r, m.s.rel_prepared, lw.attn.rel_proj, m.s.rel_table); + try attention.attend(&k.attn, s, r, geometry, stride, part_capacity, m.s.q_prepared, cache, m.s.rel_table, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.attn_heads); + try ops.rowdot(&k.glue, s, m.s.attn_heads, lw.attn.wo, m.s.attn_out, rows, h, q_width, true, false); + + if (layer.boundary) { + try m.copy(s, m.s.blocks[n_blocks], partial, rows * h * 2); + n_blocks += 1; + } + try ops.conv(&k.glue, s, .{ + .x = m.s.attn_out, + .state = m.convOf(visit.cache_slot, 2), + .w = lw.attn_conv, + .base = if (layer.boundary) 0 else partial, + .resid = m.s.t, + .hist = if (record) m.histOf(visit.cache_slot, 2) else 0, + .x_bf16 = 1, + .c = @intCast(h), + .rows = @intCast(rows), + .mode = 1, + }, 1); + + const mlp_query = m.w.mlp_queries[visit.layer]; + const mlp_blocks = m.s.blocks[0..n_blocks]; + if (messages) { + try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); + const ctl = lw.controllers[3]; + try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); + try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); + } else { + try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); + } + try ops.rowdot(&k.glue, s, m.s.normalized, lw.router, m.s.route_scores, rows, c.experts, h, false, true); + try ops.topk(&k.glue, s, m.s.route_scores, lw.router_bias, m.s.route_pick, m.s.route_weights, rows, c.experts, c.topk, c.route_scale); + try modelopt.run(&k.moe, s, lw.experts, .{ .gate = c.gate_cap, .up = c.up_cap }, m.s.normalized, h, m.s.route_pick, m.s.route_weights, rows, c.topk, m.s.moe_out, m.s.moe_scratch); + try ops.conv(&k.glue, s, .{ + .x = m.s.moe_out, + .state = m.convOf(visit.cache_slot, 3), + .w = lw.mlp_conv, + .resid = m.s.t, + .out = next, + .hist = if (record) m.histOf(visit.cache_slot, 3) else 0, + .x_bf16 = 1, + .c = @intCast(h), + .rows = @intCast(rows), + .mode = 2, + }, 1); + std.mem.swap(u64, &partial, &next); + + if (visit.layer + 1 == lp.core_start) try m.copy(s, m.s.prelude, partial, rows * h * 2); + if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) { + try m.copy(s, m.s.bank0, m.s.blocks[n_blocks - 1], rows * h * 2); + try m.copy(s, m.s.bank1, partial, rows * h * 2); + } + } + + if (heads == 0) return; + try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); + try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); + try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); + try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); + } + + pub const Saved = struct { + at: u32, + visits: u32, + passes: u32, + hidden: u32, + buf: cuda.DeviceBuffer, + }; + + /// Compact bytes for all valid K/V rows and every convolution state of all 48 visits. + pub fn snapshotBytes(m: *const Model, at: usize) u64 { + var bytes = m.layout.bytes - m.layout.at(0).conv_offset; + for (0..m.w.p.n_visits) |v| { + const layer = m.w.p.at(m.w.p.visits[v].layer); + const global = layer.kind == .global; + const count = if (global) at else @min(at, m.w.c.text.window - 1); + const row = @as(u64, layer.heads.kv) * layer.heads.dim * 2; + bytes += 2 * count * row; + } + return bytes; + } + + fn copyState(m: *const Model, s: cuda.Stream, saved: *const Saved, out: bool) !void { + const at: usize = saved.at; + var off: usize = 0; + for (0..m.w.p.n_visits) |v| { + const visit = m.w.p.visits[v]; + const layer = m.w.p.at(visit.layer); + const geometry = m.layerGeometry(visit.layer); + const rb = @as(usize, layer.heads.kv) * layer.heads.dim * 2; + const global = layer.kind == .global; + const count = if (global) at else @min(at, m.w.c.text.window - 1); + const first = at - count; + const cache = m.cacheOf(visit.cache_slot); + for ([2]u64{ cache.k, cache.v }) |base| { + var pos = first; + while (pos < at) { + const row = pos % geometry.ring; + const n = @min(at - pos, geometry.ring - row); + const dev = base + row * rb; + const src = if (out) dev else saved.buf.ptr + off; + const dst = if (out) saved.buf.ptr + off else dev; + try m.copy(s, dst, src, n * rb); + off += n * rb; + pos += n; + } + } + } + const conv = m.cache.ptr + m.layout.at(0).conv_offset; + const bytes = m.layout.bytes - m.layout.at(0).conv_offset; + try m.copy(s, if (out) saved.buf.ptr + off else conv, if (out) conv else saved.buf.ptr + off, bytes); + } + + pub fn save(m: *const Model, s: cuda.Stream, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const gpa = m.gpa; + const saved = try gpa.create(Saved); + errdefer gpa.destroy(saved); + const lp = m.w.c.text.loop.?; + saved.* = .{ .at = at, .visits = m.w.p.n_visits, .passes = lp.passes, .hidden = m.w.c.text.hidden, .buf = try cuda.DeviceBuffer.alloc(m.d, @intCast(@max(snapshotBytes(m, at), 256))) }; + errdefer saved.buf.free(); + try m.copyState(s, saved, true); + return saved; + } + + pub fn restore(m: *const Model, s: cuda.Stream, saved: *const Saved) !void { + const lp = m.w.c.text.loop.?; + if (saved.visits != m.w.p.n_visits or saved.passes != lp.passes or saved.hidden != m.w.c.text.hidden) + return error.StateOfAnotherModel; + if (saved.at == 0 or saved.at > m.context or saved.buf.len < snapshotBytes(m, saved.at)) return error.BadLoopSnapshot; + try m.copyState(s, saved, false); + } + + pub fn drop(m: *const Model, s: cuda.Stream, saved: *Saved) void { + s.synchronize() catch {}; + saved.buf.free(); + m.gpa.destroy(saved); + } +}; + +test "pass snapshots and rollback layout cover every visit" { + const config_test = @import("config_test.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), config_test.mini, &why); + var precisions: [24]@import("plan.zig").Precision = @splat(.nvfp4); + const p = try @import("plan.zig").build(&c.text, &precisions); + const layout = try loop.CacheLayout.init(&c.text, &p, 4096); + try std.testing.expectEqual(@as(u32, 48), layout.n); + try std.testing.expect(layout.at(17).kv_offset != layout.at(29).kv_offset); + try std.testing.expectEqual(@as(u64, layout.at(46).conv_offset + layout.at(46).conv_bytes), layout.at(47).conv_offset); +} diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig new file mode 100644 index 00000000000..2dbc56e5c52 --- /dev/null +++ b/zig/src/families/inkling2/loop_weights.zig @@ -0,0 +1,226 @@ +//! Inkling 2 Mini's text checkpoint on one CUDA rank. Every scheduled visit shares these physical layer weights. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const modelopt = @import("modelopt.zig"); + +pub const Controller = struct { + down: u64, + forget: u64, + gain: u64, +}; + +pub const Attention = struct { + wq: u64, + wk: u64, + wv: u64, + wr: u64, + wo: u64, + gate: u64, + sink: u64, + q_scale: u64, + rel_scale: u64, + rel_proj: u64, + k_conv: u64, + v_conv: u64, + k_dynamic: u64 = 0, + v_dynamic: u64 = 0, + /// Sliding layers use entry zero for q, k and v. Global layers use the three separate norms. + norms: [3]u64, +}; + +/// Controller order is q, k, v and MLP, matching loop_math_cuda.messages' message layout. +pub const Layer = struct { + attn: Attention, + attn_conv: u64, + mlp_norm: u64, + mlp_conv: u64, + router: u64, + router_bias: u64, + experts: modelopt.Layer, + controllers: [4]Controller, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + c: config.Config, + p: plan_.Plan, + embed: u64 = 0, + embed_norm: u64 = 0, + norm: u64 = 0, + unembed: u64 = 0, + output_query: u64 = 0, + attn_queries: []u64 = &.{}, + mlp_queries: []u64 = &.{}, + cross_qm: u64 = 0, + cross_kv: u64 = 0, + layers: []Layer = &.{}, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.gpa.free(w.attn_queries); + w.gpa.free(w.mlp_queries); + w.* = undefined; + } +}; + +/// All text tensors occupy one aligned device arena; expert uploads use this same bump allocator. +const Loader = struct { + w: *Weights, + arena: cuda.DeviceBuffer, + used: usize = 0, + + pub fn alloc(l: *Loader, len: usize) !u64 { + const at = std.mem.alignForward(usize, l.used, 256); + const end = try std.math.add(usize, at, len); + if (end > l.arena.len) return error.LoopWeightsOverflow; + l.used = end; + l.w.bytes += len; + return l.arena.ptr + at; + } + + fn put(l: *Loader, bytes: []const u8) !u64 { + const p = try l.alloc(bytes.len); + try l.arena.upload(p - l.arena.ptr, bytes); + return p; + } + + fn tensor(l: *Loader, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: core.safetensors.DType, dims: []const usize) !u64 { + var buf: [256]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return l.put((try ck.expect(name, dtype, dims)).bytes); + } +}; + +fn checkpointBytes(ck: *const core.Checkpoint) !usize { + var total: usize = 0; + for (ck.files.items) |file| for (file.names.keys(), file.names.values()) |name, entry| { + if (!std.mem.startsWith(u8, name, "model.llm.")) continue; + const padded = std.mem.alignForward(usize, entry.end - entry.begin, 256); + total = try std.math.add(usize, total, padded); + }; + return total; +} + +fn controllers(l: *Loader, ck: *core.Checkpoint, c: *const config.Text, i: u32, rank: u32, out: *[4]Controller) !void { + const h: usize = c.hidden; + const names = [4][]const u8{ "attn", "k", "v", "mlp" }; + for (names, out) |role, *g| { + var prefix: [160]u8 = undefined; + const p = try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.controllers.{s}", .{ i, role }); + var down: [224]u8 = undefined; + var forget: [224]u8 = undefined; + var gain: [224]u8 = undefined; + g.* = .{ + .down = try l.put((try ck.expect(try std.fmt.bufPrint(&down, "{s}.down_weight", .{p}), .bf16, &.{ rank, 2 * h })).bytes), + .forget = try l.put((try ck.expect(try std.fmt.bufPrint(&forget, "{s}.forget_weight", .{p}), .bf16, &.{ h, rank })).bytes), + .gain = try l.put((try ck.expect(try std.fmt.bufPrint(&gain, "{s}.gain_weight", .{p}), .bf16, &.{ h, rank })).bytes), + }; + } +} + +/// Load every text tensor, including all four controller triplets and both cross-pass query matrices. +pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, c: *const config.Config, p: plan_.Plan) !Weights { + if (c.text.loop == null) return error.Inkling2LoopRequired; + var formats: [config.max_layers]modelopt.Format = undefined; + for (p.layers[0..c.text.layers], 0..) |layer, k| { + formats[k] = switch (layer.precision) { + .nvfp4 => .nvfp4, + .mxfp8 => .mxfp8, + }; + } + const total = try checkpointBytes(ck); + var arena = try cuda.DeviceBuffer.alloc(d, @max(total, 256)); + var w: Weights = .{ .gpa = gpa, .c = c.*, .p = p }; + errdefer w.deinit(); + w.buffers.append(gpa, arena) catch |err| { + arena.free(); + return err; + }; + w.layers = try gpa.alloc(Layer, c.text.layers); + w.attn_queries = try gpa.alloc(u64, c.text.layers); + w.mlp_queries = try gpa.alloc(u64, c.text.layers); + var l: Loader = .{ .w = &w, .arena = arena }; + const h: usize = c.text.hidden; + w.embed = try l.tensor(ck, "model.llm.embed.weight", .{}, .bf16, &.{ c.text.vocab, h }); + w.embed_norm = try l.tensor(ck, "model.llm.embed_norm.weight", .{}, .bf16, &.{h}); + w.norm = try l.tensor(ck, "model.llm.norm.weight", .{}, .bf16, &.{h}); + w.unembed = try l.tensor(ck, "model.llm.unembed.weight", .{}, .bf16, &.{ c.text.vocab, h }); + w.output_query = try l.tensor(ck, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); + w.cross_qm = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); + w.cross_kv = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); + + for (w.layers, 0..) |*layer, k| { + const i: u32 = @intCast(k); + const L = .{i}; + const hd = c.text.heads(i); + const q: usize = @as(usize, hd.q) * hd.dim; + const kv: usize = @as(usize, hd.kv) * hd.dim; + w.mlp_queries[k] = try l.tensor(ck, "model.llm.attn_res.mlp_queries.{d}", L, .f32, &.{h}); + if (i == 0) { + w.attn_queries[k] = 0; + } else if (config.isGlobal(i)) { + w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{ 3, h }); + } else { + w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{h}); + } + const A = struct { + fn put(loader: *Loader, checkpoint: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dims: []const usize) !u64 { + return loader.tensor(checkpoint, fmt, args, .bf16, dims); + } + }; + layer.attn = .{ + .wq = try A.put(&l, ck, "model.llm.layers.{d}.attn.wq_du.weight", L, &.{ q, h }), + .wk = try A.put(&l, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L, &.{ kv, h }), + .wv = try A.put(&l, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L, &.{ kv, h }), + .wr = try A.put(&l, ck, "model.llm.layers.{d}.attn.wr_du.weight", L, &.{ @as(usize, hd.q) * c.text.d_rel, h }), + .wo = try A.put(&l, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L, &.{ h, q }), + .gate = try A.put(&l, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L, &.{ q, h }), + .sink = try A.put(&l, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L, &.{ hd.q, h }), + .q_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L, &.{ hd.q, hd.dim }), + .rel_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L, &.{ hd.q, c.text.d_rel }), + .rel_proj = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L, &.{ c.text.d_rel, c.text.extent(i) }), + .k_conv = undefined, + .v_conv = undefined, + .norms = undefined, + }; + inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { + const conv = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) + else + try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight", L, &.{ kv, 1, config.conv_taps }); + if (j == 0) layer.attn.k_conv = conv else layer.attn.v_conv = conv; + if (config.isGlobal(i)) { + const dyn = try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight_proj", L, &.{ @as(usize, hd.kv) * config.conv_taps, h }); + if (j == 0) layer.attn.k_dynamic = dyn else layer.attn.v_dynamic = dyn; + } + const norm = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) + else + try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}); + layer.attn.norms[j + 1] = norm; + } + layer.attn.norms[0] = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}.q_input_norm.weight", L, &.{h}) + else + layer.attn.norms[1]; + layer.attn_conv = try A.put(&l, ck, "model.llm.layers.{d}.attn_sconv.weight", L, &.{ h, 1, config.conv_taps }); + layer.mlp_norm = try A.put(&l, ck, "model.llm.layers.{d}.mlp_norm.weight", L, &.{h}); + layer.mlp_conv = try A.put(&l, ck, "model.llm.layers.{d}.mlp_sconv.weight", L, &.{ h, 1, config.conv_taps }); + layer.router = try A.put(&l, ck, "model.llm.layers.{d}.mlp.gate.weight", L, &.{ c.text.experts, h }); + layer.router_bias = try l.tensor(ck, "model.llm.layers.{d}.mlp.gate.bias", L, .f32, &.{c.text.experts}); + var prefix: [96]u8 = undefined; + layer.experts = try modelopt.load(&l, ck, try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.mlp.experts.", L), formats[k], c.text.experts, h, c.text.expert_inter); + @memset(&layer.controllers, .{ .down = 0, .forget = 0, .gain = 0 }); + const lp = c.text.loop.?; + if (i >= lp.core_start and i < lp.core_end) try controllers(&l, ck, &c.text, i, lp.gate_rank, &layer.controllers); + } + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + return w; +} diff --git a/zig/src/families/inkling2/names.zig b/zig/src/families/inkling2/names.zig index e4451ce7bf2..79890b60510 100644 --- a/zig/src/families/inkling2/names.zig +++ b/zig/src/families/inkling2/names.zig @@ -1,6 +1,6 @@ //! Inkling 2 weight maps: each tensor the config implies, with dtype and shape, checked against headers. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const config = @import("config.zig"); const plan = @import("plan.zig"); diff --git a/zig/src/families/inkling2/names_test.zig b/zig/src/families/inkling2/names_test.zig index 0b9bcb0124b..b194b435d28 100644 --- a/zig/src/families/inkling2/names_test.zig +++ b/zig/src/families/inkling2/names_test.zig @@ -3,7 +3,7 @@ const std = @import("std"); const config = @import("config.zig"); const config_test = @import("config_test.zig"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const names = @import("names.zig"); const plan = @import("plan.zig"); diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index db2d88035e8..fd40a97d523 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -12,9 +12,10 @@ const gemma4 = @import("gemma4_cuda"); const spark25 = @import("spark25"); const dory = @import("dory"); const qwen3 = @import("qwen3_cuda"); +const inkling2 = @import("inkling2"); /// CUDA families provide metadata, open their lane backend and explain their refusals. -pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native }; +pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native, inkling2.native }; pub const families: []const api.Family = blk: { var out: [registry.len + 5]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats, .decision_formats = if (@hasDecl(F, "decision_formats")) F.decision_formats else &.{} }; @@ -30,8 +31,8 @@ pub const families: []const api.Family = blk: { test "every registered family and d1's decision engine are listed for capabilities" { try std.testing.expectEqual(@as(usize, registry.len + 5), families.len); try std.testing.expectEqualStrings("nemotron_h", families[0].model_type); - try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 1].model_type); - try std.testing.expectEqualStrings("lfm2_vl", families[registry.len].model_type); + try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 2].model_type); + try std.testing.expectEqualStrings("inkling2_loop", families[registry.len - 1].model_type); try std.testing.expectEqualStrings("qwen4", families[registry.len + 2].model_type); try std.testing.expectEqualStrings("qwen4_text", families[registry.len + 3].model_type); try std.testing.expectEqualStrings("qwen3", families[registry.len + 4].model_type); From c40710cc6f5cb557c490cd2adc4be7e6833c2354 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:36:59 +0000 Subject: [PATCH 14/84] lanes: make full lone-window commits opt-in --- zig/src/core/lanes/backend.zig | 2 ++ zig/src/core/lanes/drafted.zig | 2 +- zig/src/core/lanes/drafted_role_test.zig | 2 ++ zig/src/core/lanes/engine.zig | 2 +- zig/src/core/lanes/fake.zig | 2 ++ zig/src/core/lanes/recorder.zig | 2 +- zig/src/core/lanes/recorder_test.zig | 4 +++- zig/src/core/lanes/rollback_test.zig | 17 +++++++++++++++++ 8 files changed, 29 insertions(+), 4 deletions(-) diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index 2806a0a65c5..180944cbba3 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -87,6 +87,8 @@ pub const Backend = struct { first_before_draft: bool = false, /// A single-slot target lets its asynchronous keep progress between host steps before drafting again. defer_lone_draft: bool = false, + /// Commit a fully accepted lone chain; Inkling 2 Mini needs this transaction commit. + keep_full_lone: bool = false, /// Every draw (first, queue and verify rows) takes `Stream.penalties` from the reply's tokens; wrappers copy it. penalties: bool = false, /// Prompt fill gives the same tokens at any chunk cut, so --decode-share may cap its chunk rows; wrappers copy it. diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index 330f1125566..c4480a85647 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -72,7 +72,7 @@ pub const Drafted = struct { }; pub fn backend(x: *Drafted) be.Backend { const planned = if (x.drafter.proposal_head) |service| service.mode != .legacy and x.drafter.vtable.hold_planned != null and x.drafter.vtable.clear_proposals != null else false; - return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; + return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .keep_full_lone = x.target.keep_full_lone, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; } const cancellable: [4]be.Backend.VTable = blk: { diff --git a/zig/src/core/lanes/drafted_role_test.zig b/zig/src/core/lanes/drafted_role_test.zig index 7c28f3ddab6..ff096e26f30 100644 --- a/zig/src/core/lanes/drafted_role_test.zig +++ b/zig/src/core/lanes/drafted_role_test.zig @@ -38,9 +38,11 @@ test "the drafter wrapper sees the committed callback before its first hold" { defer head.deinit(); var backend = target.backend(); backend.first_before_draft = true; + backend.keep_full_lone = true; var wrapped = try Drafted.init(gpa, backend, head.drafter()); defer wrapped.deinit(); try std.testing.expect(wrapped.backend().first_before_draft); + try std.testing.expect(wrapped.backend().keep_full_lone); var cfg = try Config.init(gpa, wrapped.facts(base()), 16, 15); defer cfg.deinit(gpa); var clock: fake.FixedClock = .{}; diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index 285fd9c9c27..a92eb0f659f 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -221,7 +221,7 @@ pub const Engine = struct { const tokens = try win.tokens(e, windows[0], out[0]); const parents = try win.rowParents(e, windows[0]); const o = try e.conclude(s, plan, out[0].sampled, out[0].rows, tokens, parents, windows[0].positions); - if (o.path.len < rows or plan.parents != null) try e.backend.keep(&windows, &.{o.path}); + if (o.path.len < rows or plan.parents != null or e.backend.keep_full_lone) try e.backend.keep(&windows, &.{o.path}); const held_levels = s.held_levels; const timed_copy = e.cfg.family_mtp and s.drafts and @import("lone_copy.zig").records(e, s, plan.kind); const verified: ?f64 = if (timed_copy) e.clock.elapsedMs(.cost) else null; // its read moves before the head drafts diff --git a/zig/src/core/lanes/fake.zig b/zig/src/core/lanes/fake.zig index 4f68632ce70..0c807d5cd91 100644 --- a/zig/src/core/lanes/fake.zig +++ b/zig/src/core/lanes/fake.zig @@ -92,6 +92,7 @@ pub const Fake = struct { image_rows: usize = 0, // image rows fed (`image_words`): the rows a tower had to make gpu_charge: ?f64 = null, // each verify and step charges its streams this many GPU seconds, as a timed backend does head_accepts: ?usize = null, // head drafts a round right before one wrong (null: one in five wrong) + keep_calls: usize = 0, // backend keep calls, including fully accepted lone windows when opted in pub fn deinit(x: *Fake) void { var it = x.lanes.valueIterator(); @@ -479,6 +480,7 @@ pub const Fake = struct { fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { const x = self(ptr); + x.keep_calls += 1; for (windows, paths) |w, path| { const l = x.lane(w.stream); l.history.shrinkRetainingCapacity(l.base); diff --git a/zig/src/core/lanes/recorder.zig b/zig/src/core/lanes/recorder.zig index a21b8bc252f..f4e4b78c263 100644 --- a/zig/src/core/lanes/recorder.zig +++ b/zig/src/core/lanes/recorder.zig @@ -239,7 +239,7 @@ pub const Recorded = struct { pub fn backend(x: *Recorded) be.Backend { const v = x.inner.vtable; x.table = .{ .prefill = prefill, .prefill_step = if (v.prefill_step != null) prefillStep else null, .cancel_prefill = if (v.cancel_prefill != null) cancelPrefill else null, .prefill_many = if (v.prefill_many != null) prefillMany else null, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .draft_capacity = if (v.draft_capacity != null) draftCapacity else null, .proposal_draft = if (v.proposal_draft != null) plannedDraft else null, .clear_proposals = if (v.clear_proposals != null) clearProposals else null, .unspeculate = if (v.unspeculate != null) unspeculate else null, .probabilities = if (v.probabilities != null) probabilities else null, .tree = if (v.tree != null) tree else null, .alternatives = if (v.alternatives != null) alternatives else null, .prepare_features = if (v.prepare_features != null) prepareFeatures else null, .features = features, .first_row = if (v.first_row != null) firstRow else null, .first_masked = if (v.first_masked != null) firstMasked else null, .score = if (v.score != null) score else null, .held = if (v.held != null) held else null, .prompt_rows = v.prompt_rows, .release = release }; - return .{ .proposal_head = x.inner.proposal_head, .ptr = x, .round_observer = x.inner.round_observer, .vtable = &x.table, .first_before_draft = x.inner.first_before_draft, .penalties = x.inner.penalties, .chunk_invariant = x.inner.chunk_invariant }; + return .{ .proposal_head = x.inner.proposal_head, .ptr = x, .round_observer = x.inner.round_observer, .vtable = &x.table, .first_before_draft = x.inner.first_before_draft, .keep_full_lone = x.inner.keep_full_lone, .penalties = x.inner.penalties, .chunk_invariant = x.inner.chunk_invariant }; } fn of(p: *anyopaque) *Recorded { diff --git a/zig/src/core/lanes/recorder_test.zig b/zig/src/core/lanes/recorder_test.zig index e0d48b2640e..43bb3b004f2 100644 --- a/zig/src/core/lanes/recorder_test.zig +++ b/zig/src/core/lanes/recorder_test.zig @@ -270,7 +270,7 @@ test "a target that gives no rows cannot be recorded" { try std.testing.expectError(error.NoFeatures, rec.Recorded.init(.{ .ptr = &target, .vtable = &table }, &recorder)); } -test "recorded backend preserves both values of first_before_draft, penalties and chunk invariance" { +test "recorded backend preserves first-before-draft, penalties, chunk invariance and lone keep" { var target: fake.Fake = .{ .gpa = gpa }; defer target.deinit(); var tmp = std.testing.tmpDir(.{}); @@ -283,10 +283,12 @@ test "recorded backend preserves both values of first_before_draft, penalties an inner.first_before_draft = enabled; inner.penalties = enabled; inner.chunk_invariant = enabled; + inner.keep_full_lone = enabled; var recorded = try rec.Recorded.init(inner, &recorder); try std.testing.expectEqual(enabled, recorded.backend().first_before_draft); try std.testing.expectEqual(enabled, recorded.backend().penalties); try std.testing.expectEqual(enabled, recorded.backend().chunk_invariant); + try std.testing.expectEqual(enabled, recorded.backend().keep_full_lone); } } diff --git a/zig/src/core/lanes/rollback_test.zig b/zig/src/core/lanes/rollback_test.zig index 683d0c40a9f..f4763e224d1 100644 --- a/zig/src/core/lanes/rollback_test.zig +++ b/zig/src/core/lanes/rollback_test.zig @@ -157,6 +157,23 @@ test "rollback: heads landing no draft, some or all commit the one-token decode, }; } +test "rollback: fully accepted lone keep is opt-in and preserves main's default call count" { + for ([_]bool{ false, true }) |enabled| { + const r = try Rig.create(every, 0); + defer r.destroy(); + r.engine.backend.keep_full_lone = enabled; + const s = try r.open(0, .{ .prompt = &p1, .max_new = 24 }); + try r.engine.addStream(s); + _ = try r.finish(); + try expectFresh(.{ .prompt = &p1, .max_new = 24 }, s); + if (enabled) { + try expect(r.target.keep_calls > 0); + } else { + try std.testing.expectEqual(@as(usize, 0), r.target.keep_calls); + } + } +} + /// Steps of the uncancelled run of `reqs`, which bound where a cancel can land. fn stepsOf(accepts: ?usize, reqs: []const Req) !usize { const r = try Rig.create(accepts, 0); From ece3a40b18b8c1d0e8fa342bfbd484332767e877 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:37:10 +0000 Subject: [PATCH 15/84] inkling2: add Mini Metal kernels and contracts --- zig/build/kernel_contract.zig | 29 +- zig/build/metal_targets.zig | 17 + zig/kernels/metal/inkling2/attention.metal | 170 +++++ .../metal/inkling2/attention_sources.zig | 5 + zig/kernels/metal/inkling2/dspark.metal | 239 +++++++ zig/kernels/metal/inkling2/dspark_sources.zig | 3 + zig/kernels/metal/inkling2/experts.metal | 171 +++++ .../metal/inkling2/experts_sources.zig | 2 + zig/kernels/metal/inkling2/glue.metal | 225 +++++++ zig/kernels/metal/inkling2/glue_sources.zig | 2 + zig/kernels/metal/inkling2/loop.metal | 136 ++++ zig/kernels/metal/inkling2/loop_sources.zig | 2 + .../metal/inkling2/prompt_attention.metal | 145 +++++ zig/kernels/metal/inkling2/runtime.metal | 28 + .../metal/inkling2/runtime_sources.zig | 2 + zig/kernels/metal/inkling2_sources.zig | 10 + zig/kernels/metal/sources.zig | 3 + zig/src/core/contract/fakes.zig | 19 + zig/src/core/contract/gates.zig | 14 + .../inkling2_attention_metal_records.zig | 15 + .../inkling2_dspark_metal_records.zig | 15 + .../inkling2_experts_metal_records.zig | 22 + .../contract/inkling2_glue_metal_records.zig | 13 + .../contract/inkling2_loop_metal_records.zig | 6 + .../inkling2_runtime_metal_records.zig | 10 + zig/src/core/contract/registry_joins.zig | 12 + zig/src/families/inkling2/metal/attention.zig | 92 +++ .../inkling2/metal/attention_plan.zig | 98 +++ .../inkling2/metal/attention_test.zig | 63 ++ .../families/inkling2/metal/dspark_fold.zig | 103 +++ .../inkling2/metal/dspark_kernels.zig | 224 +++++++ .../inkling2/metal/dspark_kernels_test.zig | 154 +++++ zig/src/families/inkling2/metal/experts.zig | 124 ++++ .../families/inkling2/metal/experts_plan.zig | 102 +++ .../families/inkling2/metal/experts_test.zig | 144 +++++ zig/src/families/inkling2/metal/glue.zig | 146 +++++ zig/src/families/inkling2/metal/glue_plan.zig | 250 ++++++++ zig/src/families/inkling2/metal/glue_test.zig | 199 ++++++ zig/src/families/inkling2/metal/loop.zig | 55 ++ zig/src/families/inkling2/metal/loop_plan.zig | 166 +++++ zig/src/families/inkling2/metal/loop_test.zig | 208 ++++++ zig/src/families/inkling2/metal/metal.zig | 7 + zig/src/families/inkling2/metal/ref.zig | 4 + .../inkling2/metal/runtime_kernels_test.zig | 116 ++++ .../families/inkling2/metal/runtime_plan.zig | 105 ++++ .../contract/metal_inkling2_attention.zig | 565 +++++++++++++++++ .../metal_inkling2_attention_controls.zig | 157 +++++ zig/tests/contract/metal_inkling2_dspark.zig | 590 ++++++++++++++++++ .../metal_inkling2_dspark_controls.zig | 56 ++ zig/tests/contract/metal_inkling2_experts.zig | 409 ++++++++++++ .../metal_inkling2_experts_controls.zig | 83 +++ zig/tests/contract/metal_inkling2_glue.zig | 376 +++++++++++ .../contract/metal_inkling2_glue_controls.zig | 65 ++ zig/tests/contract/metal_inkling2_loop.zig | 327 ++++++++++ .../contract/metal_inkling2_loop_controls.zig | 53 ++ zig/tests/contract/metal_inkling2_main.zig | 41 ++ zig/tests/contract/metal_inkling2_runtime.zig | 290 +++++++++ .../metal_inkling2_runtime_controls.zig | 65 ++ zig/tests/contract/metal_limits.zig | 21 +- zig/tests/contract/metal_main.zig | 2 + zig/tests/contract/metal_mapping_test.zig | 10 + 61 files changed, 6782 insertions(+), 3 deletions(-) create mode 100644 zig/kernels/metal/inkling2/attention.metal create mode 100644 zig/kernels/metal/inkling2/attention_sources.zig create mode 100644 zig/kernels/metal/inkling2/dspark.metal create mode 100644 zig/kernels/metal/inkling2/dspark_sources.zig create mode 100644 zig/kernels/metal/inkling2/experts.metal create mode 100644 zig/kernels/metal/inkling2/experts_sources.zig create mode 100644 zig/kernels/metal/inkling2/glue.metal create mode 100644 zig/kernels/metal/inkling2/glue_sources.zig create mode 100644 zig/kernels/metal/inkling2/loop.metal create mode 100644 zig/kernels/metal/inkling2/loop_sources.zig create mode 100644 zig/kernels/metal/inkling2/prompt_attention.metal create mode 100644 zig/kernels/metal/inkling2/runtime.metal create mode 100644 zig/kernels/metal/inkling2/runtime_sources.zig create mode 100644 zig/kernels/metal/inkling2_sources.zig create mode 100644 zig/src/core/contract/inkling2_attention_metal_records.zig create mode 100644 zig/src/core/contract/inkling2_dspark_metal_records.zig create mode 100644 zig/src/core/contract/inkling2_experts_metal_records.zig create mode 100644 zig/src/core/contract/inkling2_glue_metal_records.zig create mode 100644 zig/src/core/contract/inkling2_loop_metal_records.zig create mode 100644 zig/src/core/contract/inkling2_runtime_metal_records.zig create mode 100644 zig/src/families/inkling2/metal/attention.zig create mode 100644 zig/src/families/inkling2/metal/attention_plan.zig create mode 100644 zig/src/families/inkling2/metal/attention_test.zig create mode 100644 zig/src/families/inkling2/metal/dspark_fold.zig create mode 100644 zig/src/families/inkling2/metal/dspark_kernels.zig create mode 100644 zig/src/families/inkling2/metal/dspark_kernels_test.zig create mode 100644 zig/src/families/inkling2/metal/experts.zig create mode 100644 zig/src/families/inkling2/metal/experts_plan.zig create mode 100644 zig/src/families/inkling2/metal/experts_test.zig create mode 100644 zig/src/families/inkling2/metal/glue.zig create mode 100644 zig/src/families/inkling2/metal/glue_plan.zig create mode 100644 zig/src/families/inkling2/metal/glue_test.zig create mode 100644 zig/src/families/inkling2/metal/loop.zig create mode 100644 zig/src/families/inkling2/metal/loop_plan.zig create mode 100644 zig/src/families/inkling2/metal/loop_test.zig create mode 100644 zig/src/families/inkling2/metal/metal.zig create mode 100644 zig/src/families/inkling2/metal/ref.zig create mode 100644 zig/src/families/inkling2/metal/runtime_kernels_test.zig create mode 100644 zig/src/families/inkling2/metal/runtime_plan.zig create mode 100644 zig/tests/contract/metal_inkling2_attention.zig create mode 100644 zig/tests/contract/metal_inkling2_attention_controls.zig create mode 100644 zig/tests/contract/metal_inkling2_dspark.zig create mode 100644 zig/tests/contract/metal_inkling2_dspark_controls.zig create mode 100644 zig/tests/contract/metal_inkling2_experts.zig create mode 100644 zig/tests/contract/metal_inkling2_experts_controls.zig create mode 100644 zig/tests/contract/metal_inkling2_glue.zig create mode 100644 zig/tests/contract/metal_inkling2_glue_controls.zig create mode 100644 zig/tests/contract/metal_inkling2_loop.zig create mode 100644 zig/tests/contract/metal_inkling2_loop_controls.zig create mode 100644 zig/tests/contract/metal_inkling2_main.zig create mode 100644 zig/tests/contract/metal_inkling2_runtime.zig create mode 100644 zig/tests/contract/metal_inkling2_runtime_controls.zig diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index e33fe5fc528..f2b06256aec 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -26,6 +26,20 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { }) })); b.step("test-qwen27-paged-contract-host", "Paged prompt source controls, shuffled pages and boundary witnesses without a device").dependOn(&q27_pages.step); step.dependOn(&q27_pages.step); + const inkling_controls = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/contract/metal_inkling2_controls_host.zig"), + .target = b.graph.host, + .optimize = .debug, + .imports = &.{ + .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, + .{ .name = "inkling2_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig") }) }, + .{ .name = "inkling2_glue_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig") }) }, + .{ .name = "inkling2_loop_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig") }) }, + .{ .name = "inkling2_runtime_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/runtime_plan.zig") }) }, + }, + }) })); + b.step("test-inkling2-controls-host", "Inkling 2 Mini source controls plant one fault without a Metal compiler").dependOn(&inkling_controls.step); + step.dependOn(&inkling_controls.step); const mapping_stub = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_mapping_host.zig") }); const llama_controls = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_llama_controls.zig"), @@ -55,19 +69,23 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { .{ .name = "metal", .module = mapping_stub }, .{ .name = "kernel_sources", .module = mapping_stub }, } }); - const mapping = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + const mapping_root = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_mapping_test.zig"), .target = b.graph.host, .optimize = .debug, .imports = &.{ .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, + .{ .name = "inkling2_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig") }) }, .{ .name = "metal", .module = mapping_stub }, .{ .name = "tensorfold", .module = mapping_tf }, .{ .name = "kernel_sources", .module = mapping_stub }, }, - }) })); + }); + const mapping = b.addRunArtifact(b.addTest(.{ .root_module = mapping_root })); mapping.has_side_effects = true; b.step("test-metal-launch-map-host", "Every registered Metal launch maps without a device or shader compiler").dependOn(&mapping.step); + const dspark_mapping = b.addRunArtifact(b.addTest(.{ .root_module = mapping_root, .filters = &.{"Metal launch map: every DSpark"} })); + b.step("test-inkling2-launch-map-host", "Every Inkling DSpark launch resolves without other families' device checks").dependOn(&dspark_mapping.step); step.dependOn(&mapping.step); const precision = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/core/attention_precision.zig"), @@ -131,6 +149,9 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { @import("rotary_sweep.zig").steps(b, target, metal_mod); @import("ling_forward.zig").steps(b, target, optimize, metal_mod, sources, kimi_metallib); + const inkling2_metal = engine.import_table.get("inkling2_metal").?; + const inkling2_glue_plan = engine.import_table.get("inkling2_glue_plan").?; + const inkling2_loop_plan = engine.import_table.get("inkling2_loop_plan").?; const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), .target = target, @@ -145,6 +166,10 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, .{ .name = "ling_route", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/route.zig") }) }, .{ .name = "masked_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/masked_value_sources.zig"), .imports = &.{.{ .name = "kernel_sources", .module = sources }} }) }, + .{ .name = "inkling2_metal", .module = inkling2_metal }, + .{ .name = "inkling2_glue_plan", .module = inkling2_glue_plan }, + .{ .name = "inkling2_loop_plan", .module = inkling2_loop_plan }, + .{ .name = "inkling2_runtime_plan", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/runtime_plan.zig") }) }, }, }) }); const install = b.addInstallArtifact(exe, .{}); diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index cf1e99ed6c4..5846188fbaa 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -99,6 +99,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s // The engines registry: the families this platform's binaries serve; the CLI reads it for models/info/pull. const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = mods.lanes }} }); + mods.engine.addImport("engine_api", api); const engines = b.createModule(.{ .root_source_file = b.path("zig/src/native/metal.zig"), .target = target, @@ -107,6 +108,9 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = mods.engine } }, }); engines.addImport("living", mods.living); + engines.addImport("kernel_sources", mods.sources); + inline for ([_][]const u8{ "inkling2_metal", "inkling2_metal_ref", "inkling2_glue_plan", "inkling2_loop_plan" }) |name| + engines.addImport(name, mods.engine.import_table.get(name).?); const drama3_lib = drama3_build.metallib(b, metal_std); b.getInstallStep().dependOn(&b.addInstallFile(drama3_lib, "lib/drama3.metallib").step); const drama3_embed = if (shaders) drama3_lib else no_shaders; @@ -442,6 +446,11 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); fabric.addImport("verbs", @import("tp.zig").verbsModule(b, target, optimize)); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); + const inkling2_metal = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize }); + const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); + inkling2_metal_ref.addImport("metal", metal); + const inkling2_glue_plan = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig"), .target = target, .optimize = optimize }); + const inkling2_loop_plan = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig"), .target = target, .optimize = optimize }); // Living Weights' family-neutral learner, which Nemotron's lessons and the server's view of them share const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true }); const engine = b.createModule(.{ @@ -451,6 +460,10 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living } }, }); + engine.addImport("inkling2_metal", inkling2_metal); + engine.addImport("inkling2_metal_ref", inkling2_metal_ref); + engine.addImport("inkling2_glue_plan", inkling2_glue_plan); + engine.addImport("inkling2_loop_plan", inkling2_loop_plan); engine.addImport("engram_hash_core", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize })); return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; } @@ -465,8 +478,12 @@ pub fn distMetalServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_id m.metal.addLibraryPath(b.graph.cwdRelativePath(b.pathJoin(&.{ sdk, "usr/lib" }))); m.metal.addSystemIncludePath(b.graph.cwdRelativePath(b.pathJoin(&.{ sdk, "usr/include" }))); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = .fast, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = m.lanes }} }); + m.engine.addImport("engine_api", api); const engines = b.createModule(.{ .root_source_file = b.path("zig/src/native/metal.zig"), .target = target, .optimize = .fast, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = m.metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = m.engine } } }); engines.addImport("living", m.living); + engines.addImport("kernel_sources", m.sources); + inline for ([_][]const u8{ "inkling2_metal", "inkling2_metal_ref", "inkling2_glue_plan", "inkling2_loop_plan" }) |name| + engines.addImport(name, m.engine.import_table.get(name).?); drama3_build.addNative(b, target, .fast, m.metal, engines, drama3_build.metallib(b, mlxMetalStd(b))); engines.addImport("kimi_k3", kimiModule(b, target, .fast, m.metal, m.engine, m.lanes)); engines.addImport("kimi_metallib", embedded(b, kimiMetallib(b, &flags), "kimi.metallib")); diff --git a/zig/kernels/metal/inkling2/attention.metal b/zig/kernels/metal/inkling2/attention.metal new file mode 100644 index 00000000000..cc4aa7a79f7 --- /dev/null +++ b/zig/kernels/metal/inkling2/attention.metal @@ -0,0 +1,170 @@ +//! Inkling 2 Mini's scalar attention preparation, chunk decode and ordered sink/gate merge. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, REL = 16, EXTENT = 1024; +constant constexpr float LOG2E = 1.4426950408889634f; + +struct InkSeg { + int row0, n, p0, pad; + long off; +}; +struct InkPrepArgs { + uint heads, kv_heads, ring, global; + float qk_clip, rel_clip, floor_pos, alpha, eps; +}; +struct InkAttnArgs { + uint heads, kv_heads, ring, window, chunk, c0, chunks; + float scale; +}; +struct InkMergeArgs { + uint heads, window, chunk, c0, chunks, subs; +}; + +inline float ink_warp_sum(float v) { + for (uint o = 16; o; o >>= 1) v += simd_shuffle_xor(v, ushort(o)); + return v; +} +inline float ink_clip_factor(float ss, float threshold) { + return fmin(threshold / (precise::sqrt(ss) + 1e-6f), 1.0f); +} + +// One 32-thread group handles a row and head; independent q/k/v and relative rows keep their first BF16 rounding. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_prep(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], + const device bfloat* v_raw [[buffer(2)]], const device bfloat* rel_raw [[buffer(3)]], + const device bfloat* q_scale [[buffer(4)]], const device bfloat* rel_scale [[buffer(5)]], + const device int* rpos [[buffer(6)]], const device int* rseg [[buffer(7)]], + const device InkSeg* segs [[buffer(8)]], device bfloat* q_out [[buffer(9)]], + device bfloat* rel_out [[buffer(10)]], device bfloat* kc [[buffer(11)]], device bfloat* vc [[buffer(12)]], + constant InkPrepArgs& a [[buffer(13)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + const uint row = tg.x, unit = tg.y, pos = uint(rpos[row]); + const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f; + float x[4]; + if (unit < a.heads) { + const size_t rh = size_t(row) * a.heads + unit; + for (uint i = 0; i < 4; ++i) x[i] = float(q_raw[rh * D + lane * 4 + i]) * float(q_scale[unit * D + lane * 4 + i]); + float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + const float f = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + for (uint i = 0; i < 4; ++i) { + x[i] *= f; + const bfloat once = bfloat(x[i]); + q_out[rh * D + lane * 4 + i] = a.global ? bfloat(float(once) * tau) : once; + } + const float r = lane < REL ? float(rel_raw[rh * REL + lane]) * float(rel_scale[unit * REL + lane]) : 0.0f; + const float rf = ink_clip_factor(ink_warp_sum(r * r), a.rel_clip); + if (lane < REL) { + const bfloat once = bfloat(r * rf); + rel_out[rh * REL + lane] = a.global ? bfloat(float(once) * tau) : once; + } + return; + } + const bool key = unit < a.heads + a.kv_heads; + const uint h = key ? unit - a.heads : unit - a.heads - a.kv_heads; + const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D; + for (uint i = 0; i < 4; ++i) x[i] = float(src[lane * 4 + i]); + float scale; + if (key) { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + } else { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = precise::rsqrt(ink_warp_sum(ss) / float(D) + a.eps); + } + const InkSeg s = segs[rseg[row]]; + device bfloat* dst = (key ? kc : vc) + s.off + (size_t(h) * a.ring + pos % a.ring) * D; + for (uint i = 0; i < 4; ++i) dst[lane * 4 + i] = bfloat(x[i] * scale); +} + +// The bf16 relative-bias table, one fp32 accumulation in projection tap order. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_rel_table(const device bfloat* rel [[buffer(0)]], const device bfloat* proj [[buffer(1)]], + device bfloat* tab [[buffer(2)]], uint rh [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + float r[REL]; + for (uint j = 0; j < REL; ++j) r[j] = float(rel[rh * REL + j]); + for (uint d = t; d < EXTENT; d += 256) { + float acc = 0.0f; + for (uint j = 0; j < REL; ++j) acc += r[j] * float(proj[j * EXTENT + d]); + tab[rh * EXTENT + d] = bfloat(acc); + } +} + +// A (row, head, key chunk) a simdgroup. Every P is bf16 before both its denominator add and P.V product. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_attn_scalar(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]], + const device InkSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], + const device int* rpos [[buffer(7)]], const device int* rseg [[buffer(8)]], constant InkAttnArgs& a [[buffer(9)]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint rh = tg.x, row = rh / a.heads, h = rh % a.heads, group = a.heads / a.kv_heads, kvh = h / group; + const uint pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + const uint first = a.window ? lo / a.chunk : a.c0; + const uint c = first + tg.y; + if (c > pos / a.chunk || (a.window && c < lo / a.chunk)) return; + const uint from = max(lo, c * a.chunk), to = min(pos + 1, (c + 1) * a.chunk); + const InkSeg s = segs[rseg[row]]; + const size_t head = s.off + size_t(kvh) * a.ring * D; + const size_t prow = rh; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + float top = -INFINITY, total = 0.0f; + for (uint kp = from; kp < to; ++kp) { + const size_t at = head + size_t(kp % a.ring) * D; + float4 qv = float4(*(const device bfloat4*)(q + prow * D + lane * 4)); + float4 kv = float4(*(const device bfloat4*)(kc + at + lane * 4)); + const float dot_score = ink_warp_sum(dot(qv, kv)); + const uint distance = pos - kp; + const float bias = distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; + const float score = (dot_score * a.scale + bias) * LOG2E; + const float next = max(top, score), a0 = precise::exp2(top - next), b0 = precise::exp2(score - next); + const bfloat p = bfloat(b0); + total = total * a0 + float(p); + for (uint i = 0; i < 4; ++i) acc[i] = acc[i] * a0 + float(p) * float(vc[at + lane * 4 + i]); + top = next; + } + const size_t slot = size_t(prow) * a.chunks + tg.y; + if (lane == 0) part_ml[slot] = float2(top, total); + for (uint i = 0; i < 4; ++i) part_o[slot * D + lane * 4 + i] = acc[i]; +} + +// Fold chunks and any sub-chunks in order, add the sink logit, apply the gate, round once to bf16. +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_ink2_merge(const device float* part_o [[buffer(0)]], const device float2* part_ml [[buffer(1)]], + const device bfloat* sink [[buffer(2)]], const device bfloat* gate [[buffer(3)]], const device int* rpos [[buffer(4)]], + device bfloat* out [[buffer(5)]], constant InkMergeArgs& a [[buffer(6)]], uint rh [[threadgroup_position_in_grid]], + uint d [[thread_index_in_threadgroup]]) { + const uint row = rh / a.heads, pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + float mm = -INFINITY, ll = 0.0f, o = 0.0f; + for (uint c = lo / a.chunk; c <= pos / a.chunk; ++c) { + float cm, cl, co; + if (a.subs > 1) { + float sm = -INFINITY, sl = 0.0f, so = 0.0f; + const uint last = min(a.subs - 1, (pos - c * a.chunk) / 1024); + for (uint u = 0; u <= last; ++u) { + const size_t at = size_t(rh) * a.chunks + (c - a.c0) * a.subs + u; + const float2 ml = part_ml[at]; + const float mn = max(sm, ml.x); + const float x = precise::exp2(sm - mn), y = precise::exp2(ml.x - mn); + sl = sl * x + ml.y * y; + so = so * x + part_o[at * D + d] * y; + sm = mn; + } + cm = sm; cl = sl; co = so; + } else { + const size_t at = size_t(rh) * a.chunks + c - (a.window ? lo / a.chunk : a.c0); + const float2 ml = part_ml[at]; + cm = ml.x; cl = ml.y; co = part_o[at * D + d]; + } + const float mn = max(mm, cm), x = precise::exp2(mm - mn), y = precise::exp2(cm - mn); + ll = ll * x + cl * y; + o = o * x + co * y; + mm = mn; + } + const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf); + const float y = o * a0 / (ll * a0 + precise::exp2(sk - mf)); + const float gv = float(gate[rh * D + d]); + out[rh * D + d] = bfloat(y * (1.0f / (1.0f + precise::exp(-gv)))); +} diff --git a/zig/kernels/metal/inkling2/attention_sources.zig b/zig/kernels/metal/inkling2/attention_sources.zig new file mode 100644 index 00000000000..1aac8a107e1 --- /dev/null +++ b/zig/kernels/metal/inkling2/attention_sources.zig @@ -0,0 +1,5 @@ +//! Shader texts; the prompt's fragment helpers are inline so both chip paths use the same resolver. + +pub const attention = @embedFile("attention.metal"); +pub const prompt_attention = @embedFile("../nax.h") ++ @embedFile("prompt_attention.metal"); +pub const prompt_attention_pre_m5 = "#define TF_SIMD_FRAGS 1\n" ++ prompt_attention; diff --git a/zig/kernels/metal/inkling2/dspark.metal b/zig/kernels/metal/inkling2/dspark.metal new file mode 100644 index 00000000000..01ee835290d --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark.metal @@ -0,0 +1,239 @@ +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant uint DSP_H = 2304; +constant uint DSP_Q = 3072; +constant uint DSP_KV = 1024; +constant uint DSP_HEAD = 128; +constant uint DSP_RANK = 256; +constant uint DSP_RNN = 768; +constant float DSP_EPS = 1e-6f; +constant float DSP_SCALE = 0x1.6a09e6p-7f; + +struct DsparkPositionArgs { uint base; }; +struct DsparkContextArgs { uint base, rows, ring; }; +struct DsparkAttentionArgs { uint committed, ring, local, from; }; +struct DsparkTokenArgs { uint token; }; +struct DsparkResidualArgs { uint init; }; +struct DsparkCountArgs { uint count; }; +struct DsparkBaseArgs { uint rows, vocab; }; + +kernel void tf_ink2_dspark_init_rows(const device bfloat* anchor [[buffer(0)]], const device bfloat* mask [[buffer(1)]], device bfloat* rows [[buffer(2)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + for (uint d = t; d < DSP_H; d += 256) { + const device bfloat* src = row == 0 ? anchor : mask; + rows[row * DSP_H + d] = src[d]; + } +} + +kernel void tf_ink2_dspark_fuse_taps(const device bfloat* taps [[buffer(0)]], const device bfloat* fuse_weight [[buffer(1)]], const device bfloat* norm_weight [[buffer(2)]], device bfloat* c [[buffer(3)]], device bfloat* newest_f [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + const uint fusion = group / a.count, row = group % a.count; + threadgroup float alpha[4]; + threadgroup float scale; + if (t == 0) { + float scores[4]; + float peak = -INFINITY; + for (uint j = 0; j < 4; ++j) { scores[j] = float(fuse_weight[fusion * 4 + j]); peak = max(peak, scores[j]); } + float sum = 0.0f; + for (uint j = 0; j < 4; ++j) { scores[j] = exp(scores[j] - peak); sum += scores[j]; } + for (uint j = 0; j < 4; ++j) alpha[j] = float(bfloat(scores[j] / sum)); + float square = 0.0f; + for (uint d = 0; d < DSP_H; ++d) { + float mixed = 0.0f; + for (uint j = 0; j < 4; ++j) mixed += alpha[j] * float(taps[(row * 4 + j) * DSP_H + d]); + square += mixed * mixed; + } + scale = rsqrt(square / float(DSP_H) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < DSP_H; d += 256) { + float mixed = 0.0f; + for (uint j = 0; j < 4; ++j) mixed += alpha[j] * float(taps[(row * 4 + j) * DSP_H + d]); + const bfloat out = bfloat(mixed * scale * float(norm_weight[fusion * DSP_H + d])); + c[(fusion * a.count + row) * DSP_H + d] = out; + if (fusion == 3 && row + 1 == a.count) newest_f[d] = out; + } +} + +static inline float dspark_rope_angle(uint d, uint position) { + const uint pair = d % 64; + const float frequency = pow(1e6f, -float(pair) / 64.0f); + return float(position) * frequency; +} + +kernel void tf_ink2_dspark_block_qkv(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], const device bfloat* v_raw [[buffer(2)]], const device bfloat* q_weight [[buffer(3)]], const device bfloat* k_weight [[buffer(4)]], device bfloat* q [[buffer(5)]], device bfloat* k [[buffer(6)]], device bfloat* v [[buffer(7)]], constant DsparkPositionArgs& a [[buffer(8)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 40, work = group % 40; + threadgroup float scale; + if (work < 32 && d == 0) { + float sum = 0.0f; + if (work < 24) { + const uint h = work; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(q_raw[row * DSP_Q + h * DSP_HEAD + i]); sum += x * x; } + } else { + const uint h = work - 24; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + } + scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (work >= 32) { + const uint h = work - 32; + v[row * DSP_KV + h * DSP_HEAD + d] = v_raw[row * DSP_KV + h * DSP_HEAD + d]; + return; + } + const bool query = work < 24; + const uint h = query ? work : work - 24; + const uint at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + d; + const float x = float(bfloat(float(query ? q_raw[at] : k_raw[at]) * scale * float(query ? q_weight[d] : k_weight[d]))); + const uint partner = d < 64 ? d + 64 : d - 64; + const uint other_at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + partner; + const float other = float(bfloat(float(query ? q_raw[other_at] : k_raw[other_at]) * scale * float(query ? q_weight[partner] : k_weight[partner]))); + const float angle = dspark_rope_angle(d, a.base + row); + const float cs = cos(angle), sn = sin(angle); + const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs; + if (query) q[at] = bfloat(rotated); else k[at] = bfloat(rotated); +} + +kernel void tf_ink2_dspark_context_kv(const device bfloat* k_raw [[buffer(0)]], const device bfloat* v_raw [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* keys [[buffer(3)]], device bfloat* values [[buffer(4)]], constant DsparkContextArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 8, h = group % 8; + threadgroup float scale; + if (d == 0) { + float sum = 0.0f; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint position = a.base + row; + const uint at = (position % a.ring) * DSP_KV + h * DSP_HEAD + d; + const uint src = row * DSP_KV + h * DSP_HEAD + d; + const uint partner = d < 64 ? d + 64 : d - 64; + const float x = float(bfloat(float(k_raw[src]) * scale * float(weight[d]))); + const float other = float(bfloat(float(k_raw[row * DSP_KV + h * DSP_HEAD + partner]) * scale * float(weight[partner]))); + const float angle = dspark_rope_angle(d, position); + const float cs = cos(angle), sn = sin(angle); + keys[at] = bfloat(d < 64 ? x * cs - other * sn : other * sn + x * cs); + values[at] = v_raw[src]; +} + +static inline float dspark_attention_score(const device bfloat* q, const device bfloat* k, uint q_at, uint k_at) { + float dot = 0.0f; + for (uint d = 0; d < DSP_HEAD; ++d) dot += float(q[q_at + d]) * float(k[k_at + d]); + return dot * DSP_SCALE; +} + +kernel void tf_ink2_dspark_attention(const device bfloat* q [[buffer(0)]], const device bfloat* block_k [[buffer(1)]], const device bfloat* block_v [[buffer(2)]], const device bfloat* context_k [[buffer(3)]], const device bfloat* context_v [[buffer(4)]], device float* scores [[buffer(5)]], device bfloat* out [[buffer(6)]], constant DsparkAttentionArgs& a [[buffer(7)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 24, h = group % 24, kv = h / 3; + const uint q_at = row * DSP_Q + h * DSP_HEAD; + const uint out_at = q_at + d; + const uint first = max(a.from, a.local && a.committed > 1024 ? a.committed - 1024 : 0); + const uint retained = a.committed - first; + const uint count = retained + 8; + const uint score_at = group * count; + threadgroup float peak, denominator; + if (d == 0) { + float m = -INFINITY; + for (uint j = 0; j < retained; ++j) { + const uint position = first + j; + const float s = dspark_attention_score(q, context_k, q_at, (position % a.ring) * DSP_KV + kv * DSP_HEAD); + scores[score_at + j] = s; + m = max(m, s); + } + for (uint j = 0; j < 8; ++j) { + const float s = dspark_attention_score(q, block_k, q_at, j * DSP_KV + kv * DSP_HEAD); + scores[score_at + retained + j] = s; + m = max(m, s); + } + float sum = 0.0f; + for (uint j = 0; j < count; ++j) sum += exp(scores[score_at + j] - m); + peak = m; + denominator = sum; + } + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); + float value = 0.0f; + for (uint j = 0; j < retained; ++j) { + const uint position = first + j; + const uint v_at = (position % a.ring) * DSP_KV + kv * DSP_HEAD + d; + value += (exp(scores[score_at + j] - peak) / denominator) * float(context_v[v_at]); + } + for (uint j = 0; j < 8; ++j) { + const uint v_at = (j * DSP_KV + kv * DSP_HEAD) + d; + value += (exp(scores[score_at + retained + j] - peak) / denominator) * float(block_v[v_at]); + } + out[out_at] = bfloat(value); +} + +kernel void tf_ink2_dspark_residual_norm(const device bfloat* x [[buffer(0)]], const device bfloat* residual [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* new_residual [[buffer(3)]], device bfloat* normalized [[buffer(4)]], constant DsparkResidualArgs& a [[buffer(5)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + threadgroup float scale; + if (t == 0) { + float sum = 0.0f; + for (uint d = 0; d < DSP_H; ++d) { + const uint at = row * DSP_H + d; + const float v = a.init ? float(x[at]) : float(x[at]) + float(residual[at]); + sum += v * v; + } + scale = rsqrt(sum / float(DSP_H) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint n = 0; n < 9; ++n) { + const uint d = n * 256 + t; + const uint at = row * DSP_H + d; + const float sigma = a.init ? float(x[at]) : float(x[at]) + float(residual[at]); + new_residual[at] = bfloat(sigma); + normalized[at] = bfloat(sigma * scale * float(weight[d])); + } +} + +kernel void tf_ink2_dspark_swiglu(const device bfloat* g [[buffer(0)]], const device bfloat* u [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkCountArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const float gate = float(g[i]); + out[i] = bfloat((gate / (1.0f + exp(-gate))) * float(u[i])); +} + +kernel void tf_ink2_dspark_kappa(const device bfloat* y [[buffer(0)]], const device bfloat* f [[buffer(1)]], const device bfloat* weight [[buffer(2)]], const device bfloat* bias [[buffer(3)]], device float* out [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + const uint row = i / DSP_RNN, channel = i % DSP_RNN; + if (row >= a.count) return; + float sum = 0.0f; + for (uint d = 0; d < DSP_H; ++d) sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + 512 + d]); + for (uint d = 0; d < DSP_H; ++d) sum += float(f[d]) * float(weight[channel * 5120 + 2816 + d]); + sum += float(bias[channel]); + out[i] = sum; +} + +kernel void tf_ink2_dspark_recurrent(const device bfloat* state [[buffer(0)]], const device bfloat* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkTokenArgs& a [[buffer(7)]], uint i [[thread_position_in_grid]]) { + if (i >= DSP_RANK) return; + float values[3]; + for (uint part = 0; part < 3; ++part) { + const uint channel = part * DSP_RANK + i; + float sum = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) sum += float(state[d]) * float(rnn_weight[channel * 5120 + d]); + for (uint d = 0; d < DSP_RANK; ++d) sum += float(markov[uint64_t(a.token) * DSP_RANK + d]) * float(rnn_weight[channel * 5120 + 256 + d]); + sum += float(kappa[channel]); + const bfloat rounded = bfloat(sum); + z[channel] = rounded; + values[part] = float(rounded); + } + const bfloat gamma = bfloat(1.0f / (1.0f + exp(-values[0]))); + const bfloat candidate = bfloat(tanh(values[1])); + const bfloat keep = bfloat(1.0f - float(gamma)); + const bfloat left = bfloat(float(gamma) * float(state[i])); + const bfloat right = bfloat(float(keep) * float(candidate)); + next_state[i] = bfloat(float(left) + float(right)); + lambda[i] = bfloat(tanh(values[2])); +} + +kernel void tf_ink2_dspark_base(const device bfloat* unembed [[buffer(0)]], const device bfloat* y [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkBaseArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= a.rows * a.vocab) return; + const uint row = i / a.vocab, id = i % a.vocab; + float dot = 0.0f; + for (uint d = 0; d < DSP_H; ++d) dot += float(unembed[id * DSP_H + d]) * float(y[row * DSP_H + d]); + out[i] = bfloat(dot); +} + +kernel void tf_ink2_dspark_logits(const device bfloat* base [[buffer(0)]], const device bfloat* phi [[buffer(1)]], const device bfloat* beta [[buffer(2)]], const device bfloat* lambda [[buffer(3)]], device bfloat* out [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + float dot = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) dot += float(phi[i * DSP_RANK + d]) * float(lambda[d]); + const bfloat bias = bfloat(float(beta[i]) + dot); + const bfloat logit = bfloat(float(base[i]) + float(bias)); + out[i] = bfloat(30.0f * tanh(float(logit) / 30.0f)); +} diff --git a/zig/kernels/metal/inkling2/dspark_sources.zig b/zig/kernels/metal/inkling2/dspark_sources.zig new file mode 100644 index 00000000000..c9cddfd2917 --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark_sources.zig @@ -0,0 +1,3 @@ +//! Mini DSpark's arithmetic shader and its ten Metal library entry points. + +pub const dspark = @embedFile("dspark.metal"); diff --git a/zig/kernels/metal/inkling2/experts.metal b/zig/kernels/metal/inkling2/experts.metal new file mode 100644 index 00000000000..b1ba70059cf --- /dev/null +++ b/zig/kernels/metal/inkling2/experts.metal @@ -0,0 +1,171 @@ +// Inkling 2 Mini M3: packed weight decode in registers, BF16 activations, FP32 reductions. +#include +using namespace metal; +#pragma METAL fp contract(off) + +struct Ink2MatrixArgs { uint k, n, topk, experts; }; +struct Ink2DecodeArgs { uint rows, k; }; + +inline float ink2_e2m1(uint code) { + const float magnitude[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + const float v = magnitude[code & 7u]; + return (code & 8u) ? -v : v; +} + +inline float ink2_e4m3(uint code) { + const uint exp = (code >> 3u) & 15u, mant = code & 7u; + if (exp == 15u && mant == 7u) return NAN; + const float v = exp ? ldexp(1.0f + float(mant) * 0.125f, int(exp) - 7) + : float(mant) * (1.0f / 512.0f); + return (code & 0x80u) ? -v : v; +} + +inline float ink2_phi(device const float* amax, device const float* denominator, uint expert) { + // Loader casts both globals to BF16 before the dequantization operation. + return precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); +} + +inline float ink2_nv_weight(uchar packed, uint column, uchar scale, float phi) { + const uint code = (column & 1u) ? uint(packed >> 4u) : uint(packed & 15u); + const float inner = ink2_e2m1(code) * ink2_e4m3(scale); + return float(bfloat(inner * phi)); +} + +inline float ink2_mx_weight(uchar value, uchar scale) { + const float w = ldexp(ink2_e4m3(value), int(scale) - 127); + // E4M3 times a power of two is exactly representable in BF16, still round explicitly. + return float(bfloat(w)); +} + +inline float ink2_dot_nv(device const uchar* w, device const uchar* scales, + device const bfloat* x, float phi, uint k) { + float sum = 0.0f; + for (uint c = 0; c < k; ++c) + sum += ink2_nv_weight(w[c / 2u], c, scales[c / 16u], phi) * float(x[c]); + return sum; +} + +inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, + device const bfloat* x, uint k) { + float sum = 0.0f; + for (uint c = 0; c < k; ++c) + sum += ink2_mx_weight(w[c], scales[c / 32u]) * float(x[c]); + return sum; +} + +inline float ink2_cap(float x, float cap) { + return cap * precise::tanh(precise::divide(x, cap)); +} + +inline bfloat ink2_act(float gate_dot, float up_dot) { + const float gate = float(bfloat(gate_dot)), up = float(bfloat(up_dot)); + const float left = ink2_cap(gate, 4.0f) * precise::divide(1.0f, 1.0f + precise::exp(-gate)); + // Both GEMM results round before the softcapped SwiGLU; sigmoid uses the rounded gate. + return bfloat(left * ink2_cap(up, 25.0f)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_gu( + 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 int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + for (uint n = lane; n < a.n; n += 32u) { + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), + S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), + S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k); + Y[group * a.n + n] = ink2_act(g, u); + } +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * a.k; + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); + for (uint n = lane; n < a.n; n += 32u) { + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, + S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k); + const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, + S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k); + Y[group * a.n + n] = ink2_act(g, u); + } +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_down( + 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 int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + for (uint n = lane; n < a.n; n += 32u) + Y[group * a.n + n] = bfloat(ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), + S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * a.k; + const ulong expert_s = ulong(expert) * a.n * (a.k / 32u); + for (uint n = lane; n < a.n; n += 32u) + Y[group * a.n + n] = bfloat(ink2_dot_mx(W + expert_w + ulong(n) * a.k, + S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k)); +} + +// Weight decode helpers unpack checkpoint bytes and never quantize an activation. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device const float* amax [[buffer(2)]], device const float* denominator [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2DecodeArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + const float phi = ink2_phi(amax, denominator, 0); + Y[at] = bfloat(ink2_nv_weight(W[row * (a.k / 2u) + col / 2u], col, + S[row * (a.k / 16u) + col / 16u], phi)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DecodeArgs& a [[buffer(3)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + Y[at] = bfloat(ink2_mx_weight(W[at], S[row * (a.k / 32u) + col / 32u])); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_combine( + device const bfloat* down [[buffer(0)]], device const int* ids [[buffer(1)]], + device const float* weights [[buffer(2)]], device bfloat* Y [[buffer(3)]], + constant Ink2MatrixArgs& a [[buffer(4)]], uint group [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + // Outer expert order, not route-slot order, fixes the reference's accumulation order. + for (uint n = lane; n < a.n; n += 32u) { + float sum = 0.0f; + for (uint expert = 0; expert < a.experts; ++expert) + for (uint slot = 0; slot < a.topk; ++slot) + if (uint(ids[group * a.topk + slot]) == expert) + sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]); + Y[group * a.n + n] = bfloat(sum); + } +} diff --git a/zig/kernels/metal/inkling2/experts_sources.zig b/zig/kernels/metal/inkling2/experts_sources.zig new file mode 100644 index 00000000000..56ae6e1c0db --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's M3 packed-weight expert kernels; activations stay BF16 throughout. +pub const experts = @embedFile("experts.metal"); diff --git a/zig/kernels/metal/inkling2/glue.metal b/zig/kernels/metal/inkling2/glue.metal new file mode 100644 index 00000000000..79e3a71a743 --- /dev/null +++ b/zig/kernels/metal/inkling2/glue.metal @@ -0,0 +1,225 @@ +#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); +} +inline float ink_cap(float x, float c) { + return c * precise::tanh(precise::divide(x, c)); +} +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]); +} + +struct InkEmbedArgs { uint rows; }; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_embed_norm( + const device uint* ids [[buffer(0)]], const device bfloat* table [[buffer(1)]], + const device bfloat* weight [[buffer(2)]], device bfloat* out [[buffer(3)]], + constant InkEmbedArgs& a [[buffer(4)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device bfloat* x = table + size_t(ids[row]) * 2304; + float part = 0.0f; + for (uint d = t; d < 2304; d += 256) { const float v = float(x[d]); part += v * v; } + threadgroup float red[8], inverse; + const float reduced = simd_sum(part); + if (lane == 0) red[t / 32] = reduced; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float total = 0.0f; + for (uint j = 0; j < 8; ++j) total += red[j]; + inverse = precise::rsqrt(precise::divide(total, 2304.0f) + INKLING_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < 2304; d += 256) + out[size_t(row) * 2304 + d] = bfloat(float(weight[d]) * (float(x[d]) * inverse)); +} + +struct InkARArgs { uint sources, queries; }; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_ar( + const device bfloat* blocks [[buffer(0)]], const device float* partial [[buffer(1)]], + const device float* queries [[buffer(2)]], device float* out [[buffer(3)]], + constant InkARArgs& a [[buffer(4)]], uint t [[thread_position_in_threadgroup]], + uint q [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (q >= a.queries || a.sources == 0 || a.sources > 5) return; + 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; + } + 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]; + means[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + threadgroup float* dots = red + 40; + for (uint s = 0; s < a.sources; ++s) { + float dot = 0.0f; + for (uint d = t; d < 2304; d += 256) { + const float z = ink_value(blocks, partial, s, a.sources, d) * means[s]; + dot += queries[size_t(q) * 2304 + d] * z; + } + const float reduced = simd_sum(dot); + if (lane == 0) dots[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float peak = -INFINITY; + for (uint s = 0; s < a.sources; ++s) { + float dot = 0.0f; + for (uint j = 0; j < 8; ++j) dot += dots[s * 8 + j]; + weights[s] = dot * INKLING_AR_SCALE; + peak = max(peak, weights[s]); + } + float den = 0.0f; + for (uint s = 0; s < a.sources; ++s) { weights[s] = precise::exp(weights[s] - peak); den += weights[s]; } + for (uint s = 0; s < a.sources; ++s) weights[s] = precise::divide(weights[s], den); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < 2304; d += 256) { + float acc = 0.0f; + for (uint s = 0; s < a.sources; ++s) + acc += weights[s] * (ink_value(blocks, partial, s, a.sources, d) * means[s]); + out[size_t(q) * 2304 + d] = acc; + } +} + +struct InkConvArgs { uint rows, channels; }; +kernel void tf_inkling2_conv_static( + const device bfloat* taps [[buffer(0)]], const device bfloat* weight [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkConvArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint c = at.x, r = at.y; + if (c >= a.channels || r >= a.rows) return; + float sum = float(taps[size_t(r + 3) * a.channels + c]); + for (uint tap = 0; tap < 4; ++tap) + sum += float(weight[c * 4 + tap]) * float(taps[size_t(r + tap) * a.channels + c]); + out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, precise::sqrt(5.0f))); +} + +kernel void tf_inkling2_conv_dynamic( + const device bfloat* taps [[buffer(0)]], const device bfloat* input [[buffer(1)]], + const device bfloat* static_w [[buffer(2)]], const device bfloat* projection [[buffer(3)]], + device bfloat* out [[buffer(4)]], constant InkConvArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint r [[threadgroup_position_in_grid]]) { + if (r >= a.rows) return; + threadgroup float projected[32]; + if (t < 32) { + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(projection[size_t(t) * 2304 + d]) * float(input[size_t(r) * 2304 + d]); + projected[t] = float(bfloat(dot)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint c = t; c < a.channels; c += 256) { + float sum = float(taps[size_t(r + 3) * a.channels + c]); + for (uint lag = 0; lag < 4; ++lag) { + const float w = float(static_w[lag * a.channels + c]) + projected[4 * (c / 128) + lag]; + sum += w * float(taps[size_t(r + 3 - lag) * a.channels + c]); + } + out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, 3.0f)); + } +} + +struct InkRouteArgs { uint rows; }; +kernel void tf_inkling2_router( + const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], + const device float* bias [[buffer(2)]], device uint* ids [[buffer(3)]], + device float* weights [[buffer(4)]], constant InkRouteArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint row [[threadgroup_position_in_grid]]) { + if (row >= a.rows) return; + threadgroup float scores[128], chosen[8]; + threadgroup uint picked[8]; + if (t < 128) { + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(weight[size_t(t) * 2304 + d]) * float(x[size_t(row) * 2304 + d]); + scores[t] = ink_sigmoid(dot); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + bool used[128] = {}; + for (uint j = 0; j < 8; ++j) { + uint best = 128; + for (uint e = 0; e < 128; ++e) if (!used[e]) { + if (best == 128 || scores[e] + bias[e] > scores[best] + bias[best]) best = e; + } + used[best] = true; picked[j] = best; chosen[j] = scores[best]; + } + // Combining, including the denominator, is in ascending expert index. + for (uint j = 1; j < 8; ++j) { + uint id = picked[j]; float score = chosen[j]; uint k = j; + while (k > 0 && picked[k - 1] > id) { picked[k] = picked[k - 1]; chosen[k] = chosen[k - 1]; --k; } + picked[k] = id; chosen[k] = score; + } + float den = 1e-20f; + for (uint j = 0; j < 8; ++j) den += chosen[j]; + for (uint j = 0; j < 8; ++j) { + ids[row * 8 + j] = picked[j]; + weights[row * 8 + j] = precise::divide(chosen[j], den) * 8.0f; + } + } +} + +struct InkActArgs { uint rows, width; }; +kernel void tf_inkling2_swiglu( + const device bfloat* gu [[buffer(0)]], device bfloat* out [[buffer(1)]], + constant InkActArgs& a [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const uint j = at.x, r = at.y; + if (j >= a.width || r >= a.rows) return; + const float g = float(gu[(size_t(r) * a.width + j) * 2]); + const float u = float(gu[(size_t(r) * a.width + j) * 2 + 1]); + out[size_t(r) * a.width + j] = bfloat(ink_cap(g, 4.0f) * ink_sigmoid(g) * ink_cap(u, 25.0f)); +} + +struct InkLogitArgs { uint rows, vocab; }; +kernel void tf_inkling2_logits( + const device bfloat* h [[buffer(0)]], const device bfloat* unembed [[buffer(1)]], + device float* out [[buffer(2)]], constant InkLogitArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint v = at.x, r = at.y; + if (v >= a.vocab || r >= a.rows) return; + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(unembed[size_t(v) * 2304 + d]) * float(h[size_t(r) * 2304 + d]); + // A9(a): unembedding rounds to bf16 before it widens for softcap30. + out[size_t(r) * a.vocab + v] = ink_cap(float(bfloat(dot)), 30.0f); +} + +struct InkExpertArgs { uint rows, channels; }; +kernel void tf_inkling2_expert_pick( + const device bfloat* experts [[buffer(0)]], const device uint* ids [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkExpertArgs& a [[buffer(3)]], + uint3 at [[thread_position_in_grid]]) { + const uint j = at.x, d = at.y, r = at.z; + if (j >= 8 || d >= a.channels || r >= a.rows) return; + out[(size_t(r) * 8 + j) * a.channels + d] = experts[(size_t(r) * 128 + ids[r * 8 + j]) * a.channels + d]; +} + +kernel void tf_inkling2_expert_combine( + const device bfloat* picked [[buffer(0)]], const device float* weights [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkExpertArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint d = at.x, r = at.y; + if (d >= a.channels || r >= a.rows) return; + float acc = 0.0f; + for (uint j = 0; j < 8; ++j) + acc += weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]); + out[size_t(r) * a.channels + d] = bfloat(acc); +} diff --git a/zig/kernels/metal/inkling2/glue_sources.zig b/zig/kernels/metal/inkling2/glue_sources.zig new file mode 100644 index 00000000000..b0e00911c06 --- /dev/null +++ b/zig/kernels/metal/inkling2/glue_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's embedding, residual, convolution, routing and output glue. +pub const glue = @embedFile("glue.metal"); diff --git a/zig/kernels/metal/inkling2/loop.metal b/zig/kernels/metal/inkling2/loop.metal new file mode 100644 index 00000000000..fce6e866f6b --- /dev/null +++ b/zig/kernels/metal/inkling2/loop.metal @@ -0,0 +1,136 @@ +#include +#pragma METAL fp contract(off) +using namespace metal; + +// Cross-pass dots use fixed-order FP32 accumulation and SIMD reductions; no BF16 value accumulates. +constant float INKLING_LOOP_EPS = 1e-6f; +constant float INKLING_LOOP_SCALE = 0x1.555556p-6f; // binary32(1 / 48) +constant uint INKLING_LOOP_H = 2304; +constant uint INKLING_LOOP_RANK = 64; +constant uint INKLING_LOOP_MESSAGES = 48; + +struct InkLoopArgs { uint rows; }; + +kernel void tf_inkling2_loop_messages( + const device bfloat* bank0 [[buffer(0)]], const device bfloat* bank1 [[buffer(1)]], + const device float* q_mlp [[buffer(2)]], const device float* kv [[buffer(3)]], + device float* out [[buffer(4)]], constant InkLoopArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint work [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row = work / INKLING_LOOP_MESSAGES; + const uint entry = work - row * INKLING_LOOP_MESSAGES; + if (row >= a.rows) return; + const uint layer = entry / 4; + const uint role = entry - 4 * layer; + const device float* queries = (role == 0 || role == 3) ? q_mlp : kv; + // q/mlp and k/v occupy even/odd rows respectively. + const device float* query = queries + size_t(2 * layer + (role >= 2 ? 1 : 0)) * INKLING_LOOP_H; + const device bfloat* banks[2] = { bank0 + size_t(row) * INKLING_LOOP_H, + bank1 + size_t(row) * INKLING_LOOP_H }; + threadgroup float sums[2 * 8], inverse[2], dots[2 * 8], weights[2]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = float(banks[s][d]); + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint s = 0; s < 2; ++s) { + float dot = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float beta = float(banks[s][d]) * inverse[s]; + dot += query[d] * beta; + } + const float reduced = simd_sum(dot); + if (lane == 0) dots[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float logits[2]; + float peak = -INFINITY; + for (uint s = 0; s < 2; ++s) { + float dot = 0.0f; + for (uint j = 0; j < 8; ++j) dot += dots[s * 8 + j]; + weights[s] = dot * INKLING_LOOP_SCALE; + logits[s] = weights[s]; + peak = max(peak, logits[s]); + } + float den = 0.0f; + for (uint s = 0; s < 2; ++s) { + weights[s] = precise::exp(logits[s] - peak); + den += weights[s]; + } + for (uint s = 0; s < 2; ++s) weights[s] = precise::divide(weights[s], den); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float beta0 = float(banks[0][d]) * inverse[0]; + const float beta1 = float(banks[1][d]) * inverse[1]; + out[(size_t(row) * INKLING_LOOP_MESSAGES + entry) * INKLING_LOOP_H + d] = + weights[0] * beta0 + weights[1] * beta1; + } +} + +kernel void tf_inkling2_loop_gates( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], + const device bfloat* down [[buffer(2)]], const device bfloat* forget [[buffer(3)]], + const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], + constant InkLoopArgs& a [[buffer(6)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device float* inputs[2] = { h + size_t(row) * INKLING_LOOP_H, + m + size_t(row) * INKLING_LOOP_H }; + threadgroup float sums[2 * 8], inverse[2], zeta[INKLING_LOOP_RANK]; + threadgroup bfloat normalized[2 * INKLING_LOOP_H]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = inputs[s][d]; + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + normalized[d] = bfloat(h[size_t(row) * INKLING_LOOP_H + d] * inverse[0]); + normalized[INKLING_LOOP_H + d] = bfloat(m[size_t(row) * INKLING_LOOP_H + d] * inverse[1]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < INKLING_LOOP_RANK) { + float dot = 0.0f; + for (uint d = 0; d < 2 * INKLING_LOOP_H; ++d) + dot += float(down[size_t(t) * (2 * INKLING_LOOP_H) + d]) * float(normalized[d]); + zeta[t] = float(bfloat(dot)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + float fdot = 0.0f, gdot = 0.0f; + for (uint r = 0; r < INKLING_LOOP_RANK; ++r) { + fdot += float(forget[size_t(d) * INKLING_LOOP_RANK + r]) * zeta[r]; + gdot += float(gain[size_t(d) * INKLING_LOOP_RANK + r]) * zeta[r]; + } + const float f = precise::tanh(fdot); + const float g = precise::tanh(gdot); + // Four separately rounded binary32 steps; do not fold these into one expression. + const float keep = 1.0f - f; + const float left = keep * h[size_t(row) * INKLING_LOOP_H + d]; + const float right = g * m[size_t(row) * INKLING_LOOP_H + d]; + out[size_t(row) * INKLING_LOOP_H + d] = left + right; + } +} diff --git a/zig/kernels/metal/inkling2/loop_sources.zig b/zig/kernels/metal/inkling2/loop_sources.zig new file mode 100644 index 00000000000..3e1345c1a82 --- /dev/null +++ b/zig/kernels/metal/inkling2/loop_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's cross-pass message and rank-64 gate shaders. +pub const loop = @embedFile("loop.metal"); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal new file mode 100644 index 00000000000..06f4459bd7e --- /dev/null +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -0,0 +1,145 @@ +//! Inkling 2 Mini's prompt attention; attention_sources prepends the tensor-fragment helpers. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, 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; }; + +inline size_t ink_prompt_rh(const InkPromptSeg& s, uint heads, uint group, uint kvh, uint pair) { + return (size_t(s.row0) + pair / group) * heads + kvh * group + pair % group; +} + +inline void ink_fold(float& mm, float& ll, float m, float l, float& a, float& b) { + const float mn = max(mm, m); + a = precise::exp2(mm - mn); + b = precise::exp2(m - mn); + ll = ll * a + l * b; + mm = mn; +} +inline void ink_rows(thread const tfp::frag* s, thread float (&r)[2], bool maximum) { + for (uint f = 0; f < 4; ++f) for (uint h = 0; h < 2; ++h) { + const uint b = 4 * h; + float v = maximum ? max(max(s[f][b], s[f][b + 1]), max(s[f][b + 2], s[f][b + 3])) + : (s[f][b] + s[f][b + 1]) + (s[f][b + 2] + s[f][b + 3]); + const float x = simd_shuffle_xor(v, ushort(1)); + v = maximum ? max(v, x) : v + x; + const float y = simd_shuffle_xor(v, ushort(8)); + v = maximum ? max(v, y) : v + y; + r[h] = maximum ? max(r[h], v) : r[h] + v; + } +} + +// 128 (row, head) pairs and one key head/chunk a 256-thread group; each simdgroup owns 16 pairs. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]], + const device InkPromptSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], + constant InkPromptArgs& a [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) { + threadgroup bfloat ks[KEYS * D], vs[KEYS * D]; + 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; + 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 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; + const uint pair_a = min(row_a, total - 1), pair_b = min(row_b, total - 1); + const device bfloat* qb0 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_a) * D; + const device bfloat* qb1 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_b) * D; + const size_t hb = s.off + size_t(kvh) * a.ring * D; + tfp::frag acc[8], out[8]; + for (uint d = 0; d < 8; ++d) { acc[d] = tfp::frag(0); out[d] = tfp::frag(0); } + float top[2] = {-INFINITY, -INFINITY}, mass[2] = {0.0f, 0.0f}; + 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); + 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; + const size_t at = hb + size_t((live ? kp : kt) % a.ring) * D + col; + ks[e] = live ? kc[at] : bfloat(0); + vs[e] = live ? vc[at] : bfloat(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + 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; + } + tfp::frag score[4] = {tfp::frag(0), tfp::frag(0), tfp::frag(0), tfp::frag(0)}; + if (m < total && kt <= uint(s.p0) + min(m + 15, total - 1) / group) { + 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); + 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); + tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); + tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); + } + float peak[2] = {top[0], top[1]}; + const uint sub_lo = b_lo + ((kt - b_lo) / 1024) * 1024, sub_hi = sub_lo + 1023; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col; + const uint lr = row < total ? row / group : 0, pos = uint(s.p0) + lr; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + const bool live = row < total && kp <= pos && kp >= sub_lo && kp <= sub_hi; + const uint distance = live ? pos - kp : 0; + const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; + score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY; + } + ink_rows(score, peak, true); + float keep[2]; + for (uint h = 0; h < 2; ++h) { + const float mu = peak[h] == -INFINITY ? 0.0f : peak[h]; + keep[h] = precise::exp2(top[h] - mu); + top[h] = peak[h]; mass[h] *= keep[h]; + } + tfp::frag p[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const float mu = peak[e >> 2] == -INFINITY ? 0.0f : peak[e >> 2]; + p[f][e] = bfloat(precise::exp2(score[f][e] - mu)); + } + // Reduce the rounded P, not its pre-bf16 exponential. + tfp::frag rounded[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) rounded[f][e] = float(p[f][e]); + ink_rows(rounded, mass, false); + 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; + tfp::frag_get(v0, vs, D, 16 * f, 16 * d, home); + tfp::frag_get(v1, vs, D, 16 * f, 16 * d + 16, home); + tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); + } + } + const bool fold_now = (kt - b_lo) % 1024 == 960 || kt + KEYS > k_hi; + if (fold_now && m < total) for (uint h = 0; h < 2; ++h) { + if (top[h] == -INFINITY) continue; + float x, y; + 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; + } + threadgroup_barrier(mem_flags::mem_threadgroup); // no simdgroup reads ks/vs when the next tile overwrites them + } + if (m >= total) return; + 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 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]; + } + 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]); + } +} diff --git a/zig/kernels/metal/inkling2/runtime.metal b/zig/kernels/metal/inkling2/runtime.metal new file mode 100644 index 00000000000..e77123891b9 --- /dev/null +++ b/zig/kernels/metal/inkling2/runtime.metal @@ -0,0 +1,28 @@ +#include +using namespace metal; +#pragma METAL fp contract(off) +struct InkRuntimeArgs { uint count, boundary; }; +kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = x[i]; +} +kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = x[i]; +} +kernel void tf_ink2_widen(const device bfloat* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = float(x[i]); +} +kernel void tf_ink2_attention_partial(const device bfloat* p [[buffer(0)]], const device bfloat* x [[buffer(1)]], device bfloat* blocks [[buffer(2)]], device float* t [[buffer(3)]], constant InkRuntimeArgs& a [[buffer(4)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const uint row = i / 2304, d = i % 2304; + t[i] = a.boundary ? float(x[i]) : float(p[i]) + float(x[i]); + if (a.boundary) blocks[row * 4 * 2304 + (a.boundary - 1) * 2304 + d] = p[i]; +} +kernel void tf_ink2_mlp_partial(const device float* t [[buffer(0)]], const device bfloat* x [[buffer(1)]], device bfloat* p [[buffer(2)]], constant InkRuntimeArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) p[i] = bfloat(t[i] + float(x[i])); +} + +kernel void tf_ink2_capture_tap(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const uint row = i / 2304, d = i % 2304; + y[row * 4 * 2304 + a.boundary * 2304 + d] = x[i]; +} diff --git a/zig/kernels/metal/inkling2/runtime_sources.zig b/zig/kernels/metal/inkling2/runtime_sources.zig new file mode 100644 index 00000000000..e987c44855e --- /dev/null +++ b/zig/kernels/metal/inkling2/runtime_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's copy, widening and partial-residual shaders. +pub const runtime = @embedFile("runtime.metal"); diff --git a/zig/kernels/metal/inkling2_sources.zig b/zig/kernels/metal/inkling2_sources.zig new file mode 100644 index 00000000000..f105ac0f3a2 --- /dev/null +++ b/zig/kernels/metal/inkling2_sources.zig @@ -0,0 +1,10 @@ +//! Mini Metal shaders for the family and kernel contract, rooted beside nax.h for prompt-header package scope. + +pub const attention = @import("inkling2/attention_sources.zig").attention; +pub const prompt_attention = @import("inkling2/attention_sources.zig").prompt_attention; +pub const prompt_attention_pre_m5 = @import("inkling2/attention_sources.zig").prompt_attention_pre_m5; +pub const glue = @import("inkling2/glue_sources.zig").glue; +pub const experts = @import("inkling2/experts_sources.zig").experts; +pub const loop = @import("inkling2/loop_sources.zig").loop; +pub const runtime = @import("inkling2/runtime_sources.zig").runtime; +pub const inkling2_dspark = @import("inkling2/dspark_sources.zig").dspark; diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index b07432e1270..9ef118b2ea1 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -299,3 +299,6 @@ pub const glm_draft_topk = @embedFile("glm_draft_topk.metal"); pub const glm_draft_accept = @embedFile("glm_draft_accept.metal"); /// GLM-5.3-Flash's DFlash2 inline follow: copies accepted tap rows into the drafter ring ahead of its block. pub const glm_draft_follow = @embedFile("glm_draft_follow.metal"); + +/// Inkling 2 Mini's runtime helpers, the exact source compiled by its model and kernel contract. +pub const inkling2_runtime = @embedFile("inkling2/runtime.metal"); diff --git a/zig/src/core/contract/fakes.zig b/zig/src/core/contract/fakes.zig index 1e761d9339e..e344775cfe7 100644 --- a/zig/src/core/contract/fakes.zig +++ b/zig/src/core/contract/fakes.zig @@ -156,6 +156,25 @@ test "correct CPU kernels pass gates 1-4 and every planted fault goes red at its try std.testing.expectEqual(@as(usize, 0), t.problems()); } +test "initialization failures are tallied and later kernels and controls still run" { + const a = std.testing.allocator; + var f = Fake{ .a = a, .op = .sum }; + defer f.deinit(); + const missing: g.Kernel = .{ .spec = spec("missing library", .sum), .ctx = undefined, .vt = undefined, .init_error = error.NoFunction }; + const missed_control: g.Kernel = .{ .spec = spec("missing control library", .sum), .ctx = undefined, .vt = undefined, .control = .shapes, .init_error = error.NoFunction }; + g.quiet = true; + defer g.quiet = false; + var t: g.Tally = .{}; + try g.runAll(a, &.{ missing, missed_control, f.kernel("after missing library", null) }, 0x5eed, &t); + try std.testing.expectEqual(@as(usize, 2), t.kernels); + try std.testing.expectEqual(@as(usize, 1), t.failed); + try std.testing.expectEqual(@as(usize, 1), t.passed); + try std.testing.expectEqual(@as(usize, 1), t.controls); + try std.testing.expectEqual(@as(usize, 1), t.missed); + try std.testing.expectEqual(@as(usize, 2), t.problems()); + try std.testing.expect(f.runs > 0); +} + test "a tail fault passes at whole tiles: the edges are what catch it" { const a = std.testing.allocator; var f = Fake{ .a = a, .op = .sum, .fault = .tail }; diff --git a/zig/src/core/contract/gates.zig b/zig/src/core/contract/gates.zig index a815417a16b..eed00563a16 100644 --- a/zig/src/core/contract/gates.zig +++ b/zig/src/core/contract/gates.zig @@ -19,6 +19,8 @@ pub const Kernel = struct { ctx: *anyopaque, vt: *const VTable, control: ?Gate = null, + /// An initialization error to tally without reading ctx or vt. + init_error: ?anyerror = null, }; /// The hooks a kernel's test gives the harness; the harness owns no device memory. @@ -351,6 +353,18 @@ pub fn one(a: std.mem.Allocator, which: Gate, k: Kernel, seed: u64) !Verdict { /// Gates 1-4 on each kernel, and each control at its own gate (which must fail). pub fn runAll(a: std.mem.Allocator, kernels: []const Kernel, seed: u64, t: *Tally) !void { for (kernels) |k| { + if (k.init_error) |err| { + if (k.control) |gate| { + t.controls += 1; + t.missed += 1; + if (!quiet) std.debug.print("CONTROL ERROR {s}: {t} at {t}, so it proves nothing\n", .{ k.spec.name, err, gate }); + } else { + t.kernels += 1; + t.failed += 1; + if (!quiet) std.debug.print("FAIL init {s}: {t}\n", .{ k.spec.name, err }); + } + continue; + } defer if (k.vt.release) |free| free(k.ctx); const s = std.hash.Wyhash.hash(seed, k.spec.name); if (k.control) |g| { diff --git a/zig/src/core/contract/inkling2_attention_metal_records.zig b/zig/src/core/contract/inkling2_attention_metal_records.zig new file mode 100644 index 00000000000..14a887d12dd --- /dev/null +++ b/zig/src/core/contract/inkling2_attention_metal_records.zig @@ -0,0 +1,15 @@ +//! Inkling 2 Mini attention launches; prompt tensor ops have no ahead-of-time M1/M2 translator. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 attention prep tf_ink2_prep", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 attention relative table tf_ink2_rel_table", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 attention scalar tf_ink2_attn_scalar", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 attention merge tf_ink2_merge", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "metal inkling2 prompt m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false }, +}; + +test "Inkling 2 Metal launches respect their resource declarations" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/inkling2_dspark_metal_records.zig b/zig/src/core/contract/inkling2_dspark_metal_records.zig new file mode 100644 index 00000000000..a4cb19399da --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_metal_records.zig @@ -0,0 +1,15 @@ +//! Mini DSpark Metal launches (zig/tests/contract/metal_inkling2_dspark.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 dspark init_rows tf_ink2_dspark_init_rows", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark fuse_taps tf_ink2_dspark_fuse_taps", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "metal inkling2 dspark block_qkv tf_ink2_dspark_block_qkv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark context_kv tf_ink2_dspark_context_kv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark attention tf_ink2_dspark_attention", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark residual_norm tf_ink2_dspark_residual_norm", .threads = 256, .tg_memory = 16, .reserved = 256 }, + .{ .name = "metal inkling2 dspark swiglu tf_ink2_dspark_swiglu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark kappa tf_ink2_dspark_kappa", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark recurrent tf_ink2_dspark_recurrent", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark base tf_ink2_dspark_base", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark logits tf_ink2_dspark_logits", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_experts_metal_records.zig b/zig/src/core/contract/inkling2_experts_metal_records.zig new file mode 100644 index 00000000000..357a1ca88b0 --- /dev/null +++ b/zig/src/core/contract/inkling2_experts_metal_records.zig @@ -0,0 +1,22 @@ +//! Inkling 2 Mini M3 scalar Metal launches; 32 reserved threads avoid unmeasured M1/M2 receipts. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_gu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_gu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; + +test "Inkling2 expert launches carry no fabricated 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(std.mem.startsWith(u8, record.name, "metal inkling2 experts ")); + } +} diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig new file mode 100644 index 00000000000..e0013f02bae --- /dev/null +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -0,0 +1,13 @@ +//! Inkling 2 Mini glue launches (zig/tests/contract/metal_inkling2_glue.zig). +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 conv_static tf_inkling2_conv_static", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "metal inkling2 glue router tf_inkling2_router", .threads = 256, .tg_memory = 576, .reserved = 256 }, + .{ .name = "metal inkling2 glue swiglu tf_inkling2_swiglu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue logits tf_inkling2_logits", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue expert_pick tf_inkling2_expert_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue expert_combine tf_inkling2_expert_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; diff --git a/zig/src/core/contract/inkling2_loop_metal_records.zig b/zig/src/core/contract/inkling2_loop_metal_records.zig new file mode 100644 index 00000000000..8f32f1a7ab5 --- /dev/null +++ b/zig/src/core/contract/inkling2_loop_metal_records.zig @@ -0,0 +1,6 @@ +//! Inkling 2 Mini loop launches (zig/tests/contract/metal_inkling2_loop.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 loop messages tf_inkling2_loop_messages", .threads = 256, .tg_memory = 144, .reserved = 256 }, + .{ .name = "metal inkling2 loop gates tf_inkling2_loop_gates", .threads = 256, .tg_memory = 9552, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_runtime_metal_records.zig b/zig/src/core/contract/inkling2_runtime_metal_records.zig new file mode 100644 index 00000000000..4f1a7ffc40f --- /dev/null +++ b/zig/src/core/contract/inkling2_runtime_metal_records.zig @@ -0,0 +1,10 @@ +//! Inkling 2 Mini runtime helper launches (zig/tests/contract/metal_inkling2_runtime.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime copy_f32 tf_ink2_copy_f32", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime widen tf_ink2_widen", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime attention_partial tf_ink2_attention_partial", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime capture_tap tf_ink2_capture_tap", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index e696c6929e5..d1a0b824589 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -93,6 +93,12 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("qwen27_moe_records.zig").records ++ @import("qwen27_prompt_records.zig").records ++ @import("affine_gather_records.zig").records ++ + @import("inkling2_attention_metal_records.zig").records ++ + @import("inkling2_glue_metal_records.zig").records ++ + @import("inkling2_experts_metal_records.zig").records ++ + @import("inkling2_loop_metal_records.zig").records ++ + @import("inkling2_runtime_metal_records.zig").records ++ + @import("inkling2_dspark_metal_records.zig").records ++ @import("flint_records.zig").records ++ @import("hy4_records.zig").metal ++ @import("uocr_records.zig").records ++ @@ -136,4 +142,10 @@ pub const dsv41_pending = @import("registry_union.zig").extra( test { _ = @import("mla_cuda_records.zig"); _ = @import("inkling2_cuda_records.zig"); + _ = @import("inkling2_attention_metal_records.zig"); + _ = @import("inkling2_glue_metal_records.zig"); + _ = @import("inkling2_experts_metal_records.zig"); + _ = @import("inkling2_loop_metal_records.zig"); + _ = @import("inkling2_runtime_metal_records.zig"); + _ = @import("inkling2_dspark_metal_records.zig"); } diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig new file mode 100644 index 00000000000..8b5b4c8f39b --- /dev/null +++ b/zig/src/families/inkling2/metal/attention.zig @@ -0,0 +1,92 @@ +//! Real Metal pipeline loading and encoder dispatch for Inkling 2 Mini attention. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); +pub const planning = @import("attention_plan.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Cache = struct { k: Ref, v: Ref }; +pub const RowMeta = struct { pos: Ref, seg_of: Ref, segs: Ref }; + +pub const Kernels = struct { + scalar_lib: mtl.Library, + prompt_lib: mtl.Library, + prep: mtl.Pipeline, + rel_table: mtl.Pipeline, + decode: mtl.Pipeline, + merge: mtl.Pipeline, + prompt: mtl.Pipeline, + units: bool, + + pub fn init(a: std.mem.Allocator, device: mtl.Device) !Kernels { + var scalar_lib = try mtl.Library.fromSource(device, src.attention, mtl.CompileOptions.mlx()); + errdefer scalar_lib.deinit(); + const units = device.tensorUnits(); + const prompt_src = try a.dupe(u8, if (units) src.prompt_attention else src.prompt_attention_pre_m5); + defer a.free(prompt_src); + var prompt_lib = try mtl.Library.fromSource(device, prompt_src, mtl.CompileOptions.mlx()); + errdefer prompt_lib.deinit(); + var pipes: [5]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for ([_]mtl.Library{ scalar_lib, scalar_lib, scalar_lib, scalar_lib, prompt_lib }, [_][]const u8{ "tf_ink2_prep", "tf_ink2_rel_table", "tf_ink2_attn_scalar", "tf_ink2_merge", "tf_ink2_attn_prompt" }, &pipes) |lib, name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ .scalar_lib = scalar_lib, .prompt_lib = prompt_lib, .prep = pipes[0], .rel_table = pipes[1], .decode = pipes[2], .merge = pipes[3], .prompt = pipes[4], .units = units }; + } + pub fn deinit(k: *Kernels) void { + k.prompt.deinit(); + k.merge.deinit(); + k.decode.deinit(); + k.rel_table.deinit(); + k.prep.deinit(); + k.prompt_lib.deinit(); + k.scalar_lib.deinit(); + k.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref, first: usize) void { + for (refs, first..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} + +/// raw holds independent q/k/v rows followed by q-side relative rows; gated sliding visits never infer K or V from Q. +pub fn prep(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, c: planning.Prep, meta: RowMeta, raw: [4]Ref, scales: [2]Ref, q: Ref, rel: Ref, kv: Cache) void { + e.setPipeline(k.prep); + bind(e, &raw, 0); + bind(e, &scales, 4); + bind(e, &.{ meta.pos, meta.seg_of, meta.segs, q, rel, kv.k, kv.v }, 6); + e.setValue(planning.PrepArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .global = @intFromBool(l.tau), .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor_pos = c.floor, .alpha = c.alpha, .eps = c.eps }, 13); + e.dispatchGroups(mtl.Size.of(r.rows, r.heads + 2 * r.kv_heads, 1), mtl.Size.of(32, 1, 1)); +} + +pub fn relTable(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, rel: Ref, proj: Ref, tab: Ref) void { + e.setPipeline(k.rel_table); + bind(e, &.{ rel, proj, tab }, 0); + e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(256, 1, 1)); +} + +pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + const launch = try planning.attend(r, l, stride, slots); + const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); + if (launch.path == .decode) { + e.setPipeline(k.decode); + bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml, meta.pos, meta.seg_of }, 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 }, 9); + } else { + e.setPipeline(k.prompt); + bind(e, &.{ q, kv.k, kv.v, tab, meta.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 }, 7); + } + e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); + 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)); +} + +test { + _ = @import("attention_plan.zig"); +} diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig new file mode 100644 index 00000000000..6688dc8d7a0 --- /dev/null +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -0,0 +1,98 @@ +//! Pure host geometry and ABI declarations for Inkling 2 Mini Metal attention. +const std = @import("std"); + +pub const head_dim = 128; +pub const d_rel = 16; +pub const extent = 1024; +pub const tile_keys = 64; +pub const sliding_chunk = 256; +pub const global_chunk = 16384; +pub const global_sub = 1024; +pub const subs = global_chunk / global_sub; +pub const split_rows = 64; +pub const prompt_pairs = 128; +pub const prompt_threads = 256; +pub const decode_threads = 32; +pub const merge_threads = head_dim; + +pub const Seg = extern struct { row0: i32, n: i32, p0: i32, pad: i32 = 0, off: i64 }; +pub const PrepArgs = extern struct { + heads: u32, + kv_heads: u32, + ring: u32, + global: u32, + qk_clip: f32, + rel_clip: f32, + floor_pos: f32, + alpha: f32, + eps: f32, +}; +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 }; +comptime { + if (@sizeOf(Seg) != 24 or @sizeOf(PrepArgs) != 36 or @sizeOf(AttnArgs) != 32) @compileError("Inkling attention ABI drift"); + if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 28) @compileError("Inkling prompt ABI drift"); +} + +pub const Layer = struct { + window: u32, + ring: u32, + chunk: u32, + tau: bool, + pub fn sliding(window: u32, rows: u32) Layer { + 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 }; + } + pub fn cacheBytes(l: Layer, kv: usize) usize { + return @as(usize, l.ring) * kv * head_dim * 2; + } +}; +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 fn ringFor(window: u32, rows: u32) u32 { + return @intCast(std.mem.alignForward(usize, @as(usize, window) + rows - 1, tile_keys)); +} +pub fn chunks(last_pos: usize, chunk: u32) u32 { + return @intCast(last_pos / chunk + 1); +} +pub fn slotsFor(l: Layer, context: usize) u32 { + if (l.window > 0) return (l.window - 1) / l.chunk + 2; + return chunks(context - 1, l.chunk); +} +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); +} +pub fn partialSlot(l: Layer, c: usize, pos: usize) ?usize { + const lo = if (l.window > 0) (pos + 1) -| l.window else 0; + if (c < lo / l.chunk or c > pos / l.chunk) return null; + return c - lo / l.chunk; +} +pub fn tableBytes(rows: usize, heads: u32) usize { + return rows * heads * extent * 2; +} +pub fn partialBytes(rows: usize, heads: u32, n_chunks: u32) usize { + return rows * heads * n_chunks * (head_dim * 4 + 8); +} + +pub const Path = enum { decode, prompt }; +pub const Launch = struct { path: Path, grid: [3]u32, threads: u32, merge_grid: [3]u32, partials_rh: u32, subs: u32 = 1 }; +pub fn attend(r: Rows, l: Layer, stride: u32, slots: usize) error{Inkling2Partials}!Launch { + if (slotsFor(l, @as(usize, r.last_pos) + 1) > stride) return error.Inkling2Partials; + 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; + return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, stride }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride }; + } + return .{ .path = .decode, .grid = .{ r.rows * r.heads, stride, 1 }, .threads = decode_threads, .merge_grid = merge_grid, .partials_rh = stride }; +} + +test { + _ = @import("attention_test.zig"); +} diff --git a/zig/src/families/inkling2/metal/attention_test.zig b/zig/src/families/inkling2/metal/attention_test.zig new file mode 100644 index 00000000000..3a8e73a3deb --- /dev/null +++ b/zig/src/families/inkling2/metal/attention_test.zig @@ -0,0 +1,63 @@ +//! Host-only Mini window, ring, tau and dispatch/ABI checks; no Metal import. +const std = @import("std"); +const p = @import("attention_plan.zig"); +const t = std.testing; + +fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} + +test "inkling2 metal ABI matches the shaders" { + try t.expectEqual(@as(usize, 24), @sizeOf(p.Seg)); + try t.expectEqual(@as(usize, 36), @sizeOf(p.PrepArgs)); + try t.expectEqual(@as(usize, 24), @sizeOf(p.MergeArgs)); + try t.expectEqual(@as(usize, 28), @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); +} + +test "inkling2 metal Mini ring and window boundaries" { + try t.expectEqual(@as(u32, 1024), p.ringFor(1024, 1)); + 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(usize, 1023), @as(usize, 8191) % 1024); + try t.expectEqual(@as(usize, 0), @as(usize, 8192) % 8192); +} + +test "inkling2 metal tau starts strictly above its 8192 floor" { + try t.expectEqual(@as(f64, 1), tau(0)); + try t.expectEqual(@as(f64, 1), tau(8191)); + try t.expect(tau(8192) > 1); + try t.expectApproxEqAbs(1 + 0.1 * @log(@as(f64, 2)), tau(16383), 1e-15); +} + +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); + try t.expectEqual(p.Path.decode, sd.path); + try t.expectEqual([3]u32{ 192, 5, 1 }, sd.grid); + try t.expectEqual([3]u32{ 192, 1, 1 }, sd.merge_grid); + try t.expectEqual(@as(u32, 32), sd.threads); + const gl = p.Layer.global(1048576); + 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); + try t.expectEqual([3]u32{ 1, 8, 64 }, gd.grid); + try t.expectEqual(@as(u32, 256), gd.threads); + const streamed = p.Rows{ .rows = 1, .last_pos = 1048575, .streams = 2 }; + const scalar = try p.attend(streamed, gl, 64, 0); + try t.expectEqual(p.Path.decode, scalar.path); + try t.expectEqual([3]u32{ 24, 64, 1 }, scalar.grid); + try t.expectError(error.Inkling2Partials, p.attend(streamed, gl, 63, 0)); + const prompt = try p.attend(.{ .rows = 130, .last_pos = 20000 }, gl, 2, 130 * 24 * 2); + try t.expectEqual(p.Path.prompt, prompt.path); + try t.expectEqual([3]u32{ 4, 8, 2 }, prompt.grid); // ceil(130 * 3 / 128) +} diff --git a/zig/src/families/inkling2/metal/dspark_fold.zig b/zig/src/families/inkling2/metal/dspark_fold.zig new file mode 100644 index 00000000000..04b5a787a05 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_fold.zig @@ -0,0 +1,103 @@ +//! One-time binary64 folding of DSpark's rank-256 hidden head into the target unembedding. +const std = @import("std"); +const bf = @import("bf16_round"); + +pub const hidden = 2304; +pub const rank = 256; +pub const vocabulary = 201024; + +pub fn value(h: u16) f64 { + const x: f32 = @bitCast(@as(u32, h) << 16); + return x; +} + +/// The reference's binary64 dot, rounded once through binary32 to BF16. +pub fn dot(u: []const f64, w: []const f64) u16 { + std.debug.assert(u.len == w.len); + var sum: f64 = 0; + for (u, w) |x, y| sum += x * y; + return bf.bits(@floatCast(sum)); +} + +const Work = struct { + unembed: []const u16, + hidden_w: []const f64, + hidden_b: []const f64, + phi: []u16, + beta: []u16, + begin: usize, + end: usize, + + fn run(w: *const Work) void { + var u: [hidden]f64 = undefined; + for (w.begin..w.end) |v| { + for (&u, w.unembed[v * hidden ..][0..hidden]) |*x, h| x.* = value(h); + for (0..rank) |r| w.phi[v * rank + r] = dot(&u, w.hidden_w[r * hidden ..][0..hidden]); + w.beta[v] = dot(&u, w.hidden_b); + } + } +}; + +/// Φ[v,r] = bf16(f32(f64(U[v]) · f64(hidden_out[:,r]))), β[v] likewise for its bias. +pub fn fold( + a: std.mem.Allocator, + unembed: []const u16, + hidden_weight: []const u16, + hidden_bias: []const u16, + phi: []u16, + beta: []u16, +) !void { + const v = beta.len; + if (unembed.len != v * hidden or hidden_weight.len != hidden * rank or hidden_bias.len != hidden or phi.len != v * rank or v == 0) + return error.DSparkFoldShape; + const hw = try a.alloc(f64, hidden * rank); + defer a.free(hw); + const hb = try a.alloc(f64, hidden); + defer a.free(hb); + for (hidden_weight, 0..) |h, i| hw[(i % rank) * hidden + i / rank] = value(h); + for (hb, hidden_bias) |*x, h| x.* = value(h); + + const count = @min(@as(usize, 8), v); + const chunk = (v + count - 1) / count; + var work: [8]Work = undefined; + var threads: [8]?std.Thread = @splat(null); + for (0..count) |i| { + const begin = @min(i * chunk, v); + const end = @min(begin + chunk, v); + work[i] = .{ .unembed = unembed, .hidden_w = hw, .hidden_b = hb, .phi = phi, .beta = beta, .begin = begin, .end = end }; + threads[i] = std.Thread.spawn(.{}, Work.run, .{&work[i]}) catch null; + if (threads[i] == null) work[i].run(); + } + for (threads) |thread| if (thread) |t| t.join(); +} + +test "the binary64 fold does not collapse a discriminating binary32 intermediate" { + var u: [4]f64 = @splat(0); + u[0] = 1; + u[1] = 0x1p-8; + u[2] = 0x1p-24; + u[3] = 0x1p-24; + const w: [4]f64 = @splat(1); + const got = bf.value(dot(&u, &w)); + try std.testing.expectEqual(@as(f32, 1.0078125), got); + var sum: f32 = 0; + for (u, w) |x, y| sum += @as(f32, @floatCast(x * y)); + try std.testing.expectEqual(@as(f32, 1), bf.value(bf.bits(sum))); +} + +test "fold checks every published shape" { + var u: [hidden]u16 = @splat(0); + var w: [hidden * rank]u16 = @splat(0); + var p: [rank]u16 = undefined; + var b: [1]u16 = undefined; + try std.testing.expectError(error.DSparkFoldShape, fold(std.testing.allocator, &.{}, &w, &u, &p, &b)); + try fold(std.testing.allocator, &u, &w, &u, &p, &b); + for (p) |x| try std.testing.expectEqual(@as(u16, 0), x); + try std.testing.expectEqual(@as(u16, 0), b[0]); + u[1] = bf.bits(1); + w[rank + 2] = bf.bits(1); // hidden row 1, rank column 2 in the checkpoint's row-major layout + try fold(std.testing.allocator, &u, &w, &u, &p, &b); + try std.testing.expectEqual(bf.bits(1), p[2]); + try std.testing.expectEqual(bf.bits(1), b[0]); + for (p, 0..) |x, r| if (r != 2) try std.testing.expectEqual(@as(u16, 0), x); +} diff --git a/zig/src/families/inkling2/metal/dspark_kernels.zig b/zig/src/families/inkling2/metal/dspark_kernels.zig new file mode 100644 index 00000000000..4c7126c6ad9 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_kernels.zig @@ -0,0 +1,224 @@ +//! Mini DSpark's fixed-shape arithmetic: Metal entry points and exact launch ABIs. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); + +pub const hidden: u32 = 2304; +pub const query_width: u32 = 3072; +pub const kv_width: u32 = 1024; +pub const block_rows: u32 = 8; +pub const rank: u32 = 256; +pub const rnn_width: u32 = 768; +pub const intermediate: u32 = 9216; +pub const vocab: u32 = 200058; +pub const Ref = @import("inkling2_metal_ref").Ref; +pub const PositionArgs = extern struct { base: u32 }; +pub const ContextArgs = extern struct { base: u32, rows: u32, ring: u32 }; +pub const AttentionArgs = extern struct { committed: u32, ring: u32, local: u32, from: u32 }; +pub const TokenArgs = extern struct { token: u32 }; +pub const CountArgs = extern struct { count: u32 }; +pub const BaseArgs = extern struct { rows: u32, vocab: u32 }; + +/// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) @truncate((bits >> 16) | 0x40) else @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +/// Rotate-half RoPE partner is d+64 below the midpoint and d-64 above it. +pub fn ropeRotateHalf(x: f32, other: f32, d: u32, angle: f32) f32 { + return if (d < 64) x * @cos(angle) - other * @sin(angle) else other * @sin(angle) + x * @cos(angle); +} + +/// Every recurrent blend operation rounds independently to model precision. +pub fn recurrentBlend(gamma: f32, candidate: f32, previous: f32) f64 { + const keep: f32 = @floatCast(roundBf16(@as(f32, 1.0 - gamma))); + const left: f32 = @floatCast(roundBf16(@as(f32, gamma * previous))); + const right: f32 = @floatCast(roundBf16(@as(f32, keep * candidate))); + return roundBf16(@as(f32, left + right)); +} + +/// Folded bias and base each round before the target-style softcap. +pub fn foldedLogit(base_value: f32, beta: f32, dot: f32) f64 { + const bias: f32 = @floatCast(roundBf16(@as(f32, beta + dot))); + const logit: f32 = @floatCast(roundBf16(@as(f32, base_value + bias))); + return roundBf16(@as(f32, 30.0) * std.math.tanh(logit / @as(f32, 30.0))); +} +pub const ResidualArgs = extern struct { init: u32 }; + +pub const Kind = enum { + init_rows, + fuse_taps, + block_qkv, + context_kv, + attention, + residual_norm, + swiglu, + kappa, + recurrent, + base, + logits, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .init_rows => "tf_ink2_dspark_init_rows", + .fuse_taps => "tf_ink2_dspark_fuse_taps", + .block_qkv => "tf_ink2_dspark_block_qkv", + .context_kv => "tf_ink2_dspark_context_kv", + .attention => "tf_ink2_dspark_attention", + .residual_norm => "tf_ink2_dspark_residual_norm", + .swiglu => "tf_ink2_dspark_swiglu", + .kappa => "tf_ink2_dspark_kappa", + .recurrent => "tf_ink2_dspark_recurrent", + .base => "tf_ink2_dspark_base", + .logits => "tf_ink2_dspark_logits", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + inline else => |v| std.fmt.comptimePrint("metal inkling2 dspark {s} {s}", .{ @tagName(v), comptime v.symbol() }), + }; + } +}; + +pub const Pipelines = struct { + init_rows: mtl.Pipeline, + fuse_taps: mtl.Pipeline, + block_qkv: mtl.Pipeline, + context_kv: mtl.Pipeline, + attention: mtl.Pipeline, + residual_norm: mtl.Pipeline, + swiglu: mtl.Pipeline, + kappa: mtl.Pipeline, + recurrent: mtl.Pipeline, + base: mtl.Pipeline, + logits: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.inkling2_dspark); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var loaded: usize = 0; + errdefer inline for (@typeInfo(Pipelines).@"struct".field_names, 0..) |name, i| { + if (loaded > i) @field(out, name).deinit(); + }; + inline for (@typeInfo(Pipelines).@"struct".field_names, 0..) |name, i| { + @field(out, name) = try mtl.Pipeline.init(device, lib, @as(Kind, @fromBackingInt(@intCast(i))).symbol(), false); + loaded += 1; + } + return out; + } + pub fn deinit(p: *Pipelines) void { + inline for (@typeInfo(Pipelines).@"struct".field_names) |name| @field(p, name).deinit(); + p.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} +fn groups(e: mtl.ComputeEncoder, count: usize, width: usize) void { + e.dispatchGroups(mtl.Size.of(count, 1, 1), mtl.Size.of(width, 1, 1)); +} +fn threads(e: mtl.ComputeEncoder, count: usize, width: usize) void { + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(width, 1, 1)); +} + +/// Row zero copies the target's normalized anchor; the other seven rows copy the raw mask embedding. +pub fn initializeRows(p: *const Pipelines, e: mtl.ComputeEncoder, anchor: Ref, mask_embed: Ref, out: Ref) void { + e.setPipeline(p.init_rows); + bind(e, &.{ anchor, mask_embed, out }); + groups(e, block_rows, 256); +} + +/// Input taps are [row][tap][H], output c is [fusion][row][H], and newest_f is one [H] row. +pub fn fuseTaps(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, fuse_weight: Ref, norm_weight: Ref, c: Ref, newest_f: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.fuse_taps); + bind(e, &.{ taps, fuse_weight, norm_weight, c, newest_f }); + e.setValue(CountArgs{ .count = rows }, 5); + groups(e, 4 * @as(usize, rows), 256); +} + +/// Raw projections become per-head RMS-normalized rotate-half Q/K and an unchanged BF16 V. +pub fn blockQkv(p: *const Pipelines, e: mtl.ComputeEncoder, q_raw: Ref, k_raw: Ref, v_raw: Ref, q_norm: Ref, k_norm: Ref, q: Ref, k: Ref, v: Ref, base_position: u32) void { + e.setPipeline(p.block_qkv); + bind(e, &.{ q_raw, k_raw, v_raw, q_norm, k_norm, q, k, v }); + e.setValue(PositionArgs{ .base = base_position }, 8); + groups(e, 8 * 40, 128); +} + +/// Context K/V is written at absolute-position modulo ring_capacity for committed rows only. +pub fn commitContext(p: *const Pipelines, e: mtl.ComputeEncoder, k_raw: Ref, v_raw: Ref, k_norm_ctx: Ref, keys: Ref, values: Ref, base_position: u32, rows: u32, ring_capacity: u32) void { + std.debug.assert(rows > 0 and ring_capacity > 0); + e.setPipeline(p.context_kv); + bind(e, &.{ k_raw, v_raw, k_norm_ctx, keys, values }); + e.setValue(ContextArgs{ .base = base_position, .rows = rows, .ring = ring_capacity }, 5); + groups(e, @as(usize, rows) * 8, 128); +} + +/// Scores is FP32 scratch sized 8*24*(retained_context+8); global layers retain all context. +pub fn attend(p: *const Pipelines, e: mtl.ComputeEncoder, q: Ref, block_k: Ref, block_v: Ref, context_k: Ref, context_v: Ref, scores: Ref, out: Ref, committed: u32, ring_capacity: u32, local: bool, from: u32) void { + std.debug.assert(ring_capacity > 0 and from <= committed); + e.setPipeline(p.attention); + bind(e, &.{ q, block_k, block_v, context_k, context_v, scores, out }); + e.setValue(AttentionArgs{ .committed = committed, .ring = ring_capacity, .local = @intFromBool(local), .from = from }, 7); + groups(e, 8 * 24, 128); +} + +/// Normalization consumes the FP32 residual sum, independently of the rounded BF16 residual store. +pub fn residualNorm(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, residual: Ref, weight: Ref, new_residual: Ref, normalized: Ref, rows: u32, init: bool) void { + std.debug.assert(rows > 0); + e.setPipeline(p.residual_norm); + bind(e, &.{ x, residual, weight, new_residual, normalized }); + e.setValue(ResidualArgs{ .init = @intFromBool(init) }, 5); + groups(e, rows, 256); +} + +/// Gate and up projections are BF16 rows with 9216 entries; only this SwiGLU product is stored here. +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gate: Ref, up: Ref, out: Ref, count: u32) void { + std.debug.assert(count == 8 * intermediate); + e.setPipeline(p.swiglu); + bind(e, &.{ gate, up, out }); + e.setValue(CountArgs{ .count = count }, 3); + threads(e, count, 256); +} + +/// Kappa is FP32 [rows][768], using RNN columns 512..2815 for y and 2816..5119 for newest_f. +pub fn kappa(p: *const Pipelines, e: mtl.ComputeEncoder, y: Ref, newest_f: Ref, rnn_weight: Ref, rnn_bias: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 7); + e.setPipeline(p.kappa); + bind(e, &.{ y, newest_f, rnn_weight, rnn_bias, out }); + e.setValue(CountArgs{ .count = rows }, 5); + threads(e, @as(usize, rows) * rnn_width, 256); +} + +/// One recurrent step writes rounded Z, the next BF16 state and BF16 lambda for rows 1..7 in turn. +pub fn recurrentStep(p: *const Pipelines, e: mtl.ComputeEncoder, state: Ref, kappa_row: Ref, rnn_weight: Ref, markov_w1: Ref, z: Ref, next_state: Ref, lambda: Ref, previous_token: u32) void { + e.setPipeline(p.recurrent); + bind(e, &.{ state, kappa_row, rnn_weight, markov_w1, z, next_state, lambda }); + e.setValue(TokenArgs{ .token = previous_token }, 7); + threads(e, rank, 256); +} + +/// Raw U*y rows round once to BF16, with no target unembedding softcap. +pub fn base(p: *const Pipelines, e: mtl.ComputeEncoder, unembed: Ref, y: Ref, out: Ref, rows: u32, vocabulary_count: u32) void { + std.debug.assert(rows > 0 and vocabulary_count > 0 and vocabulary_count <= vocab); + e.setPipeline(p.base); + bind(e, &.{ unembed, y, out }); + e.setValue(BaseArgs{ .rows = rows, .vocab = vocabulary_count }, 3); + threads(e, @as(usize, rows) * vocabulary_count, 256); +} +/// Folded Phi/beta correction and target-style 30 tanh softcap, restricted to Mini's 200058 logits. +pub fn finalLogits(p: *const Pipelines, e: mtl.ComputeEncoder, base_values: Ref, phi: Ref, beta: Ref, lambda: Ref, out: Ref) void { + e.setPipeline(p.logits); + bind(e, &.{ base_values, phi, beta, lambda, out }); + e.setValue(CountArgs{ .count = vocab }, 5); + threads(e, vocab, 256); +} diff --git a/zig/src/families/inkling2/metal/dspark_kernels_test.zig b/zig/src/families/inkling2/metal/dspark_kernels_test.zig new file mode 100644 index 00000000000..0562997cadc --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_kernels_test.zig @@ -0,0 +1,154 @@ +//! Host-only FP64 witnesses for Mini DSpark rounding, pairing, reach and launch contracts. +const std = @import("std"); +const k = @import("dspark_kernels.zig"); +const records = @import("../../../core/contract/inkling2_dspark_metal_records.zig").records; +const shader = @import("inkling2_metal").inkling2_dspark; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} +fn bf(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) @truncate((bits >> 16) | 0x40) else @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const out: f32 = @bitCast(@as(u32, rounded) << 16); + return out; +} +fn f32v(v: f64) f64 { + return @as(f32, @floatCast(v)); +} + +test "DSpark symbols, records, ABIs and disabled contraction are exact" { + for (std.enums.values(k.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + const width: u32 = switch (kind) { + .block_qkv, .context_kv, .attention => 128, + else => 256, + }; + try t.expectEqual(width, record.threads); + try t.expectEqual(record.threads, record.reserved); + const threadgroup: u32 = switch (kind) { + .fuse_taps => 32, + .block_qkv, .context_kv, .attention, .residual_norm => 16, + else => 0, + }; + try t.expectEqual(threadgroup, record.tg_memory); + } + try t.expectEqual(@as(usize, 4), @sizeOf(k.PositionArgs)); + try t.expectEqual(@as(usize, 12), @sizeOf(k.ContextArgs)); + try t.expectEqual(@as(usize, 16), @sizeOf(k.AttentionArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.ResidualArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.TokenArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.CountArgs)); + try t.expectEqual(@as(usize, 8), @sizeOf(k.BaseArgs)); + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "DSP_SCALE = 0x1.6a09e6p-7f") != null); +} + +test "raw base projection rounds the dot without applying target softcap" { + const unembed: [k.hidden]f32 = @splat(1); + const y: [k.hidden]f32 = @splat(1); + var dot: f32 = 0; + for (unembed, y) |u, v| dot += u * v; + try near(2304, bf(dot)); + try near(30, bf(30.0 * std.math.tanh(dot / 30.0))); + try t.expect(std.mem.indexOf(u8, shader, "kernel void tf_ink2_dspark_base") != null); +} + +test "fusion rounds each softmax alpha through BF16 before ordered FP32 taps" { + const weights = [_]f64{ 0, 0.5, -0.25, 2 }; + const taps = [_]f64{ 303.2126159667969, -170.3546905517578, 454.9715576171875, -93.47307586669922 }; + var expv: [4]f64 = undefined; + var den: f64 = 0; + for (weights, 0..) |w, j| { + expv[j] = @exp(w - 2); + den += expv[j]; + } + var rounded: f32 = 0; + var raw: f32 = 0; + for (0..4) |j| { + const a = f32v(expv[j] / f32v(den)); + const alpha: f32 = @floatCast(bf(a)); + rounded += alpha * @as(f32, @floatCast(taps[j])); + raw += @as(f32, @floatCast(a)) * @as(f32, @floatCast(taps[j])); + } + try t.expect(bf(rounded) != bf(raw)); + var ordered: f32 = 0; + for (0..4) |j| ordered += @as(f32, @floatCast(bf(f32v(expv[j] / f32v(den))))) * @as(f32, @floatCast(taps[j])); + try t.expectEqual(ordered, rounded); +} + +test "residual normalized output sees sigma rather than rounded BF16 storage" { + const x: f32 = 1.0; + const res: f32 = 0.00390625; + const sigma: f32 = x + res; + const stored = bf(sigma); + const weight = 0.0; + const scale: f32 = 1.00390625; + const from_sigma = bf(sigma * scale); + const from_store = bf(@as(f32, @floatCast(stored)) * scale); + try t.expect(from_sigma != from_store); + try near(@as(f64, weight) + 1, 1.0); +} + +test "rotate-half RoPE pairs d with d plus 64 at absolute positions" { + const x = [_]f64{ 1, 2 }; + const angle = std.math.pi / 2.0; + const first = x[0] * @cos(angle) - x[1] * @sin(angle); + const second = x[0] * @sin(angle) + x[1] * @cos(angle); + try near(-2, first); + try near(1, second); + try t.expect(@abs(second - (-1)) > 1); + try t.expect(@abs(k.ropeRotateHalf(1, 2, 0, @floatCast(angle)) - @as(f32, @floatCast(first))) < 2e-6); + try t.expect(@abs(k.ropeRotateHalf(2, 1, 64, @floatCast(angle)) - @as(f32, @floatCast(second))) < 2e-6); +} + +test "local reach starts at committed minus 1024 without crossing a restored lower bound" { + const committed: usize = 1027; + const from: usize = 5; + const local_first = @max(from, committed - 1024); + const global_first = from; + try t.expectEqual(@as(usize, 5), local_first); + try t.expectEqual(@as(usize, 1022 + 8), committed - local_first + 8); + try t.expectEqual(committed - from + 8, committed - global_first + 8); + for (0..8) |row| { + const position = 5000 + row; + try t.expectEqual(position, 5000 + row); + } +} + +test "recurrence rounds z activations and every state operation through BF16" { + const gamma: f32 = @floatCast(bf(@as(f32, 0.431640625))); + const candidate: f32 = @floatCast(bf(@as(f32, 0.030029296875))); + const previous: f32 = -14.5625; + const keep: f32 = @floatCast(bf(1.0 - gamma)); + const left: f32 = @floatCast(bf(gamma * previous)); + const right: f32 = @floatCast(bf(keep * candidate)); + const stepped = bf(left + right); + const unrounded = bf(@as(f32, gamma) * previous + (1.0 - @as(f32, gamma)) * candidate); + try t.expect(stepped != unrounded); + try near(stepped, bf(@as(f32, left + right))); + try near(stepped, k.recurrentBlend(gamma, candidate, previous)); + const z = bf(@as(f32, 0.33333334)); + const lambda = bf(std.math.tanh(z)); + try near(lambda, bf(std.math.tanh(z))); +} + +test "folded correction rounds bias then logits before the thirty softcap" { + const beta: f32 = 0.125; + const dot: f32 = 0.0001; + const base: f32 = 40.0; + const bias: f32 = @floatCast(bf(beta + dot)); + const logit: f32 = @floatCast(bf(base + bias)); + const capped = bf(30.0 * std.math.tanh(logit / 30.0)); + const uncapped = bf(@as(f32, 30.0) * @as(f32, @floatCast(std.math.tanh(logit / 30.0)))); + try near(capped, uncapped); + try near(capped, k.foldedLogit(base, beta, dot)); + const no_bias_round: f32 = @floatCast(bf(base + (beta + dot))); + try t.expect(logit != no_bias_round); + try t.expect(@abs(capped) < @abs(logit)); + const saturated = bf(30.0 * std.math.tanh(@as(f64, 1000) / 30.0)); + try t.expect(saturated <= 30 and saturated > 29.9); +} diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig new file mode 100644 index 00000000000..268ca0398ea --- /dev/null +++ b/zig/src/families/inkling2/metal/experts.zig @@ -0,0 +1,124 @@ +//! Real Metal dispatch for Inkling 2 Mini's M3 NVFP4/MXFP8 routed experts. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); +const plan = @import("experts_plan.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Format = plan.Format; +pub const Call = plan.Call; +pub const Operation = enum { nvfp4_gu, nvfp4_down, mxfp8_gu, mxfp8_down, nvfp4_quantize, mxfp8_quantize, combine }; + +pub const function_names = [_][:0]const u8{ + "tf_ink2_nvfp4_gu", + "tf_ink2_nvfp4_down", + "tf_ink2_mxfp8_gu", + "tf_ink2_mxfp8_down", + "tf_ink2_nvfp4_quantize", + "tf_ink2_mxfp8_quantize", + "tf_ink2_combine", +}; + +pub const Pipelines = struct { + entries: [function_names.len]mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, src.experts); + } + + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var made: usize = 0; + errdefer for (out.entries[0..made]) |pipe| pipe.deinit(); + for (function_names, 0..) |name, i| { + out.entries[i] = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + if (out.entries[i].maxThreads() < 32) return error.ExpertThreads; + } + return out; + } + + pub fn deinit(p: *Pipelines) void { + for (p.entries) |pipe| pipe.deinit(); + } + + fn get(p: *const Pipelines, op: Operation) mtl.Pipeline { + return p.entries[@backingInt(op)]; + } +}; + +fn args(c: Call) plan.MatrixArgs { + return .{ .k = c.k, .n = c.n, .topk = c.topk, .experts = c.experts }; +} + +fn launch(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, groups: u32) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1)); +} + +/// Packed NVFP4 GU: X [rows,k], ids [rows,topk], Y [rows*topk,n]. +pub fn nvfp4Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .nvfp4) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ x, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 7); + launch(p, e, .nvfp4_gu, plan.geometry(c).groups); +} + +/// Packed MXFP8 GU with UE8M0 scales per row/block32. +pub fn mxfp8Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .mxfp8) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ x, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 5); + launch(p, e, .mxfp8_gu, plan.geometry(c).groups); +} + +pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .nvfp4) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ act, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 7); + launch(p, e, .nvfp4_down, plan.geometry(c).groups); +} + +pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .mxfp8) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ act, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 5); + launch(p, e, .mxfp8_down, plan.geometry(c).groups); +} + +/// Decode one expert matrix to BF16, not an activation quantization operation. +pub fn nvfp4Quantize(p: *const Pipelines, e: mtl.ComputeEncoder, w: Ref, scales: Ref, amax: Ref, denominator: Ref, out: Ref, rows: u32, k: u32) !void { + if (k == 0 or k % 16 != 0 or rows == 0) return error.BadExpertBlock; + for ([_]Ref{ w, scales, amax, denominator, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(plan.DecodeArgs{ .rows = rows, .k = k }, 5); + launch(p, e, .nvfp4_quantize, (rows * k + 31) / 32); +} + +pub fn mxfp8Quantize(p: *const Pipelines, e: mtl.ComputeEncoder, w: Ref, scales: Ref, out: Ref, rows: u32, k: u32) !void { + if (k == 0 or k % 32 != 0 or rows == 0) return error.BadExpertBlock; + for ([_]Ref{ w, scales, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(plan.DecodeArgs{ .rows = rows, .k = k }, 3); + launch(p, e, .mxfp8_quantize, (rows * k + 31) / 32); +} + +/// Sum per-token BF16 down outputs in ascending expert index and round once to BF16. +pub fn combine(p: *const Pipelines, e: mtl.ComputeEncoder, down: Ref, ids: Ref, weights: Ref, out: Ref, c: Call) !void { + try plan.check(c); + for ([_]Ref{ down, ids, weights, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 4); + // Combine has one group per token, rather than one per route pair. + launch(p, e, .combine, c.rows); +} + +pub fn gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, ids: Ref, out: Ref, c: Call) !void { + switch (c.format) { + .nvfp4 => if (nv_globals) |g| return nvfp4Gu(p, e, x, w, scales, g.amax, g.denominator, ids, out, c) else return error.MissingNvfp4Globals, + .mxfp8 => return mxfp8Gu(p, e, x, w, scales, ids, out, c), + } +} diff --git a/zig/src/families/inkling2/metal/experts_plan.zig b/zig/src/families/inkling2/metal/experts_plan.zig new file mode 100644 index 00000000000..6b98f9fe18a --- /dev/null +++ b/zig/src/families/inkling2/metal/experts_plan.zig @@ -0,0 +1,102 @@ +//! Pure M3 layout, decode and activation math shared by the host and its scalar tests. +const std = @import("std"); + +pub const hidden: u32 = 2304; +pub const intermediate: u32 = 1152; +pub const expert_count: u32 = 128; +pub const top_k: u32 = 8; + +pub const Format = enum { + nvfp4, + mxfp8, + + pub fn block(f: Format) u32 { + return if (f == .nvfp4) 16 else 32; + } + pub fn codeBytes(f: Format, k: u32) u32 { + return if (f == .nvfp4) k / 2 else k; + } +}; + +pub const Call = struct { + rows: u32, + k: u32, + n: u32, + experts: u32 = expert_count, + topk: u32 = top_k, + format: Format, +}; + +pub const Geometry = struct { + groups: u32, + threads: u32 = 32, +}; + +pub fn geometry(c: Call) Geometry { + return .{ .groups = c.rows * c.topk }; +} + +pub fn check(c: Call) !void { + if (c.rows == 0 or c.k == 0 or c.n == 0 or c.experts == 0 or c.topk == 0 or c.topk > c.experts) + return error.BadExpertShape; + if (c.k % c.format.block() != 0 or (c.format == .nvfp4 and c.k % 2 != 0)) + return error.BadExpertBlock; +} + +pub fn formatForLayer(layer: u32) !Format { + if (layer < 20) return .nvfp4; + if (layer < 24) return .mxfp8; + return error.BadExpertLayer; +} + +pub fn roundBf16(v: f32) f32 { + const bits: u32 = @bitCast(v); + const rounded: u16 = if (std.math.isNan(v)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + return @bitCast(@as(u32, rounded) << 16); +} + +pub fn e2m1(code: u8) f32 { + const values = [_]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = values[code & 7]; + return if (code & 8 != 0) -v else v; +} + +pub fn e4m3(code: u8) f32 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f32); + const value = if (exponent == 0) + @as(f32, @floatFromInt(mantissa)) / 512.0 + else + std.math.ldexp(@as(f32, 1) + @as(f32, @floatFromInt(mantissa)) / 8.0, @as(i32, exponent) - 7); + return if (code & 0x80 != 0) -value else value; +} + +pub fn phi(amax: f32, denominator: f32) f32 { + return roundBf16(amax) / roundBf16(denominator); +} + +pub fn nvWeight(codes: u8, column: u32, scale: u8, factor: f32) f32 { + const code = if (column & 1 != 0) codes >> 4 else codes & 15; + return roundBf16(e2m1(code) * e4m3(scale) * factor); +} + +pub fn mxWeight(value: u8, scale: u8) f32 { + return roundBf16(std.math.ldexp(e4m3(value), @as(i32, scale) - 127)); +} + +pub fn softcap(x: f32, cap: f32) f32 { + return @floatCast(@as(f64, cap) * std.math.tanh(@as(f64, x) / @as(f64, cap))); +} + +/// Inputs are the two already-BF16-rounded GU results; the result rounds once at the end. +pub fn swiglu(gate: f32, up: f32) f32 { + const left = softcap(gate, 4) * (1 / (1 + std.math.exp(-gate))); + return roundBf16(left * softcap(up, 25)); +} + +pub const MatrixArgs = extern struct { k: u32, n: u32, topk: u32, experts: u32 }; +pub const DecodeArgs = extern struct { rows: u32, k: u32 }; diff --git a/zig/src/families/inkling2/metal/experts_test.zig b/zig/src/families/inkling2/metal/experts_test.zig new file mode 100644 index 00000000000..4ae2612b76f --- /dev/null +++ b/zig/src/families/inkling2/metal/experts_test.zig @@ -0,0 +1,144 @@ +//! Host-only M3 format, layout, BF16-rounding and dispatch-geometry tests. +const std = @import("std"); +const p = @import("experts_plan.zig"); + +fn bf16Chain(terms: []const f32, stride: usize, first: usize) f32 { + var sum: f32 = 0; + var i = first; + while (i < terms.len) : (i += stride) sum = p.roundBf16(sum + p.roundBf16(terms[i])); + return sum; +} + +fn bf16Halves(terms: []const f32) f32 { + if (terms.len == 0) return 0; + if (terms.len == 1) return p.roundBf16(terms[0]); + const mid = terms.len / 2; + return p.roundBf16(bf16Halves(terms[0..mid]) + bf16Halves(terms[mid..])); +} + +fn bf16Strided(terms: []const f32) f32 { + var lanes: [32]f32 = @splat(0); + for (&lanes, 0..) |*lane, i| lane.* = bf16Chain(terms, 32, i); + return bf16Halves(&lanes); +} + +test "Mini layer formats and dimensions are a clean cut at layer 20" { + for (0..20) |layer| try std.testing.expectEqual(p.Format.nvfp4, try p.formatForLayer(@intCast(layer))); + for (20..24) |layer| try std.testing.expectEqual(p.Format.mxfp8, try p.formatForLayer(@intCast(layer))); + try std.testing.expectError(error.BadExpertLayer, p.formatForLayer(24)); + try std.testing.expectEqual(@as(u32, 2304), p.hidden); + try std.testing.expectEqual(@as(u32, 1152), p.intermediate); + try std.testing.expectEqual(@as(u32, 128), p.expert_count); + try std.testing.expectEqual(@as(u32, 8), p.top_k); +} + +test "every E2M1 code decodes low/high nibble and signed zero" { + const magnitude = [_]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + for (0..16) |code| { + const want = if (code & 8 != 0) -magnitude[code & 7] else magnitude[code & 7]; + try std.testing.expectEqual(want, p.e2m1(@intCast(code))); + } + const byte: u8 = 0xa7; // low 7 = 6, high 10 = -1 + try std.testing.expectEqual(@as(f32, 6), p.nvWeight(byte, 0, 0x38, 1)); + try std.testing.expectEqual(@as(f32, -1), p.nvWeight(byte, 1, 0x38, 1)); + try std.testing.expectEqual(@as(f32, 0), p.e2m1(8)); +} + +test "all E4M3 values match the independent half-bit decode" { + for (0..256) |raw| { + const code: u8 = @intCast(raw); + const h: f16 = @bitCast(@as(u16, code & 0x7f) << 7); + const magnitude = @as(f32, h) * 256; + const want = if ((code & 0x80) != 0) -magnitude else magnitude; + const got = p.e4m3(code); + // E4M3FN reserves 0x7f for NaN; the half-bit helper alone does not encode that case. + if ((code & 0x7f) == 0x7f) { + try std.testing.expect(std.math.isNan(got)); + } else try std.testing.expectEqual(want, got); + } +} + +test "NVFP4 globals round to BF16 before one FP32 division" { + const amax: f32 = @bitCast(@as(u32, 0x3f80_8001)); + const den: f32 = @bitCast(@as(u32, 0x4534_0001)); + const rounded_den = p.roundBf16(den); + try std.testing.expect(den != rounded_den); + try std.testing.expectEqual(p.roundBf16(amax) / rounded_den, p.phi(amax, den)); + try std.testing.expect(p.phi(amax, den) != amax / den); // A2: the reference rounds both loader inputs. + const raw = p.e2m1(7) * p.e4m3(0x40) * p.phi(amax, den); + try std.testing.expectEqual(p.roundBf16(raw), p.nvWeight(7, 0, 0x40, p.phi(amax, den))); +} + +test "every MXFP8 value and UE8M0 exponent is exactly BF16 decoded" { + for ([_]u8{ 0, 1, 126, 127, 128, 129, 254, 255 }) |scale| for (0..256) |raw| { + const code: u8 = @intCast(raw); + const want = std.math.ldexp(p.e4m3(code), @as(i32, scale) - 127); + if (std.math.isNan(want)) { + try std.testing.expect(std.math.isNan(p.mxWeight(code, scale))); + } else try std.testing.expectEqual(p.roundBf16(want), p.mxWeight(code, scale)); + }; +} + +test "GU BF16 round precedes cap sigmoid cap and final BF16 activation" { + const raw_gate: f32 = -10; + const raw_up: f32 = -9.4; + const g = p.roundBf16(raw_gate); + const u = p.roundBf16(raw_up); + const capped_g: f64 = 4 * std.math.tanh(@as(f64, g) / 4); + const sigmoid: f64 = 1 / (1 + @exp(-@as(f64, g))); + const capped_u: f64 = 25 * std.math.tanh(@as(f64, u) / 25); + const wide = capped_g * sigmoid * capped_u; + try std.testing.expectEqual(@as(f32, @floatCast(@import("bf16_round").bf16(wide))), p.swiglu(g, u)); + try std.testing.expect(p.swiglu(raw_gate, raw_up) != p.swiglu(g, u)); +} + +test "combine route control overflows slot order while ascending experts remain finite" { + const values = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + const weights = [_]f32{ 0x1p127, 0x1p126, -0x1p127 / 3.0, 0.25, -0.2, 1.0 / 3.0, -2.0 / 7.0, 0.375 }; + var terms: [8]f32 = undefined; + for (&terms, values, weights) |*term, value, weight| term.* = value * weight; + var route_sum: f32 = 0; + for (terms) |term| route_sum += term; + try std.testing.expect(std.math.isInf(route_sum) and route_sum > 0); + + const ids = [_]i32{ 2, 0, 1, 7, 3, 6, 4, 5 }; + var expert_sum: f32 = 0; + for (0..8) |expert| for (0..8) |slot| if (ids[slot] == expert) { + expert_sum += terms[slot]; + }; + try std.testing.expect(std.math.isFinite(expert_sum) and expert_sum > 0); +} + +test "eight-term combine stress separates FP32 and BF16 in every contract order" { + const terms = [_]f32{ 1024, 1, 1, 1, 1, 1, 1, -1029 }; + var forward: f32 = 0; + var reverse: f32 = 0; + for (terms) |term| forward += term; + for (1..terms.len + 1) |n| reverse += terms[terms.len - n]; + try std.testing.expectEqual(@as(f32, 1), forward); + try std.testing.expectEqual(@as(f32, 1), reverse); + + const reduced = [_]f32{ bf16Chain(&terms, 1, 0), bf16Halves(&terms), bf16Strided(&terms) }; + for (reduced) |sum| try std.testing.expectEqual(@as(f32, -8), sum); + const exact_allowance = (3 * 0x1p-24 + 0x1p-8) + 0x1p-38; + try std.testing.expect(9.0 / exact_allowance >= 100); +} + +test "launch geometry is 32 scalar threads and validates block/layout edges" { + const nv = p.Call{ .rows = 3, .k = 2304, .n = 1152, .format = .nvfp4 }; + try p.check(nv); + try std.testing.expectEqual(@as(u32, 24), p.geometry(nv).groups); + try std.testing.expectEqual(@as(u32, 32), p.geometry(nv).threads); + const mx = p.Call{ .rows = 1, .k = 1152, .n = 2304, .format = .mxfp8 }; + try p.check(mx); + var bad = nv; + bad.k = 17; + try std.testing.expectError(error.BadExpertBlock, p.check(bad)); + bad = nv; + bad.topk = 129; + try std.testing.expectError(error.BadExpertShape, p.check(bad)); + try std.testing.expectEqual(@as(usize, 16), @sizeOf(p.MatrixArgs)); + try std.testing.expectEqual(@as(usize, 8), @sizeOf(p.DecodeArgs)); + try std.testing.expectEqual(@as(usize, 0), @offsetOf(p.MatrixArgs, "k")); + try std.testing.expectEqual(@as(usize, 12), @offsetOf(p.MatrixArgs, "experts")); +} diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig new file mode 100644 index 00000000000..dd74a1735a5 --- /dev/null +++ b/zig/src/families/inkling2/metal/glue.zig @@ -0,0 +1,146 @@ +//! Inkling 2 Mini glue on Metal: the production shader and its real encoder dispatches. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +pub const plan = @import("inkling2_glue_plan"); + +pub const hidden: u32 = 2304; +pub const experts: u32 = 128; +pub const intermediate: u32 = 1152; +pub const top: u32 = 8; +pub const Ref = @import("inkling2_metal_ref").Ref; +const unit = mtl.Size.of(32, 1, 1); + +pub const Pipelines = struct { + embed_norm: mtl.Pipeline, + ar: mtl.Pipeline, + conv_static: mtl.Pipeline, + conv_dynamic: mtl.Pipeline, + router: mtl.Pipeline, + swiglu: mtl.Pipeline, + logits: mtl.Pipeline, + expert_pick: mtl.Pipeline, + expert_combine: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.glue); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: [9]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for ([_][]const u8{ + "tf_inkling2_embed_norm", + "tf_inkling2_ar", + "tf_inkling2_conv_static", + "tf_inkling2_conv_dynamic", + "tf_inkling2_router", + "tf_inkling2_swiglu", + "tf_inkling2_logits", + "tf_inkling2_expert_pick", + "tf_inkling2_expert_combine", + }, &pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ + .embed_norm = pipes[0], + .ar = pipes[1], + .conv_static = pipes[2], + .conv_dynamic = pipes[3], + .router = pipes[4], + .swiglu = pipes[5], + .logits = pipes[6], + .expert_pick = pipes[7], + .expert_combine = pipes[8], + }; + } + pub fn deinit(p: *Pipelines) void { + inline for (@typeInfo(Pipelines).@"struct".field_names) |name| @field(p, name).deinit(); + } +}; + +const EmbedArgs = extern struct { rows: u32 }; +pub fn embedNorm(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, table: Ref, weight: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.embed_norm); + inline for (.{ ids, table, weight, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(EmbedArgs{ .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ARArgs = extern struct { sources: u32, queries: u32 }; +/// sources = completed BF16 blocks plus one unrounded F32 partial; output is one FP32 row per query. +pub fn ar(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, queries: Ref, out: Ref, sources_: u32, queries_: u32) void { + std.debug.assert(sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3); + 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_ }, 4); + e.dispatchGroups(mtl.Size.of(queries_, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ConvArgs = extern struct { rows: u32, channels: u32 }; +/// taps contains three old rows followed by `rows` current BF16 inputs. +pub fn convStatic(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, weight: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.conv_static); + inline for (.{ taps, weight, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(channels, rows, 1), unit); +} + +/// Dynamic static_w is [lag][channel], the opposite orientation to static convolution taps. +pub fn convDynamic(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, input: Ref, static_w: Ref, projection: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0 and channels <= 1024); + e.setPipeline(p.conv_dynamic); + inline for (.{ taps, input, static_w, projection, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 5); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const RouteArgs = extern struct { rows: u32 }; +/// Router IDs and weights are sorted by ascending expert index for the deterministic expert sum. +pub fn router(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, bias: Ref, ids: Ref, weights: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.router); + inline for (.{ x, weight, bias, ids, weights }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(RouteArgs{ .rows = rows }, 5); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ActArgs = extern struct { rows: u32, width: u32 }; +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gu: Ref, out: Ref, rows: u32, width: u32) void { + std.debug.assert(rows > 0 and width > 0); + e.setPipeline(p.swiglu); + inline for (.{ gu, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ActArgs{ .rows = rows, .width = width }, 2); + e.dispatchThreads(mtl.Size.of(width, rows, 1), unit); +} + +const LogitArgs = extern struct { rows: u32, vocab: u32 }; +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 vocab > 0 and vocab <= 200058); + e.setPipeline(p.logits); + inline for (.{ h, unembed, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); + e.dispatchThreads(mtl.Size.of(vocab, rows, 1), unit); +} + +const ExpertArgs = extern struct { rows: u32, channels: u32 }; +pub fn expertPick(p: *const Pipelines, e: mtl.ComputeEncoder, all: Ref, ids: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.expert_pick); + inline for (.{ all, ids, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ExpertArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(8, channels, rows), unit); +} + +pub fn expertCombine(p: *const Pipelines, e: mtl.ComputeEncoder, picked: Ref, weights: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.expert_combine); + inline for (.{ picked, weights, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ExpertArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(channels, rows, 1), unit); +} diff --git a/zig/src/families/inkling2/metal/glue_plan.zig b/zig/src/families/inkling2/metal/glue_plan.zig new file mode 100644 index 00000000000..9cebaffe0ca --- /dev/null +++ b/zig/src/families/inkling2/metal/glue_plan.zig @@ -0,0 +1,250 @@ +//! Pure Inkling 2 Mini glue launch shapes and independent FP64 arithmetic. +const std = @import("std"); + +pub const hidden = 2304; +pub const expert_count = 128; +pub const intermediate = 1152; +pub const top_k = 8; +pub const ar_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); + +pub const Kind = enum { + embed_norm, + ar, + conv_static, + conv_dynamic, + router, + swiglu, + logits, + expert_pick, + expert_combine, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .embed_norm => "tf_inkling2_embed_norm", + .ar => "tf_inkling2_ar", + .conv_static => "tf_inkling2_conv_static", + .conv_dynamic => "tf_inkling2_conv_dynamic", + .router => "tf_inkling2_router", + .swiglu => "tf_inkling2_swiglu", + .logits => "tf_inkling2_logits", + .expert_pick => "tf_inkling2_expert_pick", + .expert_combine => "tf_inkling2_expert_combine", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .embed_norm => "metal inkling2 glue embed_norm tf_inkling2_embed_norm", + .ar => "metal inkling2 glue ar tf_inkling2_ar", + .conv_static => "metal inkling2 glue conv_static tf_inkling2_conv_static", + .conv_dynamic => "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", + .router => "metal inkling2 glue router tf_inkling2_router", + .swiglu => "metal inkling2 glue swiglu tf_inkling2_swiglu", + .logits => "metal inkling2 glue logits tf_inkling2_logits", + .expert_pick => "metal inkling2 glue expert_pick tf_inkling2_expert_pick", + .expert_combine => "metal inkling2 glue expert_combine tf_inkling2_expert_combine", + }; + } +}; + +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) 1024 else hidden; + if (c.rows == 0 or c.rows > 64) return false; + return switch (kind) { + .embed_norm => c.k == hidden and c.n == hidden, + .router => c.k == hidden and c.n == top_k, + .logits => c.k == hidden and c.n > 0 and c.n <= 200058, + .ar => c.k == hidden and c.n == hidden and c.rows >= 2 and c.rows <= 5, + .conv_static, .conv_dynamic, .expert_combine => c.k == key_depth and c.n > 0 and c.n <= max_width, + .swiglu => c.k == 2 and c.n > 0 and c.n <= intermediate, + .expert_pick => c.k == top_k and c.n > 0 and c.n <= hidden, + }; +} +pub fn count(kind: Kind, c: Call) usize { + const copies: usize = if (kind == .expert_pick) top_k else 1; + return c.rows * c.n * copies; +} + +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} +pub fn cap(x: f64, c: f64) f64 { + return c * std.math.tanh(x / c); +} +pub fn sigmoid(x: f64) f64 { + return 1 / (1 + std.math.exp(-x)); +} + +/// One normalized BF16 embedding result, before its final BF16 store. +pub fn embedValue(x: []const f32, weight: []const f32, d: usize) f64 { + var ss: f64 = 0; + for (x) |v| ss += @as(f64, v) * v; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(x.len)) + 1e-6); + return @as(f64, weight[d]) * (@as(f64, x[d]) * inv); +} + +/// Accumulation alternatives for the AR host model. Null means the independent FP64 oracle. +pub const ArAccum = enum { none, f32, f16, bf16 }; +pub const ArOrder = enum { sequential, pairwise, strided }; +pub const ArSum = struct { accum: ArAccum, order: ArOrder }; + +fn arRound(v: f64, accum: ArAccum) f64 { + return switch (accum) { + .none => v, + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => roundBf16(v), + }; +} +fn arChain(terms: []const f64, sim: ArSum, stride: usize, first: usize) f64 { + var total: f64 = 0; + var i = first; + while (i < terms.len) : (i += stride) total = arRound(total + arRound(terms[i], sim.accum), sim.accum); + return total; +} +fn arHalves(terms: []const f64, sim: ArSum) f64 { + if (terms.len == 0) return 0; + if (terms.len == 1) return arRound(terms[0], sim.accum); + const mid = terms.len / 2; + return arRound(arHalves(terms[0..mid], sim) + arHalves(terms[mid..], sim), sim.accum); +} +fn arSumIn(terms: []const f64, sim: ?ArSum) f64 { + if (sim) |s| return switch (s.order) { + .sequential => arChain(terms, s, 1, 0), + .pairwise => arHalves(terms, s), + .strided => blk: { + var lanes: [32]f64 = @splat(0); + for (&lanes, 0..) |*lane, i| lane.* = arChain(terms, s, 32, i); + break :blk arHalves(&lanes, s); + }, + }; + var total: f64 = 0; + for (terms) |term| total += term; + return total; +} + +/// Squares for one AR RMS reduction, optionally under a precision/order model. +pub fn arSourceSquares(blocks: []const f32, partial: []const f32, sources: usize, s: usize, sim: ?ArSum) f64 { + var terms: [hidden]f64 = undefined; + for (&terms, 0..) |*term, d| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + term.* = @as(f64, x) * x; + } + return arSumIn(&terms, sim); +} + +/// One normalized AR query dot. Its terms are in ascending hidden-coordinate order. +pub fn arQueryDot(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, s: usize, inverse: f64, sim: ?ArSum) f64 { + var terms: [hidden]f64 = undefined; + for (&terms, 0..) |*term, d| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + term.* = @as(f64, queries[q * hidden + d]) * (@as(f64, x) * inverse); + } + return arSumIn(&terms, sim); +} + +/// AR with explicitly modeled reductions; non-reduction arithmetic remains FP64. +pub fn blockResidualIn(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, sim: ?ArSum, out: []f64) void { + var inv: [5]f64 = undefined; + var weight: [5]f64 = undefined; + var peak = -std.math.inf(f64); + for (0..sources) |s| { + const ss = arSourceSquares(blocks, partial, sources, s, sim); + inv[s] = 1 / @sqrt(ss / hidden + 1e-6); + const dot = arQueryDot(blocks, partial, queries, sources, q, s, inv[s], sim); + weight[s] = dot * ar_scale; + peak = @max(peak, weight[s]); + } + var den_terms: [5]f64 = undefined; + for (0..sources) |s| { + den_terms[s] = std.math.exp(weight[s] - peak); + weight[s] = den_terms[s]; + } + const den = arSumIn(den_terms[0..sources], sim); + var terms: [5]f64 = undefined; + for (0..hidden) |d| { + for (0..sources) |s| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + terms[s] = weight[s] / den * (@as(f64, x) * inv[s]); + } + out[d] = arSumIn(terms[0..sources], sim); + } +} + +/// AR over BF16 blocks widened to f32 and an unrounded f32 partial. FP64 is only the oracle. +pub fn blockResidual(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, out: []f64) void { + blockResidualIn(blocks, partial, queries, sources, q, null, out); +} + +pub fn staticConv(taps: []const f32, weight: []const f32, channels: usize, r: usize, c: usize) f64 { + var sum: f64 = taps[(r + 3) * channels + c]; + for (0..4) |tap| sum += @as(f64, weight[c * 4 + tap]) * taps[(r + tap) * channels + c]; + return sum / @sqrt(5.0); +} + +pub fn dynamicConv(taps: []const f32, input: []const f32, static_w: []const f32, projection: []const f32, channels: usize, r: usize, c: usize) f64 { + var sum: f64 = taps[(r + 3) * channels + c]; + for (0..4) |lag| { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, projection[(4 * (c / 128) + lag) * hidden + d]) * input[r * hidden + d]; + const w = @as(f64, static_w[lag * channels + c]) + roundBf16(dot); + sum += w * taps[(r + 3 - lag) * channels + c]; + } + return sum / 3; +} + +pub const Route = struct { ids: [top_k]u32, weights: [top_k]f64 }; +pub fn route(x: []const f32, matrix: []const f32, bias: []const f32) Route { + var score: [expert_count]f64 = undefined; + var used: [expert_count]bool = @splat(false); + var out: Route = undefined; + for (0..expert_count) |e| { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, matrix[e * hidden + d]) * x[d]; + score[e] = sigmoid(dot); + } + for (0..top_k) |j| { + var best: ?usize = null; + for (0..expert_count) |e| if (!used[e]) { + if (best == null or score[e] + bias[e] > score[best.?] + bias[best.?]) best = e; + }; + out.ids[j] = @intCast(best.?); + out.weights[j] = score[best.?]; + used[best.?] = true; + } + std.mem.sort(u32, &out.ids, {}, std.sort.asc(u32)); + // Recover scores after sorting IDs, not route-order positions. + var den: f64 = 1e-20; + for (out.ids, 0..) |id, j| { + out.weights[j] = score[id]; + den += score[id]; + } + for (&out.weights) |*w| w.* = w.* / den * 8; + return out; +} + +pub fn swiglu(gate: f32, up: f32) f64 { + return cap(gate, 4) * sigmoid(gate) * cap(up, 25); +} +pub fn logit(h: []const f32, unembed: []const f32, v: usize) f64 { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, unembed[v * hidden + d]) * h[d]; + return cap(roundBf16(dot), 30); +} +pub fn combine(picked: []const f32, weights: []const f32, channels: usize, d: usize) f64 { + var sum: f64 = 0; + for (0..top_k) |j| sum += @as(f64, weights[j]) * picked[j * channels + d]; + return sum; +} + +pub fn pick(all_experts: []const f32, ids: []const u32, channels: usize, row: usize, j: usize, d: usize) f32 { + return all_experts[(row * expert_count + ids[row * top_k + j]) * channels + d]; +} diff --git a/zig/src/families/inkling2/metal/glue_test.zig b/zig/src/families/inkling2/metal/glue_test.zig new file mode 100644 index 00000000000..815c606f0c7 --- /dev/null +++ b/zig/src/families/inkling2/metal/glue_test.zig @@ -0,0 +1,199 @@ +//! Host-only proof of Mini's glue formulas, source inventory and shape admission. +const std = @import("std"); +const p = @import("inkling2_glue_plan"); +const records = @import("../../../core/contract/inkling2_glue_metal_records.zig").records; +const shader = @import("inkling2_metal").glue; +const c = @import("../../../core/contract/contract.zig"); +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} + +test "glue entries have one shader, symbol, unique launch record and honest scalar reservation" { + for (std.enums.values(p.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(record.threads, record.reserved); + } + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "INKLING_AR_SCALE = 0x1.555556p-6f") != null); + try t.expectEqual(@as(u32, 256), records[@backingInt(p.Kind.conv_dynamic)].threads); + try t.expectEqual(@as(u32, 128), records[@backingInt(p.Kind.conv_dynamic)].tg_memory); +} + +test "shape admission fixes Mini's hidden and routed dimensions" { + try t.expect(p.valid(.embed_norm, .{ .rows = 4, .n = p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.ar, .{ .rows = 6, .n = p.hidden, .k = p.hidden })); + 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(.swiglu, .{ .rows = 1, .n = p.intermediate + 1, .k = 2 })); + try t.expect(p.valid(.logits, .{ .rows = 1, .n = 200058, .k = p.hidden })); + try t.expectEqual(@as(usize, 8 * 1152), p.count(.expert_pick, .{ .rows = 1, .n = 1152, .k = 8 })); +} + +test "embedding uses one FP32 RMS, weighted product and final BF16 rounding" { + var x: [p.hidden]f32 = @splat(1); + var w: [p.hidden]f32 = @splat(2); + try near(@as(f64, 2) / @sqrt(@as(f64, 1) + 1e-6), p.embedValue(&x, &w, 17)); + x[3] = 3; + try t.expect(p.embedValue(&x, &w, 3) != 2); + try t.expectEqual(@as(f64, 1), p.roundBf16(1.003)); +} + +test "AR normalizes each source, scales learned FP32 query dots after reduction and softmaxes" { + const a = t.allocator; + const blocks = try a.alloc(f32, p.hidden); + defer a.free(blocks); + var partial: [p.hidden]f32 = @splat(2); + var queries: [p.hidden]f32 = @splat(0); + @memset(blocks, 1); + const out = try a.alloc(f64, p.hidden); + defer a.free(out); + p.blockResidual(blocks, &partial, &queries, 2, 0, out); + const expected = (1 / @sqrt(@as(f64, 1) + 1e-6) + 2 / @sqrt(@as(f64, 4) + 1e-6)) / 2; + try near(expected, out[0]); + try near(expected, out[1]); + queries[0] = 48; + p.blockResidual(blocks, &partial, &queries, 2, 0, out); + // The first dot is 48/sqrt(2304+eps), multiplied by 1/48 only after that dot. + try t.expect(out[0] < 1.1 and out[0] > 0.9); + try t.expectEqual(p.ar_scale, @as(f64, @as(f32, @bitCast(@as(u32, 0x3caaaaab))))); +} + +test "AR query logits use each normalized source before softmax" { + var blocks: [p.hidden]f32 = @splat(0); + var partial: [p.hidden]f32 = @splat(0); + var queries: [p.hidden]f32 = @splat(0); + var out: [p.hidden]f64 = undefined; + blocks[0] = 1; + partial[1] = 1; + queries[0] = 1; + p.blockResidual(&blocks, &partial, &queries, 2, 0, &out); + const inv = 1 / @sqrt(@as(f64, 1) / p.hidden + 1e-6); + const first = 1 / (1 + @exp(-inv * p.ar_scale)); + try near(first * inv, out[0]); + try near((1 - first) * inv, out[1]); +} + +test "AR FP32 query-dot model distinguishes partial precision and order" { + const blocks: [0]f32 = .{}; + var partial: [p.hidden]f32 = @splat(1); + var queries: [p.hidden]f32 = @splat(0.1); + const sequential = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .f32, .order = .sequential }); + var expected: f32 = 0; + for (0..p.hidden) |d| expected += queries[d] * partial[d]; + try t.expectEqual(@as(f64, expected), sequential); + + const pairwise = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .f32, .order = .pairwise }); + try t.expect(pairwise != sequential); + const bf16 = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .bf16, .order = .sequential }); + var lowered: f64 = 0; + for (0..p.hidden) |d| { + const term = p.roundBf16(@as(f64, queries[d]) * partial[d]); + lowered = p.roundBf16(lowered + term); + } + try t.expectEqual(lowered, bf16); + try t.expect(bf16 != sequential); +} + +test "AR integer stress meets the exact FP32 gate and rejects lower-precision sums" { + const sources = 4; + var blocks: [(sources - 1) * p.hidden]f32 = undefined; + for (0..sources - 1) |s| @memset(blocks[s * p.hidden ..][0..p.hidden], if (s % 2 == 0) 256 else -256); + var partial: [p.hidden]f32 = @splat(-256); + var queries: [2 * p.hidden]f32 = undefined; + for (0..2) |query_row| { + const row = queries[query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + d % 64); + row[d] = v; + row[p.hidden / 2 + d] = (if (d < 8) @as(f32, 1) else 0) - v; + } + } + var want: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidualIn(&blocks, &partial, &queries, sources, q, null, want[q * p.hidden ..][0..p.hidden]); + const spec: c.Spec = .{ .name = "AR stress", .accum = .f32, .depth = undefined, .ops = 96, .out = .f32, .served = &.{} }; + var margins = [_]f64{ std.math.inf(f64), std.math.inf(f64) }; + for ([_]p.ArOrder{ .sequential, .pairwise, .strided }) |order| { + for ([_]p.ArAccum{ .f32, .f16, .bf16 }, 0..) |accum, ai| { + var got: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidualIn(&blocks, &partial, &queries, sources, q, .{ .accum = accum, .order = order }, got[q * p.hidden ..][0..p.hidden]); + var most: f64 = 0; + for (want, got) |w, g| { + const miss = if (g == w) 0 else if (std.math.isFinite(g) or !std.math.isFinite(w)) @abs(g - w) / c.boundExact(spec, w) else std.math.inf(f64); + most = @max(most, miss); + } + if (ai == 0) try t.expect(most <= 1) else margins[ai - 1] = @min(margins[ai - 1], most); + } + } + try t.expect(margins[0] >= 100); + try t.expect(margins[1] >= 100); +} + +test "static convolution's stored tap three is current and carries the residual input" { + const taps = [_]f32{ 1, 2, 3, 4 }; + const weights = [_]f32{ 10, 20, 30, 40 }; + // This addresses channel zero at output row zero with one channel. + try near((1 * 10 + 2 * 20 + 3 * 30 + 4 * 40 + 4) / @as(f64, @sqrt(5.0)), p.staticConv(&taps, &weights, 1, 0, 0)); +} + +test "dynamic convolution rounds 32 projections to BF16 and uses lag zero for current" { + var taps: [7]f32 = @splat(0); + var input: [p.hidden]f32 = @splat(0); + var projection: [32 * p.hidden]f32 = @splat(0); + taps[3] = 2; // r=0, c=0, current + input[0] = 1; + projection[0] = 1; + const static_w = [_]f32{ 5, 0, 0, 0 }; + // lag zero: (5 + BF16(1))*current + current, all divided by three. + try near(@as(f64, 14.0) / 3, p.dynamicConv(&taps, &input, &static_w, &projection, 1, 0, 0)); + try t.expect(p.dynamicConv(&taps, &input, &static_w, &projection, 1, 0, 0) != p.staticConv(&taps, &static_w, 1, 0, 0)); +} + +test "router bias affects top-8 only; sigmoid weights normalize to eight after ascending IDs" { + var x: [p.hidden]f32 = @splat(0); + var matrix: [p.expert_count * p.hidden]f32 = @splat(0); + var bias: [p.expert_count]f32 = @splat(0); + for (120..128) |e| bias[e] = 1; + matrix[127 * p.hidden] = 1; + x[0] = 1; + const r = p.route(&x, &matrix, &bias); + for (r.ids, 0..) |id, j| try t.expectEqual(@as(u32, @intCast(120 + j)), id); + var sum: f64 = 0; + for (r.weights) |w| sum += w; + try near(8, sum); + try t.expect(r.weights[7] > r.weights[0]); + bias[127] = -1; + const changed = p.route(&x, &matrix, &bias); + try t.expect(changed.ids[7] != 127); +} + +test "interleaved SwiGLU caps gate and up separately with one BF16 activation store" { + try near(p.cap(3, 4) * p.sigmoid(3) * p.cap(7, 25), p.swiglu(3, 7)); + try t.expect(p.swiglu(40, 100) < 100); + try near(16.5, p.roundBf16(p.swiglu(3, 7))); +} + +test "A9(a) rounds the BF16 unembed before widening to the FP32 softcap30" { + var h: [p.hidden]f32 = @splat(0); + var u: [p.hidden]f32 = @splat(0); + h[0] = 1; + u[0] = 60; + try near(30 * std.math.tanh(@as(f64, 2)), p.logit(&h, &u, 0)); + u[0] = 1.003; + try near(p.cap(p.roundBf16(1.003), 30), p.logit(&h, &u, 0)); + try t.expect(p.logit(&h, &u, 0) != p.cap(1.003, 30)); +} + +test "expert pick uses sorted IDs and combine accumulates those experts from FP32 zero" { + var all: [p.expert_count]f32 = undefined; + for (&all, 0..) |*v, e| v.* = @floatFromInt(e); + const ids = [_]u32{ 2, 7, 11, 19, 40, 61, 90, 127 }; + try t.expectEqual(@as(f32, 90), p.pick(&all, &ids, 1, 0, 6, 0)); + var picked: [8]f32 = undefined; + for (&picked, 0..) |*v, j| v.* = @floatFromInt(ids[j]); + const weights = [_]f32{ 0, 0, 0, 0, 0, 0, 1, 0 }; + try near(90, p.combine(&picked, &weights, 1, 0)); + try near(2 * p.sigmoid(-3), p.sigmoid(-3) * 2); +} diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig new file mode 100644 index 00000000000..ebd3588eedf --- /dev/null +++ b/zig/src/families/inkling2/metal/loop.zig @@ -0,0 +1,55 @@ +//! Inkling 2 Mini cross-pass messages and message gates: real Metal dispatches. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +pub const plan = @import("inkling2_loop_plan"); + +pub const hidden: u32 = plan.hidden; +pub const rank: u32 = plan.rank; +pub const message_entries: u32 = plan.message_entries; +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const RowsArgs = plan.RowsArgs; + +pub const Pipelines = struct { + messages: mtl.Pipeline, + gates: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.loop); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var messages = try mtl.Pipeline.init(device, lib, plan.Kind.messages.symbol(), false); + errdefer messages.deinit(); + const gate_pipeline = try mtl.Pipeline.init(device, lib, plan.Kind.gates.symbol(), false); + return .{ .messages = messages, .gates = gate_pipeline }; + } + pub fn deinit(p: *Pipelines) void { + p.gates.deinit(); + p.messages.deinit(); + p.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} + +/// 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 <= 64); + e.setPipeline(p.messages); + bind(e, &.{ bank0, bank1, q_mlp, kv, out }); + e.setValue(RowsArgs{ .rows = rows }, 5); + e.dispatchGroups(mtl.Size.of(rows * message_entries, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// 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 <= 64); + e.setPipeline(p.gates); + bind(e, &.{ h, m, down, forget, gain, out }); + e.setValue(RowsArgs{ .rows = rows }, 6); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} diff --git a/zig/src/families/inkling2/metal/loop_plan.zig b/zig/src/families/inkling2/metal/loop_plan.zig new file mode 100644 index 00000000000..86719e705b4 --- /dev/null +++ b/zig/src/families/inkling2/metal/loop_plan.zig @@ -0,0 +1,166 @@ +//! Pure Inkling 2 Mini loop launch geometry and independent FP64 arithmetic. +const std = @import("std"); + +pub const hidden = 2304; +pub const rank = 64; +pub const core_layers = 12; +pub const roles = 4; +pub const message_entries = core_layers * roles; +pub const eps = 1e-6; +pub const message_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); +pub const RowsArgs = extern struct { rows: u32 }; + +pub const Role = enum(u8) { q, k, v, mlp }; +pub const Kind = enum { + messages, + gates, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .messages => "tf_inkling2_loop_messages", + .gates => "tf_inkling2_loop_gates", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .messages => "metal inkling2 loop messages tf_inkling2_loop_messages", + .gates => "metal inkling2 loop gates tf_inkling2_loop_gates", + }; + } +}; + +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 > 64) return false; + return switch (kind) { + .messages => c.n == message_entries * hidden and c.k == hidden, + .gates => c.n == hidden and c.k == rank, + }; +} +pub fn count(kind: Kind, c: Call) usize { + return switch (kind) { + .messages => c.rows * message_entries * hidden, + .gates => c.rows * hidden, + }; +} +pub fn geometry(kind: Kind, c: Call) Geometry { + return .{ + .groups = switch (kind) { + .messages => c.rows * message_entries, + .gates => c.rows, + }, + .tg_memory = switch (kind) { + .messages => 144, + .gates => 9552, + }, + }; +} + +/// q/mlp and k/v each occupy even/odd rows of their separate 24xH tensors. +pub fn queryRow(role: Role, layer: usize) usize { + std.debug.assert(layer < core_layers); + return 2 * layer + switch (role) { + .q, .k => @as(usize, 0), + .v, .mlp => 1, + }; +} +pub fn usesQueryMessageTensor(role: Role) bool { + return role == .q or role == .mlp; +} + +/// Round through FP32 and BF16 nearest-even, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +pub fn rmsScale(x: []const f32) f64 { + std.debug.assert(x.len == hidden); + var ss: f64 = 0; + for (x) |v| ss += @as(f64, v) * v; + return 1 / @sqrt(ss / hidden + eps); +} + +/// One of the 48 messages. Banks contain their already-decoded BF16 values as f32. +pub fn message(bank0: []const f32, bank1: []const f32, q_mlp: []const f32, kv: []const f32, layer: usize, role: Role, out: []f64) void { + std.debug.assert(bank0.len == hidden and bank1.len == hidden and out.len == hidden); + std.debug.assert(q_mlp.len == 2 * core_layers * hidden and kv.len == q_mlp.len); + const queries = if (usesQueryMessageTensor(role)) q_mlp else kv; + const query = queries[queryRow(role, layer) * hidden ..][0..hidden]; + const inverse = [2]f64{ rmsScale(bank0), rmsScale(bank1) }; + var logits: [2]f64 = undefined; + var peak = -std.math.inf(f64); + inline for (0..2) |s| { + const bank = if (s == 0) bank0 else bank1; + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, query[d]) * (@as(f64, bank[d]) * inverse[s]); + logits[s] = dot * message_scale; + peak = @max(peak, logits[s]); + } + var weights: [2]f64 = undefined; + var den: f64 = 0; + for (0..2) |s| { + weights[s] = @exp(logits[s] - peak); + den += weights[s]; + } + for (0..hidden) |d| { + const beta0 = @as(f64, bank0[d]) * inverse[0]; + const beta1 = @as(f64, bank1[d]) * inverse[1]; + out[d] = weights[0] / den * beta0 + weights[1] / den * beta1; + } +} + +/// BF16(concat(rho(h), rho(m))) D projection and the BF16 zeta endpoint, with FP64 sums. +pub fn downProjection(h: []const f32, m: []const f32, down: []const f32, zeta: *[rank]f64) void { + std.debug.assert(h.len == hidden and m.len == hidden and down.len == rank * 2 * hidden); + const ih = rmsScale(h); + const im = rmsScale(m); + var normalized: [2 * hidden]f64 = undefined; + for (0..hidden) |d| { + normalized[d] = roundBf16(@as(f64, h[d]) * ih); + normalized[hidden + d] = roundBf16(@as(f64, m[d]) * im); + } + for (0..rank) |r| { + var dot: f64 = 0; + for (0..2 * hidden) |d| dot += @as(f64, down[r * 2 * hidden + d]) * normalized[d]; + zeta[r] = roundBf16(dot); + } +} + +/// The reference's four explicit binary32 blend nodes. FP64 carries values between nodes. +pub fn blend(forget_value: f64, gain_value: f64, h: f64, m: f64) f64 { + const f: f32 = @floatCast(forget_value); + const g: f32 = @floatCast(gain_value); + const state: f32 = @floatCast(h); + const message_value: f32 = @floatCast(m); + const keep: f32 = 1.0 - f; + const left: f32 = keep * state; + const right: f32 = g * message_value; + const sum: f32 = left + right; + return sum; +} + +/// Full rank-64 gate. Matrix slices contain their exact BF16 values widened to f32. +pub fn gate(h: []const f32, m: []const f32, down: []const f32, forget: []const f32, gain: []const f32, out: []f64) void { + std.debug.assert(h.len == hidden and m.len == hidden and out.len == hidden); + std.debug.assert(forget.len == hidden * rank and gain.len == forget.len); + var zeta: [rank]f64 = undefined; + downProjection(h, m, down, &zeta); + for (0..hidden) |d| { + var fdot: f64 = 0; + var gdot: f64 = 0; + for (0..rank) |r| { + fdot += @as(f64, forget[d * rank + r]) * zeta[r]; + gdot += @as(f64, gain[d * rank + r]) * zeta[r]; + } + out[d] = blend(std.math.tanh(fdot), std.math.tanh(gdot), h[d], m[d]); + } +} diff --git a/zig/src/families/inkling2/metal/loop_test.zig b/zig/src/families/inkling2/metal/loop_test.zig new file mode 100644 index 00000000000..4fc655e211b --- /dev/null +++ b/zig/src/families/inkling2/metal/loop_test.zig @@ -0,0 +1,208 @@ +//! Host-only proof of Mini's loop formulas, launch ABI, source inventory and rounding. +const std = @import("std"); +const p = @import("inkling2_loop_plan"); +const records = @import("../../../core/contract/inkling2_loop_metal_records.zig").records; +const shader = @import("inkling2_metal").loop; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} + +test "loop entries have unique symbols, launch records and disabled FP contraction" { + for (std.enums.values(p.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(@as(u32, 256), record.threads); + try t.expectEqual(record.threads, record.reserved); + try t.expectEqual(p.geometry(kind, .{ .rows = 1, .n = 1, .k = 1 }).tg_memory, record.tg_memory); + } + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "INKLING_LOOP_SCALE = 0x1.555556p-6f") != null); + try t.expect(std.mem.indexOf(u8, shader, "LoopMathSpecMissing") == null); +} + +test "shape admission and dispatch geometry fix H=2304, rank 64 and 48 messages" { + const mc = p.Call{ .rows = 7, .n = 48 * p.hidden, .k = p.hidden }; + const gc = p.Call{ .rows = 7, .n = p.hidden, .k = p.rank }; + try t.expect(p.valid(.messages, mc)); + try t.expect(p.valid(.gates, gc)); + try t.expectEqual(@as(usize, 7 * 48), p.geometry(.messages, mc).groups); + try t.expectEqual(@as(usize, 7), p.geometry(.gates, gc).groups); + try t.expectEqual(@as(usize, 7 * 48 * p.hidden), p.count(.messages, mc)); + try t.expectEqual(@as(usize, 7 * p.hidden), p.count(.gates, gc)); + try t.expect(!p.valid(.messages, .{ .rows = 1, .n = 47 * p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.messages, .{ .rows = 1, .n = 48 * p.hidden, .k = 4608 })); + try t.expect(!p.valid(.gates, .{ .rows = 1, .n = p.hidden, .k = 32 })); + try t.expect(!p.valid(.gates, .{ .rows = 0, .n = p.hidden, .k = p.rank })); + try t.expectEqual(@as(usize, 4), @sizeOf(p.RowsArgs)); + try t.expectEqual(@as(usize, 0), @offsetOf(p.RowsArgs, "rows")); +} + +test "message with zero query is the exact mean of independently normalized banks" { + var bank0: [p.hidden]f32 = @splat(1); + var bank1: [p.hidden]f32 = @splat(2); + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var out: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, 11, .v, &out); + const expected = (@as(f64, 1) / @sqrt(@as(f64, 1) + p.eps) + + @as(f64, 2) / @sqrt(@as(f64, 4) + p.eps)) / 2; + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); + try t.expectEqual(p.message_scale, @as(f64, @as(f32, @bitCast(@as(u32, 0x3caaaaab))))); +} + +test "q/mlp and k/v even-odd layouts select all four roles and scale after the dot" { + var bank0: [p.hidden]f32 = @splat(1); + var bank1: [p.hidden]f32 = @splat(2); + bank1[0] = 4; + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + const layer = 5; + const all = [_]p.Role{ .q, .k, .v, .mlp }; + for (all) |role| { + const expected_row = @as(usize, 2 * layer) + @as(usize, @intFromBool(role == .v or role == .mlp)); + try t.expectEqual(expected_row, p.queryRow(role, layer)); + const matrix = if (p.usesQueryMessageTensor(role)) &q_mlp else &kv; + matrix[expected_row * p.hidden] = 48; + } + var first: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, layer, all[0], &first); + const scale0 = p.rmsScale(&bank0); + const scale1 = p.rmsScale(&bank1); + const l0 = 48 * scale0 * p.message_scale; + const l1 = 48 * 4 * scale1 * p.message_scale; + const peak = @max(l0, l1); + const e0 = @exp(l0 - peak); + const e1 = @exp(l1 - peak); + const expected = e0 / (e0 + e1) * scale0 + e1 / (e0 + e1) * 4 * scale1; + try near(expected, first[0]); + try t.expect(first[0] != (scale0 + 4 * scale1) / 2); + var out: [p.hidden]f64 = undefined; + for (all[1..]) |role| { + p.message(&bank0, &bank1, &q_mlp, &kv, layer, role, &out); + for (first, out) |a, b| try near(a, b); + } +} + +test "message stress dots are exact in FP32 and discriminate BF16 accumulation" { + var bank0: [p.hidden]f32 = @splat(256); + var bank1: [p.hidden]f32 = @splat(-256); + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + const query = q_mlp[0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + d % 64); + const nudge: f32 = if (d < 8) 1 else 0; + query[d] = v; + query[p.hidden / 2 + d] = nudge - v; + } + var fp: f32 = 0; + var bf: f64 = 0; + for (query) |v| { + fp += v; + bf = p.roundBf16(bf + v); + } + try t.expectEqual(@as(f32, 8), fp); + try t.expect(bf != 8); + var out: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, 0, .q, &out); + const expected = std.math.tanh(8 * p.message_scale); + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); +} + +test "rank gate hand witness shares one BF16 zeta and uses FP32 tanh projections" { + var h: [p.hidden]f32 = @splat(1); + var m: [p.hidden]f32 = @splat(2); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + var forget: [p.hidden * p.rank]f32 = @splat(0); + var gain: [p.hidden * p.rank]f32 = @splat(0); + down[0] = 1; + for (0..p.hidden) |d| { + forget[d * p.rank] = 1; + gain[d * p.rank] = 1; + } + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); + for (zeta[1..]) |z| try near(0, z); + var out: [p.hidden]f64 = undefined; + p.gate(&h, &m, &down, &forget, &gain, &out); + const expected = p.blend(std.math.tanh(@as(f64, 1)), std.math.tanh(@as(f64, 1)), 1, 2); + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); + + // The message half starts at D column H; it is not interleaved with h. + @memset(&down, 0); + down[p.hidden] = 1; + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); + down[p.hidden] = 0; + down[0] = 1; + @memset(&m, 0); + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); +} + +test "concatenated normalized gate inputs round to BF16 before D accumulation" { + var h: [p.hidden]f32 = @splat(0); + var m: [p.hidden]f32 = @splat(0); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + for (&h, 0..) |*v, d| v.* = @as(f32, @floatFromInt(d % 19 + 1)) / 32; + for (0..p.hidden) |d| down[d] = 1; + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + // Fixed witness rounds to 2024; accumulating unrounded normalized values would round to 2016. + try near(2024, zeta[0]); +} + +test "gate stress projections are exact in FP32 and expose BF16 sums" { + var h: [p.hidden]f32 = @splat(256); + var m: [p.hidden]f32 = @splat(-256); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + var forget: [p.hidden * p.rank]f32 = @splat(0); + var gain: [p.hidden * p.rank]f32 = @splat(0); + for (0..p.rank) |r| for (0..p.hidden) |d| { + const w: f32 = @floatFromInt(1 + (r + d) % 64); + down[r * 2 * p.hidden + d] = w; + down[r * 2 * p.hidden + p.hidden + d] = if (d == 0) w - 1 else w; + }; + for ([_][]f32{ &forget, &gain }) |weights| for (0..p.hidden) |d| for (0..p.rank / 2) |r| { + const w: f32 = @floatFromInt(1 + (d + r) % 7); + weights[d * p.rank + r] = w; + weights[d * p.rank + r + p.rank / 2] = if (r == 0) 1 - w else -w; + }; + var fp: f32 = 0; + var bf: f64 = 0; + for (0..2 * p.hidden) |d| { + const term = @as(f64, down[d]) * (if (d < p.hidden) @as(f64, 1) else -1); + fp += @as(f32, @floatCast(term)); + bf = p.roundBf16(bf + term); + } + try t.expectEqual(@as(f32, 1), fp); + try t.expect(bf != 1); + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + for (zeta) |z| try near(1, z); + var out: [p.hidden]f64 = undefined; + p.gate(&h, &m, &down, &forget, &gain, &out); + const expected = p.blend(std.math.tanh(@as(f64, 1)), std.math.tanh(@as(f64, 1)), 256, -256); + for (out) |v| try near(expected, v); +} + +test "BF16 nearest-even and all four binary32 blend steps have exact witnesses" { + try near(1, p.roundBf16(1.00390625)); // midpoint: even mantissa is zero + try near(1.015625, p.roundBf16(1.01171875)); // midpoint: two is even + const f: f32 = 0.33333334; + const g: f32 = 0.14285715; + const h: f32 = 1.003; + const m: f32 = 1.007; + const keep: f32 = 1.0 - f; + const left: f32 = keep * h; + const right: f32 = g * m; + const rounded: f32 = left + right; + try t.expectEqual(@as(f64, rounded), p.blend(f, g, h, m)); + try t.expect(p.blend(f, g, h, m) != (1 - @as(f64, f)) * h + @as(f64, g) * m); +} diff --git a/zig/src/families/inkling2/metal/metal.zig b/zig/src/families/inkling2/metal/metal.zig new file mode 100644 index 00000000000..bef58022713 --- /dev/null +++ b/zig/src/families/inkling2/metal/metal.zig @@ -0,0 +1,7 @@ +//! Inkling 2 Mini's Metal launchers and their shader sources. + +pub const attention = @import("attention.zig"); +pub const glue = @import("glue.zig"); +pub const experts = @import("experts.zig"); +pub const experts_plan = @import("experts_plan.zig"); +pub const loop = @import("loop.zig"); diff --git a/zig/src/families/inkling2/metal/ref.zig b/zig/src/families/inkling2/metal/ref.zig new file mode 100644 index 00000000000..1e6f5a69622 --- /dev/null +++ b/zig/src/families/inkling2/metal/ref.zig @@ -0,0 +1,4 @@ +//! Shared Metal buffer reference for Inkling 2 launchers and their state buffers. +const mtl = @import("metal"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; diff --git a/zig/src/families/inkling2/metal/runtime_kernels_test.zig b/zig/src/families/inkling2/metal/runtime_kernels_test.zig new file mode 100644 index 00000000000..0c3902ffaa6 --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_kernels_test.zig @@ -0,0 +1,116 @@ +//! Host-only proof of Mini's runtime source identity, launch ABI, block layout and rounding. +const std = @import("std"); +const p = @import("runtime_plan.zig"); +const model = @import("model.zig"); +const records = @import("../../../core/contract/inkling2_runtime_metal_records.zig").records; +const shader = @import("inkling2_metal").runtime; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-12); +} + +test "runtime source is the one exported source and every helper has one launch record" { + try t.expectEqualStrings(shader, model.runtime_source); + try t.expectEqualStrings(shader, @import("kernel_sources").inkling2_runtime); + try t.expectEqual(std.enums.values(p.Kind).len, model.runtime_names.len); + try t.expectEqual(std.enums.values(p.Kind).len, records.len); + for (std.enums.values(p.Kind), records, model.runtime_names) |kind, record, runtime_name| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqualStrings(kind.symbol(), runtime_name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(p.threads, record.threads); + try t.expectEqual(record.threads, record.reserved); + try t.expectEqual(@as(u32, 0), record.tg_memory); + } + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, "#pragma METAL fp contract(off)")); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, "struct InkRuntimeArgs { uint count, boundary; };")); +} + +test "linear launches bind H=2304 rows and the exact eight-byte argument ABI" { + try t.expectEqual(@as(usize, 8), @sizeOf(p.RuntimeArgs)); + try t.expectEqual(@as(usize, 0), @offsetOf(p.RuntimeArgs, "count")); + try t.expectEqual(@as(usize, 4), @offsetOf(p.RuntimeArgs, "boundary")); + for (std.enums.values(p.Kind)) |kind| { + const call = p.Call{ .rows = 7, .n = p.hidden, .k = if (kind == .attention_partial) 4 else 1 }; + try t.expect(p.valid(kind, call)); + const a = p.args(kind, call); + try t.expectEqual(@as(u32, 7 * p.hidden), a.count); + try t.expectEqual(@as(u32, if (kind == .attention_partial) 4 else if (kind == .capture_tap) 1 else 0), a.boundary); + try t.expectEqual(@as(usize, 7 * p.hidden), p.geometry(call).count); + try t.expectEqual(p.threads, p.geometry(call).threads); + try t.expectEqual(@as(u32, 0), p.geometry(call).tg_memory); + const outputs: usize = 7 * p.hidden * (if (kind == .capture_tap) @as(usize, p.tap_channels) else 1); + try t.expectEqual(outputs, p.outputCount(kind, call)); + try t.expect(!p.valid(kind, .{ .rows = 0, .n = p.hidden, .k = call.k })); + if (kind == .copy_bf16 or kind == .copy_f32) { + try t.expect(p.valid(kind, .{ .rows = 5, .n = 1024, .k = 1 })); + } else { + try t.expect(!p.valid(kind, .{ .rows = 1, .n = p.hidden - 1, .k = call.k })); + } + } + try t.expect(!p.valid(.copy_bf16, .{ .rows = 1, .n = 0, .k = 1 })); + try t.expect(p.valid(.attention_partial, .{ .rows = 1, .n = p.hidden, .k = 0 })); + try t.expect(!p.valid(.attention_partial, .{ .rows = 1, .n = p.hidden, .k = 5 })); + try t.expect(!p.valid(.widen, .{ .rows = 1, .n = p.hidden, .k = 0 })); + try t.expect(p.valid(.capture_tap, .{ .rows = 1, .n = p.hidden, .k = 3 })); + try t.expect(!p.valid(.capture_tap, .{ .rows = 1, .n = p.hidden, .k = 4 })); +} + +test "DSpark capture channels are packed [row][tap][H] in visit order" { + try t.expectEqual(@as(usize, 4), p.tap_channels); + try t.expectEqual(@as(usize, 0), p.tapOffset(0, 0)); + try t.expectEqual(p.hidden, p.tapOffset(0, 1)); + try t.expectEqual(3 * p.hidden, p.tapOffset(0, 3)); + try t.expectEqual(4 * p.hidden, p.tapOffset(1, 0)); + try t.expectEqual(7 * p.hidden, p.tapOffset(1, 3)); + try t.expectEqual(2 * 4 * p.hidden, p.outputCount(.capture_tap, .{ .rows = 2, .n = p.hidden, .k = 0 })); + try t.expectEqual(2 * p.hidden, p.args(.capture_tap, .{ .rows = 2, .n = p.hidden, .k = 0 }).count); +} + +test "four completed BF16 blocks are row-major and disjoint from the partial source" { + try t.expectEqual(@as(usize, 0), p.blockOffset(0, 1)); + try t.expectEqual(3 * p.hidden, p.blockOffset(0, 4)); + try t.expectEqual(4 * p.hidden, p.blockOffset(1, 1)); + try t.expectEqual(15 * p.hidden, p.blockOffset(3, 4)); + var previous: usize = 0; + for (0..4) |row| for (1..5) |boundary| { + const at = p.blockOffset(row, boundary); + if (at != 0) try t.expectEqual(previous + p.hidden, at); + previous = at; + }; + try t.expectEqual(4 * 4 * p.hidden, previous + p.hidden); +} + +test "attention restart and addition references cover every valid boundary" { + const partial: f32 = 1.5; + const attention: f32 = -0.25; + try near(1.25, p.attentionPartial(partial, attention, 0)); + for (1..5) |boundary| try near(-0.25, p.attentionPartial(partial, attention, boundary)); + // One binary32 addition rounds this midpoint to one; unrounded FP64 addition would not. + const ulp: f32 = 0x1p-24; + try near(1, p.attentionPartial(1, ulp, 0)); + try t.expect(p.attentionPartial(1, ulp, 0) != 1 + @as(f64, ulp)); + for (1..5) |boundary| try near(@as(f64, ulp), p.attentionPartial(std.math.nan(f32), ulp, boundary)); +} + +test "MLP partial rounds its FP32 sum to nearest-even BF16" { + try near(1, p.roundBf16(@as(f32, 1.00390625))); + try near(1.015625, p.roundBf16(@as(f32, 1.01171875))); + try near(1, p.mlpPartial(1, 0.00390625)); + try near(1.015625, p.mlpPartial(1, 0.01171875)); + try t.expect(p.mlpPartial(1, 0.00390625) != 1.00390625); +} + +test "copy and widening witnesses preserve actual BF16 and FP32 values" { + const bf16 = @import("bf16_round"); + const bf_values = [_]f32{ -0.0, 1.0, -2.5, 0.0078125, std.math.inf(f32) }; + for (bf_values) |x| { + const bits = bf16.bits(x); + const stored: f32 = @bitCast(@as(u32, bits) << 16); + try t.expectEqual(@as(u32, @bitCast(x)), @as(u32, bits) << 16); + try near(x, stored); + } + const f32_values = [_]f32{ -0.0, 1.00000011920928955078125, -8192.25 }; + for (f32_values) |x| try t.expectEqual(@as(u32, @bitCast(x)), @as(u32, @bitCast(@as(f32, @floatCast(@as(f64, x)))))); +} diff --git a/zig/src/families/inkling2/metal/runtime_plan.zig b/zig/src/families/inkling2/metal/runtime_plan.zig new file mode 100644 index 00000000000..4edc008967d --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_plan.zig @@ -0,0 +1,105 @@ +//! Pure Inkling 2 Mini runtime launch geometry and independent FP64 references. +const std = @import("std"); + +pub const hidden = 2304; +pub const block_slots = 4; +pub const tap_channels = 4; +pub const max_rows = 64; +pub const threads: u32 = 256; +pub const RuntimeArgs = extern struct { count: u32, boundary: u32 }; + +pub const Kind = enum { + copy_bf16, + copy_f32, + widen, + attention_partial, + mlp_partial, + capture_tap, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .copy_bf16 => "tf_ink2_copy_bf16", + .copy_f32 => "tf_ink2_copy_f32", + .widen => "tf_ink2_widen", + .attention_partial => "tf_ink2_attention_partial", + .mlp_partial => "tf_ink2_mlp_partial", + .capture_tap => "tf_ink2_capture_tap", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .copy_bf16 => "metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", + .copy_f32 => "metal inkling2 runtime copy_f32 tf_ink2_copy_f32", + .widen => "metal inkling2 runtime widen tf_ink2_widen", + .attention_partial => "metal inkling2 runtime attention_partial tf_ink2_attention_partial", + .mlp_partial => "metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", + .capture_tap => "metal inkling2 runtime capture_tap tf_ink2_capture_tap", + }; + } +}; + +/// `k` is one for pointwise helpers, a boundary for attention, or a DSpark tap channel. +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub const Geometry = struct { count: usize, threads: u32 = threads, tg_memory: u32 = 0 }; + +pub fn valid(kind: Kind, c: Call) bool { + if (c.rows == 0 or c.rows > max_rows or c.n == 0 or c.rows > std.math.maxInt(u32) / c.n) return false; + return switch (kind) { + .copy_bf16, .copy_f32 => c.k == 1, + .capture_tap => c.n == hidden and c.k < tap_channels, + .widen, .attention_partial, .mlp_partial => c.n == hidden and switch (kind) { + .attention_partial => c.k <= block_slots, + else => c.k == 1, + }, + }; +} + +pub fn geometry(c: Call) Geometry { + return .{ .count = c.rows * c.n }; +} + +/// Values in the full destination for one capture launch; its dispatch still reads rows*n. +pub fn outputCount(kind: Kind, c: Call) usize { + const channels: usize = if (kind == .capture_tap) tap_channels else 1; + return c.rows * c.n * channels; +} + +pub fn args(kind: Kind, c: Call) RuntimeArgs { + std.debug.assert(valid(kind, c)); + return .{ .count = @intCast(c.rows * c.n), .boundary = if (kind == .attention_partial or kind == .capture_tap) @intCast(c.k) else 0 }; +} + +/// Completed blocks are [row][four BF16 blocks][H]; the separate partial is not stored here. +pub fn blockOffset(row: usize, boundary: usize) usize { + std.debug.assert(row < max_rows and boundary >= 1 and boundary <= block_slots); + return (row * block_slots + boundary - 1) * hidden; +} + +/// DSpark features are [row][four taps][H]; a capture launch writes one tap channel. +pub fn tapOffset(row: usize, channel: usize) usize { + std.debug.assert(row < max_rows and channel < tap_channels); + return (row * tap_channels + channel) * hidden; +} + +/// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +/// Boundary restarts the FP32 partial; otherwise the two exact BF16 inputs undergo one FP32 add. +pub fn attentionPartial(p: f32, x: f32, boundary: usize) f64 { + std.debug.assert(boundary <= block_slots); + return if (boundary != 0) x else @as(f32, p + x); +} + +/// FP32 residual addition followed by the required BF16 endpoint. +pub fn mlpPartial(t: f32, x: f32) f64 { + return roundBf16(@as(f32, t + x)); +} diff --git a/zig/tests/contract/metal_inkling2_attention.zig b/zig/tests/contract/metal_inkling2_attention.zig new file mode 100644 index 00000000000..9b359464c85 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention.zig @@ -0,0 +1,565 @@ +//! Inkling 2 Mini Metal attention gates 1-4 with an independent float64 formula and both prompt layouts. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_inkling2_attention_controls.zig"); +const sources = @import("inkling2_metal"); +const plan = @import("tensorfold").inkling2_metal_host.attention.planning; +const c = contract.spec; +const g = contract.gates; +const Which = controls.Which; +const Mutation = controls.Mutation; +const D = 128; +const H = 24; +const KV = 8; +const R = 16; +const EXTENT = 1024; +const scale = 0.08838834764831845; + +const prep_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 9000 } }; +const prep_global_shapes = [_]c.Shape{ prep_shapes[0], prep_shapes[1], .{ .rows = 4, .n = H * D, .k = 1048576 } }; +const rel_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * EXTENT, .k = R }, .{ .rows = 1, .n = H * EXTENT, .k = R } }; +const sliding_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 2049 } }; +const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 } }; +const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 } }; +fn depth(s: c.Shape) usize { + return D + 4 * s.k + 64; +} +fn flat(_: c.Shape) usize { + return R; +} +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) { + .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; + s.ops = 32; + s.mids = 2; + }, + .rel_table => { + s.name = "metal inkling2 attention relative table tf_ink2_rel_table"; + s.served = &rel_shapes; + s.depth = flat; + s.ops = 4; + s.mids = 0; + }, + .decode_sliding => { + s.name = "metal inkling2 attention scalar sliding tf_ink2_attn_scalar"; + s.served = &sliding_shapes; + }, + .decode_global => { + s.name = "metal inkling2 attention scalar global tf_ink2_attn_scalar"; + s.served = &global_shapes; + }, + .prompt_m5 => { + s.name = "metal inkling2 prompt m5 tf_ink2_attn_prompt"; + s.served = &prompt_shapes; + }, + .prompt_pre_m5 => { + s.name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt"; + s.served = &prompt_shapes; + }, + } + return s; +} +fn bf(x: u16) f64 { + return c.fromBf16(x); +} +fn rn(x: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(x))); +} +fn bits(x: f64) u16 { + return c.toBf16(@floatCast(x)); +} +fn minNum(x: f64, y: f64) f64 { + return if (std.math.isNan(x)) y else if (std.math.isNan(y)) x else @min(x, y); +} +fn maxNan(x: f64, y: f64) f64 { + return if (std.math.isNan(x) or std.math.isNan(y)) std.math.nan(f64) else @max(x, y); +} +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} +/// Prompt P rounds to BF16 at each tile maximum; later rescaling does not round twice. The result anchors weights. +fn promptWeights(score: []const f64, weights: []f64) f64 { + const tile_keys = 64; + const sub_keys = 1024; + var top = -std.math.inf(f64); + var upper = -std.math.inf(f64); + var first: usize = 0; + while (first < score.len) { + const end = @min(first + tile_keys, score.len); + const sub_first = first - first % sub_keys; + var tile_peak = top; + for (score[first..end]) |sc| tile_peak = maxNan(tile_peak, sc); + const mu = if (tile_peak == -std.math.inf(f64)) 0 else tile_peak; + const keep = @exp(top - mu); + for (weights[sub_first..first]) |*w| w.* *= keep; + for (weights[first..end], score[first..end]) |*w, sc| w.* = rn(@exp(sc - mu)); + top = tile_peak; + if (first % sub_keys == sub_keys - tile_keys or end == score.len) { + if (top != -std.math.inf(f64)) { + const merged = maxNan(upper, top); + const old_scale = @exp(upper - merged); + const new_scale = @exp(top - merged); + for (weights[0..sub_first]) |*w| w.* *= old_scale; + for (weights[sub_first..end]) |*w| w.* *= new_scale; + upper = merged; + } + top = -std.math.inf(f64); + } + first = end; + } + return upper; +} +fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} +fn periodic(p: usize, col: usize) f64 { + const i = p % 1024; + if (i < 512) return @floatFromInt(129 + (i * 73 + col * 31) % 127); + const j = i - 512; + return -@as(f64, @floatFromInt(129 + ((j + 1) * 73 + col * 31) % 127)) + @as(f64, if (j < 8) 1 else 0); +} +const Sim = struct { acc: c.Accum, order: g.Order }; +fn sum(v: []const f64, sim: ?Sim) f64 { + if (sim) |s| return contract.rows.sumIn(s.acc, s.order, v); + var total: f64 = 0; + for (v) |x| total += x; + return total; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + which: Which, + mutation: Mutation, + lib: mtl.Library, + main: mtl.Pipeline, + merge_lib: ?mtl.Library = null, + merge: mtl.Pipeline = undefined, + fused: bool = false, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + fill: g.Fill = .random, + layer: plan.Layer = undefined, + q: []u16 = &.{}, + kc: []u16 = &.{}, + vc: []u16 = &.{}, + tab: []u16 = &.{}, + sink: []u16 = &.{}, + gate: []u16 = &.{}, + rel: []u16 = &.{}, + proj: []u16 = &.{}, + qs: []u16 = &.{}, + rs: []u16 = &.{}, + pos: []usize = &.{}, + refs: [10]rig_.Ref = undefined, + out: [4]rig_.Ref = undefined, + meta: [3]rig_.Ref = undefined, + po: rig_.Ref = undefined, + pml: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, w: Which, m: Mutation) !Probe { + const plain = if (controls.isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const text = try controls.apply(a, plain, m); + defer a.free(text); + var lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + var main = try mtl.Pipeline.init(device, lib, controls.function(w), false); + errdefer main.deinit(); + var merge_lib: ?mtl.Library = null; + errdefer if (merge_lib) |loaded| loaded.deinit(); + var merge: mtl.Pipeline = undefined; + const fused = controls.isAttention(w); + if (fused) { + if (controls.isPrompt(w)) merge_lib = try mtl.Library.fromSource(device, sources.attention, mtl.CompileOptions.mlx()); + const merge_library = if (merge_lib) |loaded| loaded else lib; + merge = try mtl.Pipeline.init(device, merge_library, "tf_ink2_merge", false); + } + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = w, .mutation = m, .lib = lib, .main = main, .merge_lib = merge_lib, .merge = merge, .fused = fused }; + } + fn hostFree(p: *Probe) void { + inline for (.{ "q", "kc", "vc", "tab", "sink", "gate", "rel", "proj", "qs", "rs", "pos" }) |f| { + p.a.free(@field(p, f)); + @field(p, f) = &.{}; + } + } + pub fn deinit(p: *Probe) void { + p.hostFree(); + p.rig.deinit(); + if (p.fused) p.merge.deinit(); + if (p.merge_lib) |loaded| loaded.deinit(); + p.main.deinit(); + p.lib.deinit(); + } + const vt = g.hooks(Probe); + pub fn kernel(p: *Probe) g.Kernel { + var k: g.Kernel = .{ .spec = spec(p.which), .ctx = p, .vt = &vt }; + if (p.mutation != .none) { + k.spec.name = p.mutation.name(); + k.control = p.mutation.gate(); + } + return k; + } + fn sizes(p: *const Probe) [4]usize { + const n = p.rigCache(); + return .{ p.shape.rows * H * D, p.shape.rows * H * R, n, n }; + } + fn rigCache(p: *const Probe) usize { + return KV * p.layer.ring * D; + } + pub fn count(p: *const Probe) usize { + if (p.which == .rel_table) return p.shape.rows * H * EXTENT; + if (controls.isAttention(p.which)) return p.shape.rows * H * D; + const z = p.sizes(); + return z[0] + z[1] + z[2] + z[3]; + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.k < s.rows) return false; + if (p.which == .rel_table) { + if (s.n != H * EXTENT or s.k != R) return false; + } else if (s.n != H * D) return false; + p.hostFree(); + p.rig.reset(); + p.shape = s; + p.fill = fill; + const global = p.which == .prep_global or p.which == .decode_global or controls.isPrompt(p.which); + const sliding = p.which == .prep_sliding or p.which == .decode_sliding; + p.layer = .{ .window = if (sliding) 1024 else 0, .ring = 2048, .chunk = if (sliding) 256 else plan.global_chunk, .tau = global }; + const rows = s.rows; + const rh = rows * H; + const cache = KV * p.layer.ring * D; + p.pos = try p.a.alloc(usize, rows); + for (p.pos, 0..) |*v, r| v.* = s.k - rows + r; + if (p.which != .rel_table) { + p.q = try p.a.alloc(u16, rh * D); + p.tab = try p.a.alloc(u16, rh * EXTENT); + @memset(p.q, 0); + @memset(p.tab, 0); + } else { + p.rel = try p.a.alloc(u16, rh * R); + p.proj = try p.a.alloc(u16, R * EXTENT); + @memset(p.rel, 0); + @memset(p.proj, 0); + } + if (!controls.isAttention(p.which) and p.which != .rel_table) p.rel = try p.a.alloc(u16, rh * R); + if (p.which != .rel_table) { + p.kc = try p.a.alloc(u16, if (controls.isAttention(p.which)) cache else rows * KV * D); + p.vc = try p.a.alloc(u16, p.kc.len); + @memset(p.kc, 0); + @memset(p.vc, 0); + } + if (controls.isAttention(p.which)) { + p.sink = try p.a.alloc(u16, rh); + p.gate = try p.a.alloc(u16, rh * D); + @memset(p.sink, 0); + @memset(p.gate, 0); + } + if (p.which == .prep_sliding or p.which == .prep_global) { + p.qs = try p.a.alloc(u16, H * D); + p.rs = try p.a.alloc(u16, H * R); + @memset(p.qs, 0); + @memset(p.rs, 0); + } + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.fillValues(rng, global); + if (fill == .nonfinite) p.plant(); + try p.bind(); + return true; + } + fn fillValues(p: *Probe, rng: std.Random, global: bool) void { + const stress = p.fill == .stress; + for (p.q) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 511))) - 255) else rng.floatNorm(f64) * 0.3); + for (p.kc) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64) * 0.3); + for (p.vc, 0..) |*v, i| v.* = if (stress and controls.isAttention(p.which)) bits(periodic(i / D % p.layer.ring, i % D)) else bits(if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64)); + for (p.tab) |*v| v.* = bits(if (stress) 0 else rng.floatNorm(f64) * 0.25); + for (p.sink) |*v| v.* = bits(if (stress) -std.math.inf(f64) else 2 + 4 * rng.float(f64)); + for (p.gate) |*v| v.* = bits(if (stress) 32 else rng.floatNorm(f64)); + for (p.rel, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(2 * (i % 31) + 1) else rng.floatNorm(f64)); + for (p.proj, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(1 + i % 2) else rng.floatNorm(f64) * 0.5); + for (p.qs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + for (p.rs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + if (global and !controls.isAttention(p.which)) { + _ = tau(p.pos[0]); + } + } + fn plant(p: *Probe) void { + const nan = bits(std.math.nan(f64)); + const inf = bits(std.math.inf(f64)); + if (p.which == .rel_table) { + p.rel[3] = nan; + if (p.rel.len > R + 5) p.rel[R + 5] = inf; + if (p.rel.len > 2 * R + 1) { + p.rel[2 * R] = inf; + p.rel[2 * R + 1] = inf | 0x8000; + } + } else if (controls.isAttention(p.which)) { + p.q[D + 5] = nan; + p.sink[2] = inf; + p.gate[3 * D] = inf; + p.gate[3 * D + 1] = inf | 0x8000; + } else { + p.q[D + 3] = nan; + p.kc[5] = inf; + p.vc[D] = inf | 0x8000; + p.rel[2] = nan; + } + } + fn bind(p: *Probe) !void { + const rows = p.shape.rows; + if (p.which == .rel_table) { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.rel)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.proj)); + p.out[0] = try p.rig.output(p.count() * 2); + return; + } + if (controls.isAttention(p.which)) { + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.tab, p.sink, p.gate }; + for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); + } else { + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.rel, p.qs, p.rs }; + for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); + } + const pos32 = try p.a.alloc(i32, rows); + defer p.a.free(pos32); + const seg32 = try p.a.alloc(i32, rows); + defer p.a.free(seg32); + @memset(seg32, 0); + for (pos32, p.pos) |*v, x| v.* = @intCast(x); + const seg = [1]plan.Seg{.{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p.shape.k - rows), .off = 0 }}; + p.meta[0] = try p.rig.input(std.mem.sliceAsBytes(pos32)); + p.meta[1] = try p.rig.input(std.mem.sliceAsBytes(seg32)); + p.meta[2] = try p.rig.input(std.mem.sliceAsBytes(&seg)); + if (controls.isAttention(p.which)) { + const stride = plan.slotsFor(p.layer, p.shape.k); + const parts = rows * H * stride; + p.po = try p.rig.scratch(parts * D * 4); + p.pml = try p.rig.scratch(parts * 8); + p.out[0] = try p.rig.output(p.count() * 2); + } else for (p.sizes(), 0..) |n, i| p.out[i] = try p.rig.output(n * 2); + } + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.main); + const rows: u32 = @intCast(p.shape.rows); + const ring = p.layer.ring; + if (p.which == .rel_table) { + e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); + e.setBuffer(p.refs[1].buf, p.refs[1].off, 1); + e.setBuffer(p.out[0].buf, p.out[0].off, 2); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(256, 1, 1)); + } else if (!controls.isAttention(p.which)) { + @memset(p.rig.bytes(p.out[2], p.sizes()[2] * 2), 0); + @memset(p.rig.bytes(p.out[3], p.sizes()[3] * 2), 0); + for (p.refs[0..6], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + for (p.meta, 6..) |r, i| e.setBuffer(r.buf, r.off, i); + for (p.out, 9..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(plan.PrepArgs{ .heads = H, .kv_heads = KV, .ring = ring, .global = @intFromBool(p.layer.tau), .qk_clip = 22.627416997969522, .rel_clip = 8, .floor_pos = 8192, .alpha = 0.1, .eps = 1e-6 }, 13); + e.dispatchGroups(mtl.Size.of(rows, H + 2 * KV, 1), mtl.Size.of(32, 1, 1)); + } else { + const stride = plan.slotsFor(p.layer, p.shape.k); + for (p.refs[0..4], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.meta[2].buf, p.meta[2].off, 4); + e.setBuffer(p.po.buf, p.po.off, 5); + e.setBuffer(p.pml.buf, p.pml.off, 6); + 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 }, 7); + 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)); + } else { + e.setBuffer(p.meta[0].buf, p.meta[0].off, 7); + e.setBuffer(p.meta[1].buf, p.meta[1].off, 8); + e.setValue(plan.AttnArgs{ .heads = H, .kv_heads = KV, .ring = ring, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 9); + e.dispatchGroups(mtl.Size.of(rows * H, stride, 1), mtl.Size.of(32, 1, 1)); + } + e.barrier(); + e.setPipeline(p.merge); + e.setBuffer(p.po.buf, p.po.off, 0); + e.setBuffer(p.pml.buf, p.pml.off, 1); + e.setBuffer(p.refs[4].buf, p.refs[4].off, 2); + e.setBuffer(p.refs[5].buf, p.refs[5].off, 3); + e.setBuffer(p.meta[0].buf, p.meta[0].off, 4); + e.setBuffer(p.out[0].buf, p.out[0].off, 5); + e.setValue(plan.MergeArgs{ .heads = H, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride }, 6); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(D, 1, 1)); + } + try p.rig.finish(pass); + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + if (p.which == .rel_table) return p.tableRef(null, want, mag); + if (controls.isAttention(p.which)) return p.attentionRef(null, want, mag); + return p.prepRef(null, want, mag); + } + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try p.a.alloc(f64, out.len); + defer p.a.free(mag); + const sim: Sim = .{ .acc = acc, .order = order }; + if (p.which == .rel_table) return p.tableRef(sim, out, mag); + if (controls.isAttention(p.which)) return p.attentionRef(sim, out, mag); + return p.prepRef(sim, out, mag); + } + fn tableRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + var terms: [R]f64 = undefined; + for (want, mag, 0..) |*w, *m, o| { + const rh = o / EXTENT; + const d = o % EXTENT; + for (&terms, 0..) |*v, j| v.* = bf(p.rel[rh * R + j]) * bf(p.proj[j * EXTENT + d]); + m.* = 0; + for (terms) |x| m.* += @abs(x); + const x = sum(&terms, sim); + w.* = if (sim != null) rn(x) else x; + } + } + fn headClip(x: []const f64, threshold: f64, sim: ?Sim, t: ?f64, want: []f64, mag: []f64) void { + var sq: [D]f64 = undefined; + mZero(mag); + for (sq[0..x.len], x, 0..) |*v, y, i| { + v.* = y * y; + mag[i] = @abs(y); + } + const f = minNum(threshold / (@sqrt(sum(sq[0..x.len], sim)) + 1e-6), 1); + for (want, x, mag) |*w, v, *m| { + w.* = rn(v * f); + if (t) |tv| w.* = rn(w.* * tv); + m.* = @abs(v) + v * v; + } + } + /// prep uses independent K/V and attention uses populated ring caches; q and rel never alias either one. + fn prepRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + const z = p.sizes(); + var x: [D]f64 = undefined; + for (0..p.shape.rows) |r| { + const tv: ?f64 = if (p.layer.tau) tau(p.pos[r]) else null; + for (0..H) |h| { + for (&x, 0..) |*v, d| v.* = bf(p.q[(r * H + h) * D + d]) * bf(p.qs[h * D + d]); + headClip(&x, 22.627416997969522, sim, tv, want[(r * H + h) * D ..][0..D], mag[(r * H + h) * D ..][0..D]); + for (x[0..R], 0..) |*v, d| v.* = bf(p.rel[(r * H + h) * R + d]) * bf(p.rs[h * R + d]); + const at = z[0] + (r * H + h) * R; + headClip(x[0..R], 8, sim, tv, want[at..][0..R], mag[at..][0..R]); + } + for (0..KV) |h| { + const slot = (h * p.layer.ring + p.pos[r] % p.layer.ring) * D; + for (&x, 0..) |*v, d| v.* = bf(p.kc[(r * KV + h) * D + d]); + headClip(&x, 22.627416997969522, sim, null, want[z[0] + z[1] + slot ..][0..D], mag[z[0] + z[1] + slot ..][0..D]); + var sq: [D]f64 = undefined; + for (&x, &sq, 0..) |*v, *ss, d| { + v.* = bf(p.vc[(r * KV + h) * D + d]); + ss.* = v.* * v.*; + } + const inv = 1 / @sqrt(sum(&sq, sim) / D + 1e-6); + for (0..D) |d| { + const at = z[0] + z[1] + z[2] + slot + d; + want[at] = rn(x[d] * inv); + mag[at] = sq[d] + @abs(x[d]); + } + } + } + } + fn mZero(mag: []f64) void { + @memset(mag, 0); + } + fn attentionRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + const most = p.shape.k; + const score = try p.a.alloc(f64, most); + defer p.a.free(score); + const weights = try p.a.alloc(f64, most); + defer p.a.free(weights); + const terms = try p.a.alloc(f64, @max(most, D)); + defer p.a.free(terms); + for (0..p.shape.rows) |r| { + for (0..H) |h| { + const rh = r * H + h; + const pos = p.pos[r]; + const lo = if (p.layer.window > 0) (pos + 1) -| p.layer.window else 0; + const n = pos + 1 - lo; + const kvh = h / (H / KV); + const z = bf(p.sink[rh]); + // Prompt P is BF16 at the keys' maximum; the sink joins in the final merge using the shared maximum. + const prompt = sim == null and controls.isPrompt(p.which); + var peak = if (prompt) -std.math.inf(f64) else z; + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; + for (0..D) |d| terms[d] = bf(p.q[rh * D + d]) * bf(p.kc[at + d]); + const distance = pos - kp; + const bias = if (distance < EXTENT) bf(p.tab[rh * EXTENT + distance]) else 0; + score[j] = sum(terms[0..D], sim) * scale + bias; + peak = maxNan(peak, score[j]); + } + if (prompt) { + peak = promptWeights(score[0..n], weights[0..n]); + } else for (weights[0..n], score[0..n]) |*w, sc| w.* = @exp(sc - peak); + const merged_peak = if (prompt) maxNan(peak, z) else peak; + const rescale = if (prompt) @exp(peak - merged_peak) else 1; + const den = sum(weights[0..n], sim) * rescale + @exp(z - merged_peak); + for (0..D) |d| { + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; + terms[j] = weights[j] * bf(p.vc[at + d]); + } + const num = sum(terms[0..n], sim) * rescale; + const y = num / den * sigmoid(bf(p.gate[rh * D + d])); + want[rh * D + d] = if (sim != null) rn(y) else y; + mag[rh * D + d] = (@abs(num) + den + 1) * (1 + @abs(y)); + for (terms[0..n]) |v| mag[rh * D + d] += @abs(v * rescale); + } + } + } + } +}; + +fn supported(device: mtl.Device, w: Which) bool { + return switch (w) { + .prompt_m5 => device.tensorUnits(), + .prompt_pre_m5 => !device.tensorUnits(), + else => true, + }; +} +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Which)) |w| { + if (!supported(s.device, w) or (only != null and std.mem.indexOf(u8, spec(w).name, only.?) == null)) continue; + try s.add(w, .none); + } + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const w = m.which(); + if (!supported(s.device, w) or (only != null and std.mem.indexOf(u8, m.name(), only.?) == null)) continue; + try s.add(w, m); + } + } + fn add(s: *Suite, w: Which, m: Mutation) !void { + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = Probe.init(s.a, s.device, s.queue, w, m) catch |err| { + var k: g.Kernel = .{ .spec = spec(w), .ctx = undefined, .vt = undefined, .control = m.gate(), .init_error = err }; + if (m != .none) k.spec.name = m.name(); + try s.kernels.append(s.a, k); + s.a.destroy(p); + return; + }; + try s.probes.append(s.a, p); + try s.kernels.append(s.a, p.kernel()); + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_attention_controls.zig b/zig/tests/contract/metal_inkling2_attention_controls.zig new file mode 100644 index 00000000000..f4b9cc69cb9 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention_controls.zig @@ -0,0 +1,157 @@ +//! Count-checked, discriminating source edits for every Inkling 2 attention shader entry point. +const std = @import("std"); +const contract = @import("contract"); + +pub const Which = enum { prep_sliding, prep_global, rel_table, decode_sliding, decode_global, prompt_m5, prompt_pre_m5 }; +pub fn function(w: Which) []const u8 { + return switch (w) { + .prep_sliding, .prep_global => "tf_ink2_prep", + .rel_table => "tf_ink2_rel_table", + .decode_sliding, .decode_global => "tf_ink2_attn_scalar", + .prompt_m5, .prompt_pre_m5 => "tf_ink2_attn_prompt", + }; +} +pub fn isPrompt(w: Which) bool { + return w == .prompt_m5 or w == .prompt_pre_m5; +} +pub fn isAttention(w: Which) bool { + return w == .decode_sliding or w == .decode_global or isPrompt(w); +} + +pub const Mutation = enum { + none, + prep_swap_kv, + prep_tau_off, + rel_late, + decode_late_bias, + merge_no_sink, + prompt_late_bias, + prompt_pre_late_bias, + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .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", + .rel_late => "control: metal inkling2 attention relative projection one column late tf_ink2_rel_table", + .decode_late_bias => "control: metal inkling2 attention sliding first key score boosted tf_ink2_attn_scalar", + .merge_no_sink => "control: metal inkling2 attention global merge without sink tf_ink2_merge", + .prompt_late_bias => "control: metal inkling2 prompt m5 first key bias boosted tf_ink2_attn_prompt", + .prompt_pre_late_bias => "control: metal inkling2 prompt pre-m5 first key bias boosted tf_ink2_attn_prompt", + }; + } + pub fn gate(m: Mutation) ?contract.gates.Gate { + return if (m == .none) null else .shapes; + } + pub fn which(m: Mutation) Which { + return switch (m) { + .none => unreachable, + .prep_swap_kv => .prep_sliding, + .prep_tau_off => .prep_global, + .rel_late => .rel_table, + .decode_late_bias => .decode_sliding, + .merge_no_sink => .decode_global, + .prompt_late_bias => .prompt_m5, + .prompt_pre_late_bias => .prompt_pre_m5, + }; + } + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .prep_swap_kv => .{ + .from = "const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D;", + .to = "const device bfloat* src = (key ? v_raw : k_raw) + (size_t(row) * a.kv_heads + h) * D;", + }, + .prep_tau_off => .{ + .from = "const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f;", + .to = "const float tau = 1.0f;", + }, + .rel_late => .{ + .from = "acc += r[j] * float(proj[j * EXTENT + d]);", + .to = "acc += r[j] * float(proj[j * EXTENT + (d + 1) % EXTENT]);", + }, + .decode_late_bias => .{ + .from = "const float score = (dot_score * a.scale + bias) * LOG2E;", + .to = "const float score = (dot_score * a.scale + bias + (kp == from ? 128.0f : 0.0f)) * LOG2E;", + }, + .merge_no_sink => .{ + .from = "const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", + .to = "const float sk = -INFINITY, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", + }, + .prompt_late_bias, .prompt_pre_late_bias => .{ + .from = "const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;", + .to = "const float bias = (live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f) + (live && kp == b_lo ? 128.0f : 0.0f);", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, text: []const u8, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, text); + const e = m.edit(); + if (std.mem.count(u8, text, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, text, e.from, e.to); +} + +test "Inkling 2 attention controls each hit one live statement and cannot apply twice" { + const a = std.testing.allocator; + const sources = @import("inkling2_metal"); + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const w = m.which(); + const plain = if (isPrompt(w)) (if (w == .prompt_pre_m5) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const edited = try apply(a, plain, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectError(error.ControlEditMissing, apply(a, edited, m)); + try std.testing.expectEqual(contract.gates.Gate.shapes, m.gate().?); + } + const unchanged = try apply(a, sources.attention, .none); + defer a.free(unchanged); + try std.testing.expectEqualStrings(sources.attention, unchanged); +} + +fn fp64Clip(src: []const f64, dst: []f64, threshold: f64) void { + var ss: f64 = 0; + for (src) |x| ss += x * x; + const f = @min(threshold / (@sqrt(ss) + 1e-6), 1); + for (dst, src) |*y, x| y.* = x * f; +} + +fn fp64Rms(src: []const f64, dst: []f64) void { + var ss: f64 = 0; + for (src) |x| ss += x * x; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(src.len)) + 1e-6); + for (dst, src) |*y, x| y.* = x * inv; +} + +test "Inkling 2 gated FP64 prep exchanges only K/V" { + const q = [4]f64{ 4, 0, 0, 0 }; + const rel = [4]f64{ 4, 0, 0, 0 }; + const k = [4]f64{ 4, 0, 0, 0 }; + const v = [4]f64{ 0, 3, 0, 0 }; + var q_base: [4]f64 = undefined; + var q_swap: [4]f64 = undefined; + var rel_base: [4]f64 = undefined; + var rel_swap: [4]f64 = undefined; + var k_base: [4]f64 = undefined; + var k_swap: [4]f64 = undefined; + var v_base: [4]f64 = undefined; + var v_swap: [4]f64 = undefined; + fp64Clip(&q, &q_base, 5); + fp64Clip(&q, &q_swap, 5); + fp64Clip(&rel, &rel_base, 5); + fp64Clip(&rel, &rel_swap, 5); + fp64Clip(&k, &k_base, 5); + fp64Clip(&v, &k_swap, 5); + fp64Rms(&v, &v_base); + fp64Rms(&k, &v_swap); + try std.testing.expectEqualSlices(f64, &q_base, &q_swap); + try std.testing.expectEqualSlices(f64, &rel_base, &rel_swap); + try std.testing.expectEqualSlices(f64, &.{ 4, 0, 0, 0 }, &k_base); + try std.testing.expectEqualSlices(f64, &.{ 0, 3, 0, 0 }, &k_swap); + const v_from_v = 3 * (1 / @sqrt(@as(f64, 9) / 4 + 1e-6)); + const v_from_k = 4 * (1 / @sqrt(@as(f64, 16) / 4 + 1e-6)); + try std.testing.expectEqualSlices(f64, &.{ 0, v_from_v, 0, 0 }, &v_base); + try std.testing.expectEqualSlices(f64, &.{ v_from_k, 0, 0, 0 }, &v_swap); +} diff --git a/zig/tests/contract/metal_inkling2_dspark.zig b/zig/tests/contract/metal_inkling2_dspark.zig new file mode 100644 index 00000000000..6274197e9d0 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark.zig @@ -0,0 +1,590 @@ +//! Mini DSpark's ten real Metal launches with guarded buffers, FP64 references and red controls. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_dspark_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_dspark_host; +const sources = @import("inkling2_metal"); + +const H = host.hidden; +const Q = host.query_width; +const KV = host.kv_width; +const RANK = host.rank; +const RNN = host.rnn_width; +const INTER = host.intermediate; + +fn depth(s: c.Shape) usize { + return s.k + 16; +} +fn bf(v: anytype) f64 { + return host.roundBf16(v); +} +fn rounded(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} +fn rms(values: []const f32, start: usize, width: usize) f32 { + var sum: f32 = 0; + for (0..width) |d| { + const x = values[start + d]; + sum += x * x; + } + return 1.0 / @sqrt(sum / @as(f32, @floatFromInt(width)) + 1e-6); +} +fn rope(d: usize, position: usize, x: f32, other: f32) f64 { + const frequency = std.math.pow(f32, 1e6, -@as(f32, @floatFromInt(d % 64)) / 64.0); + const angle = @as(f32, @floatFromInt(position)) * frequency; + const rotated: f32 = if (d < 64) x * @cos(angle) - other * @sin(angle) else other * @sin(angle) + x * @cos(angle); + return bf(rotated); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: host.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [6]c.Shape = undefined, + served_len: usize = 0, + f: [8][]f32 = @splat(&.{}), + phi: []u16 = &.{}, + refs: [8]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + score_scratch: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: host.Kind) !Probe { + return initSource(a, device, queue, kind, sources.inkling2_dspark); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: host.Kind, text: []const u8) !Probe { + var self: Probe = .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .pipes = try host.Pipelines.loadSource(device, text) }; + switch (kind) { + .init_rows => self.setServed(&.{.{ .rows = 8, .n = H, .k = 0 }}), + .fuse_taps => self.setServed(&.{ .{ .rows = 5, .n = H, .k = 0 }, .{ .rows = 1, .n = H, .k = 0 }, .{ .rows = 3, .n = H, .k = 0 }, .{ .rows = 7, .n = H, .k = 0 } }), + .block_qkv => self.setServed(&.{ .{ .rows = 8, .n = Q, .k = 17 }, .{ .rows = 8, .n = Q, .k = 67 } }), + .context_kv => self.setServed(&.{ .{ .rows = 5, .n = KV, .k = 17 }, .{ .rows = 1, .n = KV, .k = 31 }, .{ .rows = 3, .n = KV, .k = 47 }, .{ .rows = 8, .n = KV, .k = 67 } }), + .attention => self.setServed(&.{ + .{ .rows = 8, .n = 0, .k = 0 }, + .{ .rows = 8, .n = 1, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 5 }, + .{ .rows = 8, .n = 1025, .k = 1 }, + .{ .rows = 8, .n = 1025, .k = 7 }, + }), + .residual_norm => self.setServed(&.{ .{ .rows = 8, .n = H, .k = 1 }, .{ .rows = 8, .n = H, .k = 0 } }), + .swiglu => self.setServed(&.{.{ .rows = 8, .n = INTER, .k = 0 }}), + .kappa => self.setServed(&.{ .{ .rows = 5, .n = RNN, .k = 0 }, .{ .rows = 1, .n = RNN, .k = 0 }, .{ .rows = 3, .n = RNN, .k = 0 }, .{ .rows = 7, .n = RNN, .k = 0 } }), + .recurrent => self.setServed(&.{.{ .rows = 8, .n = RNN, .k = 0 }}), + .base => self.setServed(&.{ .{ .rows = 5, .n = 5, .k = 0 }, .{ .rows = 1, .n = 1, .k = 0 }, .{ .rows = 3, .n = 17, .k = 0 }, .{ .rows = 7, .n = 129, .k = 0 } }), + .logits => self.setServed(&.{.{ .rows = 8, .n = host.vocab, .k = 0 }}), + } + return self; + } + fn setServed(self: *Probe, shapes: []const c.Shape) void { + @memcpy(self.served[0..shapes.len], shapes); + self.served_len = shapes.len; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + + const vt = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = &vt, .spec = .{ + .name = self.kind.label(), + .accum = .none, + .depth = depth, + .ops = 0, + .mids = 0, + .out = if (self.kind == .kappa) .f32 else .bf16, + .served = self.served[0..self.served_len], + .sums = .{ .f16 = 0, .bf16 = 0, .why = "explicit serial FP32 reference and required BF16 nodes are checked directly" }, + } }; + } + pub fn count(self: *Probe) usize { + return switch (self.kind) { + .init_rows => 8 * H, + .fuse_taps => (4 * self.shape.rows + 1) * H, + .block_qkv => 8 * (Q + 2 * KV), + .context_kv => 2 * self.shape.rows * KV, + .attention => 8 * Q, + .residual_norm => 2 * 8 * H, + .swiglu => 8 * INTER, + .kappa => self.shape.rows * RNN, + .recurrent => RNN + 2 * RANK, + .base => self.shape.rows * self.shape.n, + .logits => host.vocab, + }; + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = rng.float(f32) * 0.5 - 0.25; + return values; + } + fn input(self: *Probe, values: []const f32, is_bf: bool) !rig_.Ref { + if (!is_bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + fn output(self: *Probe, slot: usize, elements: usize, elem: c.Elem) !void { + self.outs[slot] = try self.rig.output(elements * c.size(elem)); + } + fn first(self: *const Probe) usize { + const from = self.shape.k / 2; + const local = self.shape.k % 2 != 0; + return @max(from, if (local and self.shape.n > 1024) self.shape.n - 1024 else 0); + } + + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + var admitted = false; + for (self.served[0..self.served_len]) |served| if (std.meta.eql(shape, served)) { + admitted = true; + break; + }; + if (!admitted) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + self.phi = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + const rows = shape.rows; + switch (self.kind) { + .init_rows => { + self.f[0] = try self.floats(H, rng); + self.f[1] = try self.floats(H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + rounded(self.f[0]); + rounded(self.f[1]); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + try self.output(0, 8 * H, .bf16); + }, + .fuse_taps => { + self.f[0] = try self.floats(rows * 4 * H, rng); + self.f[1] = try self.floats(16, rng); + self.f[2] = try self.floats(4 * H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + @memcpy(self.f[1][0..4], &[_]f32{ 0, 0.5, -0.25, 2 }); + for (self.f[0][0 .. 4 * H]) |*v| v.* *= 400; + rounded(self.f[0]); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 4 * rows * H, .bf16); + try self.output(1, H, .bf16); + }, + .block_qkv => { + const sizes = [_]usize{ 8 * Q, 8 * KV, 8 * KV, 128, 128 }; + for (sizes, 0..) |n, j| { + self.f[j] = try self.floats(n, rng); + rounded(self.f[j]); + self.refs[j] = try self.input(self.f[j], true); + } + if (nf) { + self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + } + try self.output(0, 8 * Q, .bf16); + try self.output(1, 8 * KV, .bf16); + try self.output(2, 8 * KV, .bf16); + }, + .context_kv => { + self.f[0] = try self.floats(rows * KV, rng); + self.f[1] = try self.floats(rows * KV, rng); + self.f[2] = try self.floats(128, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, rows * KV, .bf16); + try self.output(1, rows * KV, .bf16); + }, + .attention => { + const ring = @max(shape.n, 1); + const sizes = [_]usize{ 8 * Q, 8 * KV, 8 * KV, ring * KV, ring * KV }; + for (sizes, 0..) |n, j| { + self.f[j] = try self.floats(n, rng); + rounded(self.f[j]); + self.refs[j] = try self.input(self.f[j], true); + } + if (nf) { + self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + } + self.score_scratch = try self.rig.scratch(8 * 24 * (shape.n - self.first() + 8) * 4); + self.refs[5] = self.score_scratch; + try self.output(0, 8 * Q, .bf16); + }, + .residual_norm => { + self.f[0] = try self.floats(8 * H, rng); + self.f[1] = try self.floats(8 * H, rng); + self.f[2] = try self.floats(H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 8 * H, .bf16); + try self.output(1, 8 * H, .bf16); + }, + .swiglu => { + self.f[0] = try self.floats(8 * INTER, rng); + self.f[1] = try self.floats(8 * INTER, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..2]) |values| rounded(values); + for (0..2) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 8 * INTER, .bf16); + }, + .kappa => { + self.f[0] = try self.floats(rows * H, rng); + self.f[1] = try self.floats(H, rng); + self.f[2] = try self.floats(RNN * 5120, rng); + self.f[3] = try self.floats(RNN, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..4]) |values| rounded(values); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, rows * RNN, .f32); + }, + .recurrent => { + self.f[0] = try self.floats(RANK, rng); + self.f[1] = try self.floats(RNN, rng); + self.f[2] = try self.floats(RNN * 5120, rng); + self.f[3] = try self.floats(2 * RANK, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..4]) |values| rounded(values); + @memset(self.f[0], 99.5); + self.f[1][0] = c.fromBf16(c.toBf16(0.6)); + self.f[1][RANK] = c.fromBf16(c.toBf16(0.8)); + self.f[1][2 * RANK] = c.fromBf16(c.toBf16(0.3)); + for ([_]usize{ 0, RANK, 2 * RANK }) |channel| @memset(self.f[2][channel * 5120 ..][0..512], 0); + if (nf) self.f[0][0] = std.math.nan(f32); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, RNN, .bf16); + try self.output(1, RANK, .bf16); + try self.output(2, RANK, .bf16); + }, + .logits => { + self.f[0] = try self.floats(host.vocab, rng); + self.f[1] = try self.floats(host.vocab, rng); + self.f[2] = try self.floats(RANK, rng); + for (self.f[0]) |*v| v.* = rng.float(f32) * 120 - 60; + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + self.f[0][0] = 40; + self.f[0][1] = 1000; + self.f[1][0] = 0.125; + if (nf) self.f[0][0] = std.math.nan(f32); + self.f[2][0] = c.fromBf16(c.toBf16(0.0001)); + self.phi = try self.arena.allocator().alloc(u16, host.vocab * RANK); + for (self.phi) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + @memset(self.phi[0..RANK], 0); + self.phi[0] = c.toBf16(1); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(self.phi)); + self.refs[2] = try self.input(self.f[1], true); + self.refs[3] = try self.input(self.f[2], true); + try self.output(0, host.vocab, .bf16); + }, + .base => { + self.f[0] = try self.floats(shape.n * H, rng); + self.f[1] = try self.floats(rows * H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + rounded(self.f[0]); + rounded(self.f[1]); + if (!nf) { + @memset(self.f[0][0..H], 1); + @memset(self.f[1][0..H], 1); + } + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + try self.output(0, rows * shape.n, .bf16); + }, + } + return true; + } + + fn hostRef(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const R = self.refs; + const O = self.outs; + const p = &self.pipes; + switch (self.kind) { + .init_rows => host.initializeRows(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0])), + .fuse_taps => host.fuseTaps(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), @intCast(self.shape.rows)), + .block_qkv => host.blockQkv(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(R[4]), hostRef(O[0]), hostRef(O[1]), hostRef(O[2]), @intCast(self.shape.k)), + .context_kv => host.commitContext(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), @intCast(self.shape.k), @intCast(self.shape.rows), @intCast(self.shape.rows)), + .attention => host.attend(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(R[4]), hostRef(self.score_scratch), hostRef(O[0]), @intCast(self.shape.n), @intCast(@max(self.shape.n, 1)), self.shape.k % 2 != 0, @intCast(self.shape.k / 2)), + .residual_norm => host.residualNorm(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), 8, self.shape.k != 0), + .swiglu => host.swiglu(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0]), 8 * INTER), + .kappa => host.kappa(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0]), @intCast(self.shape.rows)), + .recurrent => host.recurrentStep(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0]), hostRef(O[1]), hostRef(O[2]), 1), + .base => host.base(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0]), @intCast(self.shape.rows), @intCast(self.shape.n)), + .logits => host.finalLogits(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0])), + } + try self.rig.finish(pass); + } + + fn fusionReference(self: *Probe, want: []f64) void { + const rows = self.shape.rows; + for (0..4) |fusion| { + var scores: [4]f32 = undefined; + var peak: f32 = -std.math.inf(f32); + for (0..4) |j| { + scores[j] = self.f[1][fusion * 4 + j]; + peak = @max(peak, scores[j]); + } + var den: f32 = 0; + for (0..4) |j| { + scores[j] = @exp(scores[j] - peak); + den += scores[j]; + } + var alpha: [4]f32 = undefined; + for (0..4) |j| alpha[j] = @floatCast(bf(scores[j] / den)); + for (0..rows) |row| { + var square: f32 = 0; + for (0..H) |d| { + var mixed: f32 = 0; + for (0..4) |j| mixed += alpha[j] * self.f[0][(row * 4 + j) * H + d]; + square += mixed * mixed; + } + const scale: f32 = 1.0 / @sqrt(square / H + 1e-6); + for (0..H) |d| { + var mixed: f32 = 0; + for (0..4) |j| mixed += alpha[j] * self.f[0][(row * 4 + j) * H + d]; + const out = bf(mixed * scale * self.f[2][fusion * H + d]); + want[(fusion * rows + row) * H + d] = out; + if (fusion == 3 and row + 1 == rows) want[4 * rows * H + d] = out; + } + } + } + } + fn qkvReference(self: *Probe, want: []f64) void { + for (0..8) |row| for (0..24) |h| for (0..128) |d| { + const at = row * Q + h * 128 + d; + const other_at = row * Q + h * 128 + (if (d < 64) d + 64 else d - 64); + const scale = rms(self.f[0], row * Q + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[0][at] * scale * self.f[3][d])); + const other: f32 = @floatCast(bf(self.f[0][other_at] * scale * self.f[3][if (d < 64) d + 64 else d - 64])); + want[at] = rope(d, self.shape.k + row, x, other); + }; + const offset = 8 * Q; + for (0..8) |row| for (0..8) |h| for (0..128) |d| { + const at = row * KV + h * 128 + d; + const other_at = row * KV + h * 128 + (if (d < 64) d + 64 else d - 64); + const scale = rms(self.f[1], row * KV + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[1][at] * scale * self.f[4][d])); + const other: f32 = @floatCast(bf(self.f[1][other_at] * scale * self.f[4][if (d < 64) d + 64 else d - 64])); + want[offset + at] = rope(d, self.shape.k + row, x, other); + want[offset + 8 * KV + at] = self.f[2][at]; + }; + } + fn contextReference(self: *Probe, want: []f64) void { + const rows = self.shape.rows; + for (0..rows) |row| for (0..8) |h| for (0..128) |d| { + const src = row * KV + h * 128 + d; + const dst = ((self.shape.k + row) % rows) * KV + h * 128 + d; + const partner = if (d < 64) d + 64 else d - 64; + const other_src = row * KV + h * 128 + partner; + const scale = rms(self.f[0], row * KV + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[0][src] * scale * self.f[2][d])); + const other: f32 = @floatCast(bf(self.f[0][other_src] * scale * self.f[2][partner])); + want[dst] = rope(d, self.shape.k + row, x, other); + want[rows * KV + dst] = self.f[1][src]; + }; + } + fn attentionReference(self: *Probe, want: []f64) !void { + const committed = self.shape.n; + const first_kept = self.first(); + const retained = committed - first_kept; + const score_count = retained + 8; + const ring = @max(committed, 1); + const scores = try self.a.alloc(f32, score_count); + defer self.a.free(scores); + for (0..8) |row| for (0..24) |h| { + const kv = h / 3; + const q_at = row * Q + h * 128; + var peak: f32 = -std.math.inf(f32); + for (0..score_count) |j| { + var dot: f32 = 0; + const k_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 else (j - retained) * KV + kv * 128; + const keys = if (j < retained) self.f[3] else self.f[1]; + for (0..128) |d| dot += self.f[0][q_at + d] * keys[k_at + d]; + scores[j] = dot * @as(f32, 0x1.6a09e6p-7); + peak = @max(peak, scores[j]); + } + var den: f32 = 0; + for (scores) |s| den += @exp(s - peak); + for (0..128) |d| { + var sum: f32 = 0; + for (0..score_count) |j| { + const v_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 + d else (j - retained) * KV + kv * 128 + d; + const values = if (j < retained) self.f[4] else self.f[2]; + sum += (@exp(scores[j] - peak) / den) * values[v_at]; + } + want[q_at + d] = bf(sum); + } + }; + } + fn recurrentReference(self: *Probe, want: []f64) void { + for (0..RANK) |i| { + var z: [3]f32 = undefined; + for (0..3) |part| { + const channel = part * RANK + i; + var sum: f32 = 0; + for (0..RANK) |d| sum += self.f[0][d] * self.f[2][channel * 5120 + d]; + for (0..RANK) |d| sum += self.f[3][RANK + d] * self.f[2][channel * 5120 + 256 + d]; + sum += self.f[1][channel]; + z[part] = @floatCast(bf(sum)); + want[channel] = z[part]; + } + const gamma: f32 = @floatCast(bf(1.0 / (1.0 + @exp(-z[0])))); + const candidate: f32 = @floatCast(bf(std.math.tanh(z[1]))); + const keep: f32 = @floatCast(bf(1.0 - gamma)); + const left: f32 = @floatCast(bf(gamma * self.f[0][i])); + const right: f32 = @floatCast(bf(keep * candidate)); + want[RNN + i] = bf(left + right); + want[RNN + RANK + i] = bf(std.math.tanh(z[2])); + } + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + switch (self.kind) { + .init_rows => for (0..8) |row| { + for (0..H) |d| want[row * H + d] = self.f[if (row == 0) 0 else 1][d]; + }, + .fuse_taps => self.fusionReference(want), + .block_qkv => self.qkvReference(want), + .context_kv => self.contextReference(want), + .attention => try self.attentionReference(want), + .residual_norm => for (0..8) |row| { + var square: f32 = 0; + for (0..H) |d| { + const at = row * H + d; + const sigma: f32 = if (self.shape.k != 0) self.f[0][at] else self.f[0][at] + self.f[1][at]; + square += sigma * sigma; + } + const scale: f32 = 1.0 / @sqrt(square / H + 1e-6); + for (0..H) |d| { + const at = row * H + d; + const sigma: f32 = if (self.shape.k != 0) self.f[0][at] else self.f[0][at] + self.f[1][at]; + want[at] = bf(sigma); + want[8 * H + at] = bf(sigma * scale * self.f[2][d]); + } + }, + .swiglu => for (want, 0..) |*w, i| { + const gate = self.f[0][i]; + w.* = bf((gate / (1.0 + @exp(-gate))) * self.f[1][i]); + }, + .kappa => for (0..self.shape.rows) |row| for (0..RNN) |channel| { + var sum: f32 = 0; + for (0..H) |d| sum += self.f[0][row * H + d] * self.f[2][channel * 5120 + 512 + d]; + for (0..H) |d| sum += self.f[1][d] * self.f[2][channel * 5120 + 2816 + d]; + sum += self.f[3][channel]; + want[row * RNN + channel] = sum; + }, + .recurrent => self.recurrentReference(want), + .base => for (0..self.shape.rows) |row| for (0..self.shape.n) |id| { + var dot: f32 = 0; + for (0..H) |d| dot += self.f[0][id * H + d] * self.f[1][row * H + d]; + want[row * self.shape.n + id] = bf(dot); + }, + .logits => for (0..host.vocab) |i| { + var dot: f32 = 0; + for (0..RANK) |d| dot += c.fromBf16(self.phi[i * RANK + d]) * self.f[2][d]; + const bias: f32 = @floatCast(bf(self.f[1][i] + dot)); + const logit: f32 = @floatCast(bf(self.f[0][i] + bias)); + want[i] = bf(30.0 * std.math.tanh(logit / 30.0)); + }, + } + for (mag, want) |*m, w| m.* = 1 + @abs(w); + } + + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (gate != .shapes and gate != .nonfinite) return "numeric hooks must be used"; + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + const bytes = try self.rig.outputBytes(); + for (want, 0..) |w, i| { + if (self.kind == .kappa) { + const got = c.read(.f32, bytes, i); + if (gate == .nonfinite and c.classOf(got) != c.classOf(w)) return "kappa floating-point class differs"; + if (gate == .shapes and std.math.isFinite(w) and @abs(got - w) > 2e-5 * @max(1, @abs(w))) return "FP32 kappa dot or column split differs"; + } else { + const bits = std.mem.readInt(u16, bytes[2 * i ..][0..2], .little); + const expected = c.toBf16(@floatCast(w)); + if (std.math.isNan(w)) { + if (!std.math.isNan(c.fromBf16(bits))) return "BF16 NaN was not propagated"; + } else if (bits != expected) { + const relative: f64 = switch (self.kind) { + .fuse_taps, .block_qkv, .context_kv, .swiglu, .logits => 0.02, + .attention => 0.03, + .base => 0, + else => 0, + }; + const got = c.fromBf16(bits); + if (@abs(@as(f64, got) - w) > @max(1e-5, relative * @abs(w))) return "BF16 endpoint differs from the explicit FP32/FP64 reference"; + } + } + } + if (self.kind == .logits and gate == .shapes) { + if (!(want[1] <= 30 and want[1] > 29.9)) return "the planted large logit does not prove softcap saturation"; + } + if (self.kind == .base and gate == .shapes and self.f[0][0] == 1) { + if (want[0] != 2304) return "raw base projection was softened instead of rounded once"; + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: host.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(@fromBackingInt(@intCast(@backingInt(kind)))) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.inkling2_dspark, @fromBackingInt(@intCast(@backingInt(kind)))); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else probe.* = try Probe.init(s.a, s.device, s.queue, kind); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(host.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_dspark_controls.zig b/zig/tests/contract/metal_inkling2_dspark_controls.zig new file mode 100644 index 00000000000..638e1535fdf --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_controls.zig @@ -0,0 +1,56 @@ +//! One host-checkable arithmetic mutation for every Mini DSpark Metal kernel. +const std = @import("std"); + +pub const Kind = enum { init_rows, fuse_taps, block_qkv, context_kv, attention, residual_norm, swiglu, kappa, recurrent, base, logits }; +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: Kind) Edit { + return switch (kind) { + .init_rows => .{ .from = "rows[row * DSP_H + d] = src[d];", .to = "rows[row * DSP_H + d] = mask[d];" }, + .fuse_taps => .{ .from = "alpha[j] = float(bfloat(scores[j] / sum));", .to = "alpha[j] = scores[j] / sum;" }, + .block_qkv => .{ .from = "const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs;", .to = "const float rotated = d < 64 ? x * cs - other * sn : x * sn + other * cs;" }, + .context_kv => .{ .from = "keys[at] = bfloat(d < 64 ? x * cs - other * sn : other * sn + x * cs);", .to = "keys[at] = bfloat(d < 64 ? x * cs - other * sn : x * sn + other * cs);" }, + .attention => .{ .from = "const uint first = max(a.from, a.local && a.committed > 1024 ? a.committed - 1024 : 0);", .to = "const uint first = a.from;" }, + .residual_norm => .{ .from = "normalized[at] = bfloat(sigma * scale * float(weight[d]));", .to = "normalized[at] = bfloat(float(new_residual[at]) * scale * float(weight[d]));" }, + .swiglu => .{ .from = "out[i] = bfloat((gate / (1.0f + exp(-gate))) * float(u[i]));", .to = "out[i] = bfloat(gate * float(u[i]));" }, + .kappa => .{ .from = "sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + 512 + d]);", .to = "sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + d]);" }, + .recurrent => .{ .from = "const bfloat left = bfloat(float(gamma) * float(state[i]));", .to = "const float left = float(gamma) * float(state[i]);" }, + .base => .{ .from = "out[i] = bfloat(dot);", .to = "out[i] = bfloat(30.0f * tanh(dot / 30.0f));" }, + .logits => .{ .from = "const bfloat bias = bfloat(float(beta[i]) + dot);", .to = "const float bias = float(beta[i]) + dot;" }, + }; +} + +pub fn name(kind: Kind) []const u8 { + return switch (kind) { + inline else => |k| "control: metal inkling2 dspark " ++ @tagName(k), + }; +} +pub fn source(a: std.mem.Allocator, production: []const u8, kind: Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +test "every DSpark control applies once and only mutates its arithmetic anchor" { + const production = @import("inkling2_metal").inkling2_dspark; + const a = std.testing.allocator; + for (std.enums.values(Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "repeated DSpark control anchors are refused" { + const production = @import("inkling2_metal").inkling2_dspark; + const a = std.testing.allocator; + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + for (std.enums.values(Kind)) |kind| try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); +} diff --git a/zig/tests/contract/metal_inkling2_experts.zig b/zig/tests/contract/metal_inkling2_experts.zig new file mode 100644 index 00000000000..55c9a3d1c66 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_experts.zig @@ -0,0 +1,409 @@ +//! Inkling 2 Mini M3 contracts: independent FP64 decode/dot/activation and ascending-expert combine. +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_experts_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_decode, mx_decode, combine }; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu", + .nv_down => "tf_ink2_nvfp4_down", + .mx_gu => "tf_ink2_mxfp8_gu", + .mx_down => "tf_ink2_mxfp8_down", + .nv_decode => "tf_ink2_nvfp4_quantize", + .mx_decode => "tf_ink2_mxfp8_quantize", + .combine => "tf_ink2_combine", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_up, + .nv_down => .nv_down_phi, + .mx_gu => .mx_gu_up, + .mx_down => .mx_down_scale, + .nv_decode => .nv_decode_nibble, + .mx_decode => .mx_decode_scale, + .combine => .combine_slot_order, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down or k == .nv_decode; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu; +} +fn isDown(k: Kind) bool { + return k == .nv_down or k == .mx_down; +} +fn isDecode(k: Kind) bool { + return k == .nv_decode or k == .mx_decode; +} +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 experts tf_ink2_nvfp4_gu", + .nv_down => "metal inkling2 experts tf_ink2_nvfp4_down", + .mx_gu => "metal inkling2 experts tf_ink2_mxfp8_gu", + .mx_down => "metal inkling2 experts tf_ink2_mxfp8_down", + .nv_decode => "metal inkling2 experts tf_ink2_nvfp4_quantize", + .mx_decode => "metal inkling2 experts tf_ink2_mxfp8_quantize", + .combine => "metal inkling2 experts tf_ink2_combine", + }; + return .{ + .name = base, + .accum = if (isDecode(k)) .none else .f32, + .depth = depth, + .ops = if (isGu(k)) 12 else if (isDecode(k)) 1 else 3, + .mids = if (isGu(k)) 3 else 0, + .out = .bf16, + .served = switch (k) { + .nv_gu, .mx_gu => &.{ .{ .rows = 2, .n = 4, .k = 32 }, .{ .rows = 4, .n = 8, .k = 64 } }, + .nv_down, .mx_down => &.{ .{ .rows = 2, .n = 8, .k = 32 }, .{ .rows = 4, .n = 12, .k = 64 } }, + .nv_decode, .mx_decode => &.{ .{ .rows = 2, .n = 32, .k = 32 }, .{ .rows = 3, .n = 64, .k = 64 } }, + .combine => &.{ .{ .rows = 2, .n = 8, .k = 8 }, .{ .rows = 4, .n = 12, .k = 8 } }, + }, + .sums = if (k == .combine) .{ .f16 = 0, .bf16 = 100, .why = "bounded cancellation is exact in fp32 but loses its residual in bf16" } else .{ .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 = &.{}, + weights: []f32 = &.{}, + 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); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = try host.Pipelines.loadSource(device, text), .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.a.free(p.weights); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.weights = &.{}; + 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 = if (p.kind == .combine and p.ctl == .combine_slot_order) &vt_exact else &vt, .control = p.ctl.gate() }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + const vt_exact = g.hooks(Probe); + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(if (p.kind == .combine) 32 else p.shape.k), .n = @intCast(p.shape.n), .experts = if (p.kind == .combine) 8 else 4, .topk = if (p.kind == .combine) 8 else 2, .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 > 8) return false; + if (isGu(k) and (shape.n > 8 or shape.k > 64 or shape.k % 32 != 0)) return false; + if (isDown(k) and (shape.n > 12 or shape.k > 64 or shape.k % 32 != 0)) return false; + if (isDecode(k) and (shape.n != shape.k or shape.k > 64 or shape.k % 32 != 0)) return false; + if (k == .combine and (shape.n > 12 or shape.k != 8)) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const topk: usize = if (k == .combine) 8 else 2; + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (!isDecode(k)) { + const nx = if (isGu(k)) shape.rows * shape.k else if (isDown(k)) routes * shape.k else routes * shape.n; + p.x = try p.a.alloc(u16, nx); + 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); + const combine_ids = [_]i32{ 2, 0, 1, 7, 3, 6, 4, 5 }; + // Eight distinct, unsorted routes exercise ascending-expert accumulation. + for (p.ids, 0..) |*id, i| id.* = if (k == .combine) combine_ids[i % 8] else @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = if (isGu(k)) 8 * shape.n else if (isDown(k)) 4 * shape.n else shape.rows; + if (k != .combine) { + 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); + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(125 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (k == .mx_decode) { + p.w[0] = 0x30; + p.scales[0] = 255; // Decodes to 2^127 without first forming an overflowing 2^128. + } + } + if (nv) { + p.amax = try p.a.alloc(f32, if (isDecode(k)) 1 else 4); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75; + } + if (k == .combine) p.weights = try p.a.alloc(f32, routes); + if (fill == .stress and !isDecode(k)) { + 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)); + if (k != .combine) @memset(p.scales, if (nv) 0x38 else 127); + } + if (k == .combine) { + const values = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + for (p.x, 0..) |*v, i| v.* = c.toBf16(if (fill == .stress) 1 else values[i % 8]); + if (fill == .stress) { + const terms = [_]f32{ 1024, 1, 1, 1, 1, 1, 1, -1029 }; + // Map expert indices back to route slots; the ascending sum is 1024 + six 1s - 1029. + for (0..p.shape.rows) |token| for (0..8) |expert| for (0..8) |slot| if (p.ids[token * 8 + slot] == expert) { + p.weights[token * 8 + slot] = terms[expert]; + }; + } else if (p.ctl == .combine_slot_order) { + const control_weights = [_]f32{ 0x1p127, 0x1p126, -0x1p127 / 3.0, 0.25, -0.2, 1.0 / 3.0, -2.0 / 7.0, 0.375 }; + for (p.weights, 0..) |*v, i| v.* = control_weights[i % 8]; + // Only this planted control overflows route order; ascending experts remain finite. + } else { + const ordinary_weights = [_]f32{ 0.125, -0.25, 0.375, -0.5, 0.625, -0.75, 0.875, -1 }; + for (p.weights, 0..) |*v, i| v.* = ordinary_weights[i % 8]; + } + } + if (fill == .nonfinite) { + if (!isDecode(k) 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)); + } else if (isDecode(k) and p.scales.len > 1) { + if (nv) p.scales[0] = 0x7f else p.w[0] = 0x7f; + } + } + const out = try p.rig.output(p.count() * 2); + if (k == .combine) { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.weights)); + p.refs[3] = out; + } else if (isDecode(k)) { + p.refs[0] = try p.rig.input(p.w); + p.refs[1] = try p.rig.input(p.scales); + if (nv) { + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[4] = out; + } else p.refs[2] = out; + } else { + 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); + if (isDecode(p.kind)) { + if (nv) try host.nvfp4Quantize(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), @intCast(p.shape.rows), @intCast(p.shape.k)) else try host.mxfp8Quantize(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.k)); + } else if (isGu(p.kind)) { + if (nv) try host.nvfp4Gu(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), hr(p.refs[5]), hr(p.refs[6]), p.call()) else try host.mxfp8Gu(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), p.call()); + } else if (isDown(p.kind)) { + if (nv) try host.nvfp4Down(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), hr(p.refs[5]), hr(p.refs[6]), p.call()) else try host.mxfp8Down(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), p.call()); + } else try host.combine(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), p.call()); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return if (isGu(p.kind) or isDown(p.kind)) p.shape.rows * 2 * p.shape.n else p.shape.rows * 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 nv = isNv(p.kind); + 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 = if (isDecode(p.kind)) row else expert * rows_per_expert + row; + if (!nv) { + 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[if (isDecode(p.kind)) 0 else 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: [64]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 { + if (isDecode(p.kind)) return .{ .value = p.weight(0, at / p.shape.k, at % p.shape.k), .magnitude = 0 }; + if (p.kind == .combine) { + const token = at / p.shape.n; + const col = at % p.shape.n; + var terms: [8]f64 = undefined; + var magnitude: f64 = 0; + var made: usize = 0; + for (0..8) |expert| for (0..8) |slot| if (p.ids[token * 8 + slot] == @as(i32, @intCast(expert))) { + const value = p.weights[token * 8 + slot] * @as(f64, c.fromBf16(p.x[(token * 8 + slot) * p.shape.n + col])); + terms[made] = value; + made += 1; + magnitude += @abs(value); + }; + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..made]) else blk: { + var total: f64 = 0; + for (terms[0..made]) |term| total += term; + break :blk total; + }; + return .{ .value = bf(sum), .magnitude = magnitude }; + } + const pair = at / p.shape.n; + const n = at % p.shape.n; + const token = pair / 2; + 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 (isDown(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 fn check(p: *Probe, gate: g.Gate) !?[]const u8 { + if (gate != .shapes) return null; + const bytes = try p.rig.outputBytes(); + const want = try p.a.alloc(f64, p.count()); + defer p.a.free(want); + const mag = try p.a.alloc(f64, p.count()); + defer p.a.free(mag); + try p.reference(want, mag); + for (want, 0..) |w, i| if (c.read(.bf16, bytes, i) != w) return "route-slot output differs from the ascending-expert reference"; + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [14]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + 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 seven shipped entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 experts ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig new file mode 100644 index 00000000000..e28ae1f9cd3 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -0,0 +1,83 @@ +//! Count-checked M3 source mutations: every shader 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_up, + nv_down_phi, + mx_gu_up, + mx_down_scale, + nv_decode_nibble, + mx_decode_scale, + combine_slot_order, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_up => "control: metal inkling2 experts tf_ink2_nvfp4_gu up row", + .nv_down_phi => "control: metal inkling2 experts tf_ink2_nvfp4_down phi", + .mx_gu_up => "control: metal inkling2 experts tf_ink2_mxfp8_gu up row", + .mx_down_scale => "control: metal inkling2 experts tf_ink2_mxfp8_down scale", + .nv_decode_nibble => "control: metal inkling2 experts tf_ink2_nvfp4_quantize nibble", + .mx_decode_scale => "control: metal inkling2 experts tf_ink2_mxfp8_quantize scale", + .combine_slot_order => "control: metal inkling2 experts tf_ink2_combine route-slot order", + }; + } + + 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_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, + .mx_gu_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, + .nv_down_phi => .{ .from = "const float phi = ink2_phi(amax, denominator, expert);", .to = "const float phi = precise::divide(2.0f * amax[expert], denominator[0]);" }, + .nv_decode_nibble => .{ .from = "W[row * (a.k / 2u) + col / 2u], col,", .to = "W[row * (a.k / 2u) + col / 2u], col + 1u," }, + .mx_down_scale => .{ .from = "S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k));", .to = "S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, a.k));" }, + .mx_decode_scale => .{ .from = "S[row * (a.k / 32u) + col / 32u]", .to = "S[row * (a.k / 32u) + col / 16u]" }, + .combine_slot_order => .{ + .from = "for (uint expert = 0; expert < a.experts; ++expert)\n for (uint slot = 0; slot < a.topk; ++slot)\n if (uint(ids[group * a.topk + slot]) == expert)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", + .to = "for (uint slot = 0; slot < a.topk; ++slot)\n sum += weights[group * a.topk + slot] * float(down[(group * a.topk + slot) * a.n + n]);", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts); + const change = m.edit(); + const expected: usize = switch (m) { + .nv_gu_up, .mx_gu_up, .nv_down_phi => 2, + else => 1, + }; + if (std.mem.count(u8, src.experts, change.from) != expected) return error.ControlEditCount; + // The same textual mutation serves both formats; a control compiles only its selected entry. + return std.mem.replaceOwned(u8, a, src.experts, change.from, change.to); +} + +test "every expert 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 experts ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts, plain); +} + +test "expert source exports all seven entries and has no activation quantizer" { + for ([_][]const u8{ "tf_ink2_nvfp4_gu", "tf_ink2_nvfp4_down", "tf_ink2_mxfp8_gu", "tf_ink2_mxfp8_down", "tf_ink2_nvfp4_quantize", "tf_ink2_mxfp8_quantize", "tf_ink2_combine" }) |name| + try std.testing.expect(std.mem.indexOf(u8, src.experts, name) != null); + try std.testing.expect(std.mem.indexOf(u8, src.experts, "never quantize an activation") != null); + try std.testing.expect(std.mem.indexOf(u8, src.experts, "e2m1(float") == null); +} diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig new file mode 100644 index 00000000000..496f4c69f98 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -0,0 +1,376 @@ +//! Inkling 2 Mini glue under FP64 references, guarded buffers and real Metal dispatch. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_glue_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.glue; +const p = host.plan; +const sources = @import("inkling2_metal"); + +fn depth(s: c.Shape) usize { + return s.k + 40; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn fromBf(v: u16) f32 { + return c.fromBf16(v); +} + +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [3]c.Shape = undefined, + f: [4][]f32 = @splat(&.{}), + ids: []u32 = &.{}, + route_ids: rig_.Ref = undefined, + refs: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + nonfinite: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.glue); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .pipes = try host.Pipelines.loadSource(device, text) }; + self.served = switch (kind) { + .embed_norm => .{ .{ .rows = 1, .n = p.hidden, .k = p.hidden }, .{ .rows = 5, .n = p.hidden, .k = p.hidden }, .{ .rows = 7, .n = p.hidden, .k = p.hidden } }, + .ar => .{ .{ .rows = 2, .n = p.hidden, .k = p.hidden }, .{ .rows = 4, .n = p.hidden, .k = p.hidden }, .{ .rows = 5, .n = p.hidden, .k = p.hidden } }, + .conv_static => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 1024, .k = 4 }, .{ .rows = 7, .n = p.hidden, .k = 4 } }, + .conv_dynamic => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 512, .k = 4 }, .{ .rows = 7, .n = 1024, .k = 4 } }, + .router => .{ .{ .rows = 1, .n = 8, .k = p.hidden }, .{ .rows = 5, .n = 8, .k = p.hidden }, .{ .rows = 7, .n = 8, .k = p.hidden } }, + .swiglu => .{ .{ .rows = 1, .n = p.intermediate, .k = 2 }, .{ .rows = 5, .n = p.intermediate, .k = 2 }, .{ .rows = 7, .n = p.intermediate, .k = 2 } }, + .logits => .{ .{ .rows = 1, .n = 128, .k = p.hidden }, .{ .rows = 5, .n = 256, .k = p.hidden }, .{ .rows = 7, .n = 128, .k = p.hidden } }, + .expert_pick => .{ .{ .rows = 1, .n = p.intermediate, .k = 8 }, .{ .rows = 5, .n = p.intermediate, .k = 8 }, .{ .rows = 7, .n = p.intermediate, .k = 8 } }, + .expert_combine => .{ .{ .rows = 1, .n = p.hidden, .k = 8 }, .{ .rows = 5, .n = p.hidden, .k = 8 }, .{ .rows = 7, .n = p.hidden, .k = 8 } }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + const vt_checked = g.hooks(Probe); + const vt_plain = blk: { + var vt = g.hooks(Probe); + vt.check = null; + break :blk vt; + }; + pub fn kernel(self: *Probe) g.Kernel { + const out: c.Elem = switch (self.kind) { + .ar, .router, .logits => .f32, + else => .bf16, + }; + return .{ + .ctx = self, + .vt = if (self.kind == .router) &vt_checked else &vt_plain, + .spec = .{ + .name = self.kind.label(), + .accum = .f32, + .depth = depth, + .ops = 96, + .mids = if (self.kind == .logits) 1 else 0, + .out = out, + .served = &self.served, + .nan = if (self.kind == .router) .{ .stated = "a NaN selected score makes the shared normalization and every selected weight NaN" } else .propagate, + // AR's integer stress terms are exact in FP32 and must discriminate FP16/BF16 by 100x. + .sums = if (self.kind == .ar) .{} else .{ .f16 = 0, .bf16 = 0, .why = "nonlinear norms, exponentials and BF16 endpoints have no uniform lower-precision separability factor" }, + }, + }; + } + pub fn count(self: *Probe) usize { + return if (self.kind == .ar) 2 * p.hidden else p.count(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const out = try self.arena.allocator().alloc(f32, n); + for (out) |*x| x.* = value(rng); + return out; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, x| b.* = c.toBf16(x); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!p.valid(self.kind, .{ .rows = shape.rows, .n = shape.n, .k = shape.k })) return false; + if (self.kind == .embed_norm and shape.n != p.hidden) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.nonfinite = fill == .nonfinite; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.rows; + const n = shape.n; + const nf = fill == .nonfinite; + self.f = @splat(&.{}); + switch (self.kind) { + .embed_norm => { + self.f[0] = try self.floats(64 * p.hidden, rng); + self.f[1] = try self.floats(p.hidden, rng); + self.ids = try self.arena.allocator().alloc(u32, r); + for (self.ids, 0..) |*id, i| id.* = @intCast(i % 64); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + self.refs[1] = try self.input(self.f[0], true); + self.refs[2] = try self.input(self.f[1], true); + }, + .ar => { + self.f[0] = try self.floats((r - 1) * p.hidden, rng); + self.f[1] = try self.floats(p.hidden, rng); + self.f[2] = try self.floats(2 * p.hidden, rng); + if (fill == .stress) { + // Each 2304-term square sum is exactly 9 * 2^24 in FP32 under every order. + for (0..r) |s| { + const values = if (s + 1 == r) self.f[1] else self.f[0][s * p.hidden ..][0..p.hidden]; + @memset(values, if (s % 2 == 0) 256 else -256); + } + // Normalized mirrored queries leave +/-8; partial sums stay exact integers in FP32. + for (0..2) |query_row| { + const row = self.f[2][query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (d < 8) 1 else 0; + row[d] = v; + row[p.hidden / 2 + d] = nudge - v; + } + } + } + if (nf) self.f[2][0] = std.math.inf(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], false); + self.refs[2] = try self.input(self.f[2], false); + }, + .conv_static => { + self.f[0] = try self.floats((r + 3) * n, rng); + self.f[1] = try self.floats(4 * n, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + }, + .conv_dynamic => { + self.f[0] = try self.floats((r + 3) * n, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(4 * n, rng); + self.f[3] = try self.floats(32 * p.hidden, rng); + if (nf) self.f[1][0] = std.math.nan(f32); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + }, + .router => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(p.expert_count * p.hidden, rng); + self.f[2] = try self.floats(p.expert_count, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + self.refs[2] = try self.input(self.f[2], false); + self.route_ids = try self.rig.scratch(r * 8 * 4); + }, + .swiglu => { + self.f[0] = try self.floats(r * n * 2, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + }, + .logits => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(n * p.hidden, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + }, + .expert_pick => { + self.f[0] = try self.floats(r * p.expert_count * n, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.ids = try self.arena.allocator().alloc(u32, r * 8); + for (self.ids, 0..) |*id, j| id.* = @intCast(j % 8 * 13 + j / 8); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + }, + .expert_combine => { + self.f[0] = try self.floats(r * 8 * n, rng); + self.f[1] = try self.floats(r * 8, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], false); + }, + } + // Every BF16 input and the FP64 oracle see exactly the same stored values. + for (self.f, 0..) |values, j| if (values.len > 0 and switch (self.kind) { + .ar => j == 0, + .router => j < 2, + .expert_combine => j == 0, + else => true, + }) round(values); + const bytes = self.count() * @as(usize, if (self.kind == .ar or self.kind == .router or self.kind == .logits) 4 else 2); + self.out = try self.rig.output(bytes); + return true; + } + fn at(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const pl = &self.pipes; + const R = self.refs; + const y = at(self.out); + const r: u32 = @intCast(self.shape.rows); + const n: u32 = @intCast(self.shape.n); + switch (self.kind) { + .embed_norm => host.embedNorm(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r), + .ar => host.ar(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r, 2), + .conv_static => host.convStatic(pl, e, at(R[0]), at(R[1]), y, r, n), + .conv_dynamic => host.convDynamic(pl, e, at(R[0]), at(R[1]), at(R[2]), at(R[3]), y, r, n), + .router => host.router(pl, e, at(R[0]), at(R[1]), at(R[2]), at(self.route_ids), y, r), + .swiglu => host.swiglu(pl, e, at(R[0]), y, r, n), + .logits => host.logits(pl, e, at(R[0]), at(R[1]), y, r, n), + .expert_pick => host.expertPick(pl, e, at(R[0]), at(R[1]), y, r, n), + .expert_combine => host.expertCombine(pl, e, at(R[0]), at(R[1]), y, r, n), + } + try self.rig.finish(pass); + } + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + const r = self.shape.rows; + const n = self.shape.n; + for (0..r) |row| switch (self.kind) { + .embed_norm => { + const x = self.f[0][self.ids[row] * p.hidden ..][0..p.hidden]; + for (0..p.hidden) |d| want[row * p.hidden + d] = p.embedValue(x, self.f[1], d); + }, + .ar => { + var qout: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidual(self.f[0], self.f[1], self.f[2], r, q, qout[q * p.hidden ..][0..p.hidden]); + @memcpy(want, &qout); + break; + }, + .conv_static => { + for (0..n) |d| want[row * n + d] = p.staticConv(self.f[0], self.f[1], n, row, d); + }, + .conv_dynamic => { + for (0..n) |d| want[row * n + d] = p.dynamicConv(self.f[0], self.f[1], self.f[2], self.f[3], n, row, d); + }, + .router => { + const route = p.route(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], self.f[2]); + @memcpy(want[row * 8 ..][0..8], &route.weights); + }, + .swiglu => { + for (0..n) |d| want[row * n + d] = p.swiglu(self.f[0][(row * n + d) * 2], self.f[0][(row * n + d) * 2 + 1]); + }, + .logits => { + for (0..n) |v| want[row * n + v] = p.logit(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], v); + }, + .expert_pick => { + for (0..8) |j| { + for (0..n) |d| want[(row * 8 + j) * n + d] = p.pick(self.f[0], self.ids, n, row, j, d); + } + }, + .expert_combine => { + for (0..n) |d| want[row * n + d] = p.combine(self.f[0][row * 8 * n ..], self.f[1][row * 8 ..][0..8], n, d); + }, + }; + for (mag, want) |*m, w| m.* = 10 * @abs(w) + 1e-5; + } + pub fn simulate(self: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + if (self.kind == .ar) { + const sim: p.ArSum = .{ + .accum = switch (acc) { + .none => .none, + .f32 => .f32, + .f16 => .f16, + .bf16 => .bf16, + }, + .order = switch (order) { + .sequential => .sequential, + .pairwise => .pairwise, + .strided => .strided, + }, + }; + for (0..2) |q| p.blockResidualIn(self.f[0], self.f[1], self.f[2], self.shape.rows, q, sim, out[q * p.hidden ..][0..p.hidden]); + return; + } + const mag = try self.a.alloc(f64, out.len); + defer self.a.free(mag); + return self.reference(out, mag); + } + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (self.kind != .router) return "numeric hooks must be used"; + const bytes = try self.rig.outputBytes(); + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + if (gate == .nonfinite) { + for (want, 0..) |w, i| if (std.math.isNan(c.read(.f32, bytes, i)) != std.math.isNan(w)) return "NaN normalization rule differs"; + return null; + } + const got_ids = std.mem.bytesAsSlice(u32, self.rig.bytes(self.route_ids, self.shape.rows * 8 * 4)); + for (0..self.shape.rows) |row| { + const route = p.route(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], self.f[2]); + for (0..8) |j| { + if (got_ids[row * 8 + j] != route.ids[j]) return "selected IDs differ"; + const got = c.read(.f32, bytes, row * 8 + j); + if (@abs(got - want[row * 8 + j]) > 1e-5 * @max(1, @abs(want[row * 8 + j]))) return "router weight differs"; + } + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.glue, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_glue_controls.zig b/zig/tests/contract/metal_inkling2_glue_controls.zig new file mode 100644 index 00000000000..aba23199f09 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue_controls.zig @@ -0,0 +1,65 @@ +//! One host-checkable source-planted arithmetic fault for every Inkling 2 Mini glue kernel. +const std = @import("std"); +const p = @import("inkling2_glue_plan"); + +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;" }, + .conv_static => .{ .from = "weight[c * 4 + tap]", .to = "weight[c * 4 + 3 - tap]" }, + .conv_dynamic => .{ .from = "static_w[lag * a.channels + c]", .to = "static_w[(3 - lag) * a.channels + c]" }, + .router => .{ .from = "scores[e] + bias[e] > scores[best] + bias[best]", .to = "scores[e] > scores[best]" }, + .swiglu => .{ .from = "ink_cap(u, 25.0f)", .to = "ink_cap(g, 25.0f)" }, + .logits => .{ .from = "ink_cap(float(bfloat(dot)), 30.0f)", .to = "ink_cap(dot, 30.0f)" }, + .expert_pick => .{ .from = "ids[r * 8 + j]", .to = "ids[r * 8 + 7 - j]" }, + .expert_combine => .{ .from = "acc += weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]);", .to = "acc -= weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]);" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .embed_norm => "control: metal inkling2 glue embed_norm tf_inkling2_embed_norm", + .ar => "control: metal inkling2 glue ar tf_inkling2_ar", + .conv_static => "control: metal inkling2 glue conv_static tf_inkling2_conv_static", + .conv_dynamic => "control: metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", + .router => "control: metal inkling2 glue router tf_inkling2_router", + .swiglu => "control: metal inkling2 glue swiglu tf_inkling2_swiglu", + .logits => "control: metal inkling2 glue logits tf_inkling2_logits", + .expert_pick => "control: metal inkling2 glue expert_pick tf_inkling2_expert_pick", + .expert_combine => "control: metal inkling2 glue expert_combine tf_inkling2_expert_combine", + }; +} + +test "every glue control applies once and changes only its arithmetic anchor" { + const production = @import("inkling2_metal").glue; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated glue control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").glue; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_loop.zig b/zig/tests/contract/metal_inkling2_loop.zig new file mode 100644 index 00000000000..f597983003e --- /dev/null +++ b/zig/tests/contract/metal_inkling2_loop.zig @@ -0,0 +1,327 @@ +//! Mini cross-pass messages and rank-64 gates under FP64 oracles and mutation controls. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_loop_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.loop; +const p = host.plan; +const sources = @import("inkling2_metal"); + +fn depth(s: c.Shape) usize { + return if (s.n == p.message_entries * p.hidden) 2 * s.k + 16 else 2 * p.hidden + s.k + 16; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [3]c.Shape = undefined, + f: [6][]f32 = @splat(&.{}), + refs: [6]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.loop); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ + .a = a, + .arena = .init(a), + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = kind, + .pipes = try host.Pipelines.loadSource(device, text), + }; + self.served = switch (kind) { + .messages => .{ + .{ .rows = 1, .n = p.message_entries * p.hidden, .k = p.hidden }, + .{ .rows = 5, .n = p.message_entries * p.hidden, .k = p.hidden }, + .{ .rows = 7, .n = p.message_entries * p.hidden, .k = p.hidden }, + }, + .gates => .{ + .{ .rows = 1, .n = p.hidden, .k = p.rank }, + .{ .rows = 5, .n = p.hidden, .k = p.rank }, + .{ .rows = 7, .n = p.hidden, .k = p.rank }, + }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + + const vt = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = &vt, .spec = .{ + .name = self.kind.label(), + .accum = .f32, + .depth = depth, + .ops = if (self.kind == .messages) 32 else 64, + .mids = if (self.kind == .gates) 2 else 0, + .out = .f32, + .served = &self.served, + .sums = .{}, + } }; + } + pub fn count(self: *Probe) usize { + return p.count(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = value(rng); + return values; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const call = p.Call{ .rows = shape.rows, .n = shape.n, .k = shape.k }; + if (!p.valid(self.kind, call)) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.rows; + switch (self.kind) { + .messages => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(2 * p.core_layers * p.hidden, rng); + self.f[3] = try self.floats(2 * p.core_layers * p.hidden, rng); + if (fill == .stress) { + // rho(+256) = +1 and rho(-256) = -1 in FP32: their square sum is 9 * 2^24. + @memset(self.f[0], 256); + @memset(self.f[1], -256); + // Mirrored integer queries leave 8, while every partial sum stays below 2^24. + for ([_][]f32{ self.f[2], self.f[3] }) |queries| for (0..2 * p.core_layers) |query_row| { + const row = queries[query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (d < 8) 1 else 0; + row[d] = v; + row[p.hidden / 2 + d] = nudge - v; + } + }; + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + round(self.f[0]); + round(self.f[1]); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + self.refs[2] = try self.input(self.f[2], false); + self.refs[3] = try self.input(self.f[3], false); + }, + .gates => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(p.rank * 2 * p.hidden, rng); + self.f[3] = try self.floats(p.hidden * p.rank, rng); + self.f[4] = try self.floats(p.hidden * p.rank, rng); + if (fill == .stress) { + @memset(self.f[0], 256); + @memset(self.f[1], -256); + // D sees [+1; -1]: mirrored integer rows leave zeta = 1, with exact FP32 partials. + for (0..p.rank) |rank| for (0..p.hidden) |d| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + self.f[2][rank * 2 * p.hidden + d] = w; + self.f[2][rank * 2 * p.hidden + p.hidden + d] = if (d == 0) w - 1 else w; + }; + // With zeta = 1, mirrored F/Gamma rows leave one, also exactly in every FP32 order. + for ([_][]f32{ self.f[3], self.f[4] }) |weights| for (0..p.hidden) |d| for (0..p.rank / 2) |rank| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + weights[d * p.rank + rank] = w; + weights[d * p.rank + rank + p.rank / 2] = if (rank == 0) 1 - w else -w; + }; + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + round(self.f[2]); + round(self.f[3]); + round(self.f[4]); + self.refs[0] = try self.input(self.f[0], false); + self.refs[1] = try self.input(self.f[1], false); + self.refs[2] = try self.input(self.f[2], true); + self.refs[3] = try self.input(self.f[3], true); + self.refs[4] = try self.input(self.f[4], true); + }, + } + self.out = try self.rig.output(self.count() * @sizeOf(f32)); + return true; + } + + fn at(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const rows: u32 = @intCast(self.shape.rows); + switch (self.kind) { + .messages => host.crossPassMessageAttention(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.out), rows), + .gates => host.gates(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), at(self.out), rows), + } + try self.rig.finish(pass); + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + switch (self.kind) { + .messages => for (0..self.shape.rows) |row| { + const b0 = self.f[0][row * p.hidden ..][0..p.hidden]; + const b1 = self.f[1][row * p.hidden ..][0..p.hidden]; + for (0..p.message_entries) |entry| { + const role: p.Role = @fromBackingInt(@intCast(entry % p.roles)); + const dst = want[(row * p.message_entries + entry) * p.hidden ..][0..p.hidden]; + p.message(b0, b1, self.f[2], self.f[3], entry / p.roles, role, dst); + } + }, + .gates => for (0..self.shape.rows) |row| { + const h = self.f[0][row * p.hidden ..][0..p.hidden]; + const m = self.f[1][row * p.hidden ..][0..p.hidden]; + p.gate(h, m, self.f[2], self.f[3], self.f[4], want[row * p.hidden ..][0..p.hidden]); + }, + } + for (mag, want) |*m, w| m.* = if (self.kind == .messages) + 10 * @abs(w) + 1e-3 + else + 32 * @abs(w) + 8; + } + fn simRms(x: []const f32, acc: c.Accum, order: g.Order, terms: []f64) f64 { + for (x, 0..) |v, d| terms[d] = @as(f64, v) * v; + const ss = contract.rows.sumIn(acc, order, terms[0..p.hidden]); + return 1 / @sqrt(ss / @as(f64, @floatFromInt(p.hidden)) + p.eps); + } + + fn simMessage(bank0: []const f32, bank1: []const f32, q_mlp: []const f32, kv: []const f32, layer: usize, role: p.Role, inverse: [2]f64, acc: c.Accum, order: g.Order, terms: []f64, out: []f64) void { + const queries = if (p.usesQueryMessageTensor(role)) q_mlp else kv; + const query = queries[p.queryRow(role, layer) * p.hidden ..][0..p.hidden]; + var logits: [2]f64 = undefined; + var peak = -std.math.inf(f64); + inline for (0..2) |s| { + const bank = if (s == 0) bank0 else bank1; + for (0..p.hidden) |d| terms[d] = @as(f64, query[d]) * (@as(f64, bank[d]) * inverse[s]); + logits[s] = contract.rows.sumIn(acc, order, terms[0..p.hidden]) * p.message_scale; + peak = @max(peak, logits[s]); + } + var weights: [2]f64 = undefined; + var den: f64 = 0; + for (0..2) |s| { + weights[s] = @exp(logits[s] - peak); + den += weights[s]; + } + for (0..p.hidden) |d| out[d] = weights[0] / den * (@as(f64, bank0[d]) * inverse[0]) + weights[1] / den * (@as(f64, bank1[d]) * inverse[1]); + } + + fn simGate(h: []const f32, m: []const f32, down: []const f32, forget: []const f32, gain: []const f32, inverse: [2]f64, acc: c.Accum, order: g.Order, terms: []f64, normalized: *[2 * p.hidden]f64, zeta: *[p.rank]f64, out: []f64) void { + for (0..p.hidden) |d| { + normalized[d] = p.roundBf16(@as(f64, h[d]) * inverse[0]); + normalized[p.hidden + d] = p.roundBf16(@as(f64, m[d]) * inverse[1]); + } + for (0..p.rank) |r| { + for (0..2 * p.hidden) |d| terms[d] = @as(f64, down[r * 2 * p.hidden + d]) * normalized[d]; + zeta[r] = p.roundBf16(contract.rows.sumIn(acc, order, terms)); + } + for (0..p.hidden) |d| { + for (0..p.rank) |r| terms[r] = @as(f64, forget[d * p.rank + r]) * zeta[r]; + const fdot = contract.rows.sumIn(acc, order, terms[0..p.rank]); + for (0..p.rank) |r| terms[r] = @as(f64, gain[d * p.rank + r]) * zeta[r]; + const gdot = contract.rows.sumIn(acc, order, terms[0..p.rank]); + out[d] = p.blend(std.math.tanh(fdot), std.math.tanh(gdot), h[d], m[d]); + } + } + + pub fn simulate(self: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + const terms = try self.a.alloc(f64, 2 * p.hidden); + defer self.a.free(terms); + switch (self.kind) { + .messages => for (0..self.shape.rows) |row| { + const banks = [2][]const f32{ + self.f[0][row * p.hidden ..][0..p.hidden], + self.f[1][row * p.hidden ..][0..p.hidden], + }; + var inverse: [2]f64 = undefined; + inline for (0..2) |s| inverse[s] = simRms(banks[s], acc, order, terms); + for (0..p.message_entries) |entry| { + const role: p.Role = @fromBackingInt(@intCast(entry % p.roles)); + const dst = out[(row * p.message_entries + entry) * p.hidden ..][0..p.hidden]; + simMessage(banks[0], banks[1], self.f[2], self.f[3], entry / p.roles, role, inverse, acc, order, terms, dst); + } + }, + .gates => { + var normalized: [2 * p.hidden]f64 = undefined; + var zeta: [p.rank]f64 = undefined; + for (0..self.shape.rows) |row| { + const h = self.f[0][row * p.hidden ..][0..p.hidden]; + const m = self.f[1][row * p.hidden ..][0..p.hidden]; + var inverse: [2]f64 = undefined; + inverse[0] = simRms(h, acc, order, terms); + inverse[1] = simRms(m, acc, order, terms); + simGate(h, m, self.f[2], self.f[3], self.f[4], inverse, acc, order, terms, &normalized, &zeta, out[row * p.hidden ..][0..p.hidden]); + } + }, + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.loop, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_loop_controls.zig b/zig/tests/contract/metal_inkling2_loop_controls.zig new file mode 100644 index 00000000000..5464bf58e5d --- /dev/null +++ b/zig/tests/contract/metal_inkling2_loop_controls.zig @@ -0,0 +1,53 @@ +//! One host-checkable arithmetic mutation for each Inkling 2 Mini loop kernel. +const std = @import("std"); +const p = @import("inkling2_loop_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + // Drops the required post-dot binary32(1/48) scale. + .messages => .{ .from = "weights[s] = dot * INKLING_LOOP_SCALE;", .to = "weights[s] = dot;" }, + // Drops the model-dtype rounding between D accumulation and F/Gamma. + .gates => .{ .from = "zeta[t] = float(bfloat(dot));", .to = "zeta[t] = dot;" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .messages => "control: metal inkling2 loop messages tf_inkling2_loop_messages", + .gates => "control: metal inkling2 loop gates tf_inkling2_loop_gates", + }; +} + +test "every loop control applies once and changes only its arithmetic anchor" { + const production = @import("inkling2_metal").loop; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated loop control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").loop; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig new file mode 100644 index 00000000000..57f7558ce6d --- /dev/null +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -0,0 +1,41 @@ +//! Inkling 2 Mini Metal suites and the lifetimes of their contract probes. +const std = @import("std"); +const mtl = @import("metal"); +const g = @import("contract").gates; + +pub const Suites = struct { + attention: @import("metal_inkling2_attention.zig").Suite, + glue: @import("metal_inkling2_glue.zig").Suite, + experts: @import("metal_inkling2_experts.zig").Suite, + loop: @import("metal_inkling2_loop.zig").Suite, + runtime: @import("metal_inkling2_runtime.zig").Suite, + dspark: @import("metal_inkling2_dspark.zig").Suite, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !Suites { + var s = Suites{ + .attention = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .glue = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .experts = .{ .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 }, + }; + errdefer s.deinit(); + try s.attention.collect(only); + try s.glue.collect(only); + try s.experts.collect(only); + try s.loop.collect(only); + try s.runtime.collect(only); + try s.dspark.collect(only); + return s; + } + + pub fn deinit(s: *Suites) void { + s.attention.deinit(); + s.glue.deinit(); + s.experts.deinit(); + s.loop.deinit(); + s.runtime.deinit(); + s.dspark.deinit(); + } +}; diff --git a/zig/tests/contract/metal_inkling2_runtime.zig b/zig/tests/contract/metal_inkling2_runtime.zig new file mode 100644 index 00000000000..5f0fc8ddefd --- /dev/null +++ b/zig/tests/contract/metal_inkling2_runtime.zig @@ -0,0 +1,290 @@ +//! Inkling 2 Mini runtime helpers under FP64 references, guarded buffers and exact ABI launches. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_runtime_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const p = @import("inkling2_runtime_plan"); +const sources = @import("inkling2_metal"); + +fn depth(_: c.Shape) usize { + return 1; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + served: [5]c.Shape = undefined, + f: [2][]f32 = @splat(&.{}), + refs: [2]rig_.Ref = undefined, + blocks: rig_.Ref = undefined, + blocks_before: []u16 = &.{}, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.runtime); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ + .a = a, + .arena = .init(a), + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = kind, + .pipe = undefined, + }; + errdefer self.arena.deinit(); + self.pipe = try rig_.pipeline(device, text, kind.symbol()); + self.served = switch (kind) { + .attention_partial => .{ + .{ .rows = 1, .n = p.hidden, .k = 0 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 3, .n = p.hidden, .k = 2 }, + .{ .rows = 2, .n = p.hidden, .k = 3 }, + .{ .rows = 7, .n = p.hidden, .k = 4 }, + }, + .copy_bf16, .copy_f32 => .{ + .{ .rows = 1, .n = p.hidden, .k = 1 }, + .{ .rows = 5, .n = 1024, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 1 }, + .{ .rows = 16, .n = 1024, .k = 1 }, + .{ .rows = 32, .n = p.hidden, .k = 1 }, + }, + .capture_tap => .{ + .{ .rows = 1, .n = p.hidden, .k = 0 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 2 }, + .{ .rows = 16, .n = p.hidden, .k = 3 }, + .{ .rows = 32, .n = p.hidden, .k = 3 }, + }, + else => .{ + .{ .rows = 1, .n = p.hidden, .k = 1 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 1 }, + .{ .rows = 16, .n = p.hidden, .k = 1 }, + .{ .rows = 32, .n = p.hidden, .k = 1 }, + }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.pipe.deinit(); + self.rig.deinit(); + self.arena.deinit(); + } + + const vt_plain = blk: { + var vt = g.hooks(Probe); + vt.check = null; + break :blk vt; + }; + const vt_checked = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = if (self.kind == .attention_partial) &vt_checked else &vt_plain, .spec = .{ + .name = self.kind.label(), + .accum = .none, + .depth = depth, + .ops = if (self.kind == .attention_partial or self.kind == .mlp_partial) 1 else 0, + .out = switch (self.kind) { + .copy_bf16, .mlp_partial, .capture_tap => .bf16, + .copy_f32, .widen, .attention_partial => .f32, + }, + .served = &self.served, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "pointwise moves and single additions have no reduction accumulator to discriminate" }, + } }; + } + pub fn count(self: *Probe) usize { + return p.outputCount(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = value(rng); + return values; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const call = p.Call{ .rows = shape.rows, .n = shape.n, .k = shape.k }; + if (!p.valid(self.kind, call)) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + self.blocks_before = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * shape.n; + self.f[0] = try self.floats(n, rng); + switch (self.kind) { + .copy_bf16, .widen, .capture_tap => round(self.f[0]), + .attention_partial => { + self.f[1] = try self.floats(n, rng); + round(self.f[0]); + round(self.f[1]); + const blocks = try self.arena.allocator().alloc(u16, shape.rows * p.block_slots * p.hidden); + for (blocks) |*b| b.* = c.toBf16(value(rng)); + self.blocks_before = blocks; + self.blocks = try self.rig.scratch(std.mem.sliceAsBytes(blocks).len); + @memcpy(self.rig.bytes(self.blocks, std.mem.sliceAsBytes(blocks).len), std.mem.sliceAsBytes(blocks)); + self.refs[1] = try self.input(self.f[1], true); + }, + .mlp_partial => { + self.f[1] = try self.floats(n, rng); + round(self.f[1]); + self.refs[1] = try self.input(self.f[1], true); + }, + .copy_f32 => {}, + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], self.kind == .copy_bf16 or self.kind == .widen or self.kind == .attention_partial or self.kind == .capture_tap); + const elem: c.Elem = switch (self.kind) { + .copy_bf16, .mlp_partial, .capture_tap => .bf16, + .copy_f32, .widen, .attention_partial => .f32, + }; + self.out = try self.rig.output(self.count() * c.size(elem)); + if (self.kind == .capture_tap) { + const untouched = std.mem.bytesAsSlice(u16, self.rig.bytes(self.out, self.count() * 2)); + @memset(untouched, c.toBf16(1)); + } + return true; + } + + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + e.setPipeline(self.pipe); + e.setBuffer(self.refs[0].buf, self.refs[0].off, 0); + switch (self.kind) { + .copy_bf16, .copy_f32, .widen, .capture_tap => { + e.setBuffer(self.out.buf, self.out.off, 1); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 2); + }, + .attention_partial => { + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.blocks.buf, self.blocks.off, 2); + e.setBuffer(self.out.buf, self.out.off, 3); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 4); + }, + .mlp_partial => { + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.out.buf, self.out.off, 2); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 3); + }, + } + e.dispatchThreads(mtl.Size.of(p.geometry(.{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }).count, 1, 1), mtl.Size.of(p.threads, 1, 1)); + try self.rig.finish(pass); + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + if (self.kind == .capture_tap) { + for (want, mag, 0..) |*w, *m, i| { + const row = i / (p.tap_channels * p.hidden); + const channel = (i / p.hidden) % p.tap_channels; + const x = self.f[0][row * p.hidden + i % p.hidden]; + w.* = if (channel == self.shape.k) x else 1; + m.* = @abs(@as(f64, x)); + } + return; + } + for (want, mag, 0..) |*w, *m, i| { + const x = self.f[0][i]; + const y = if (self.f[1].len == 0) 0 else self.f[1][i]; + w.* = switch (self.kind) { + .copy_bf16, .copy_f32, .widen, .capture_tap => x, + .attention_partial => p.attentionPartial(x, y, self.shape.k), + .mlp_partial => p.mlpPartial(x, y), + }; + m.* = @abs(@as(f64, x)) + @abs(@as(f64, y)); + } + } + + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (self.kind != .attention_partial or (gate != .shapes and gate != .nonfinite)) return "numeric hooks must be used"; + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + const bytes = try self.rig.outputBytes(); + var planted: usize = 0; + for (want, 0..) |w, i| { + const got = c.read(.f32, bytes, i); + if (c.classOf(got) != c.classOf(w)) return "partial's floating-point class differs"; + if (c.classOf(w) != .finite) planted += 1; + if (gate == .shapes and std.math.isFinite(w) and got != w) return "FP32 partial differs from the FP64 reference's explicit rounding"; + } + if (gate == .nonfinite and (planted == 0 or planted == want.len)) return "the planted NaN does not discriminate finite and non-finite partials"; + const block_bytes = self.rig.bytes(self.blocks, std.mem.sliceAsBytes(self.blocks_before).len); + const got_blocks = std.mem.bytesAsSlice(u16, block_bytes); + for (0..self.shape.rows) |row| for (0..p.block_slots) |slot| for (0..p.hidden) |d| { + const at = (row * p.block_slots + slot) * p.hidden + d; + const expected = if (self.shape.k != 0 and slot == self.shape.k - 1) + c.toBf16(self.f[0][row * p.hidden + d]) + else + self.blocks_before[at]; + if (got_blocks[at] != expected) return "completed-block row/slot layout differs"; + }; + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.runtime, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_runtime_controls.zig b/zig/tests/contract/metal_inkling2_runtime_controls.zig new file mode 100644 index 00000000000..09c1b4526a9 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_runtime_controls.zig @@ -0,0 +1,65 @@ +//! One host-checkable arithmetic or layout mutation for each Inkling 2 Mini runtime helper. +const std = @import("std"); +const p = @import("inkling2_runtime_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + .copy_bf16 => .{ + .from = "kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = x[i];", + .to = "kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = bfloat(0);", + }, + .copy_f32 => .{ + .from = "kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = x[i];", + .to = "kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = 0.0f;", + }, + .widen => .{ .from = "if (i < a.count) y[i] = float(x[i]);", .to = "if (i < a.count) y[i] = 2.0f * float(x[i]);" }, + .attention_partial => .{ .from = "blocks[row * 4 * 2304 + (a.boundary - 1) * 2304 + d] = p[i];", .to = "blocks[row * 2304 + (a.boundary - 1) * 2304 + d] = p[i];" }, + .mlp_partial => .{ .from = "p[i] = bfloat(t[i] + float(x[i]));", .to = "p[i] = bfloat(t[i] - float(x[i]));" }, + .capture_tap => .{ .from = "y[row * 4 * 2304 + a.boundary * 2304 + d] = x[i];", .to = "y[row * 4 * 2304 + ((a.boundary + 1) % 4) * 2304 + d] = x[i];" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .copy_bf16 => "control: metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", + .copy_f32 => "control: metal inkling2 runtime copy_f32 tf_ink2_copy_f32", + .widen => "control: metal inkling2 runtime widen tf_ink2_widen", + .attention_partial => "control: metal inkling2 runtime attention_partial tf_ink2_attention_partial", + .mlp_partial => "control: metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", + .capture_tap => "control: metal inkling2 runtime capture_tap tf_ink2_capture_tap", + }; +} + +test "every runtime control applies once and changes only its discriminating anchor" { + const production = @import("inkling2_metal").runtime; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated runtime control anchor is ambiguous and refuses to prove a fault" { + const production = @import("inkling2_metal").runtime; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 790b720bb0f..688db2625f8 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -34,7 +34,7 @@ fn boltSource(name: []const u8) ![]const u8 { } /// Each registration's function is its label's last word; the label's words say which source it compiles. -fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { +pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { return resolve(a, device, d, true); } @@ -209,6 +209,25 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const t = try @import("metal_flint.zig").limitsText(a, device, d.name); return .{ .decl = d, .function = fun, .here = t.here, .pre_m5 = t.pre_m5 }; } + if (std.mem.startsWith(u8, d.name, "metal inkling2 ")) { + if (!assemble) return undefined; + const body = if (std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) + @import("inkling2_metal").inkling2_dspark + else if (std.mem.startsWith(u8, d.name, "metal inkling2 runtime ")) + @import("inkling2_metal").runtime + 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 experts ")) + @import("inkling2_metal").experts + else if (std.mem.startsWith(u8, d.name, "metal inkling2 glue ")) + @import("inkling2_metal").glue + else if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) + @import("inkling2_metal").prompt_attention + else + @import("inkling2_metal").attention; + const pre_m5 = if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) @import("inkling2_metal").prompt_attention_pre_m5 else body; + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = pre_m5 }; + } if (std.mem.startsWith(u8, d.name, "lfm2 masked prompt ")) { if (!assemble) return undefined; const body = try tf.lfm2_moe.source.prompt(device, a, true); diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index eb44a76eab1..cf80f33dc37 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -359,6 +359,8 @@ pub fn main(init: std.process.Init) !u8 { var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; defer ling_mla_set.deinit(); try ling_mla_set.collect(&kernels, o.only); + var inkling2_suites = try @import("metal_inkling2_main.zig").Suites.create(a, device, queue, &kernels, o.only); + defer inkling2_suites.deinit(); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue; const p = try a.create(affine_k.Proj); diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index aedf4e04e08..7ef293a5dcf 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -15,6 +15,16 @@ test "Metal launch map: every registered launch and control has a resolver branc try std.testing.expectEqual(@as(usize, 0), missing); } +test "Metal launch map: every DSpark limit pipeline has a resolver branch" { + var count: usize = 0; + for (registry.all_metal) |d| { + if (!std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) continue; + try launches.requireMapped(d); + count += 1; + } + try std.testing.expectEqual(@as(usize, 11), count); +} + test "Metal launch map: unknown registrations stay errors on every chip" { try std.testing.expectError(error.UnknownLaunch, launches.requireMapped(.{ .name = "unregistered family missing_kernel", .threads = 32, .tg_memory = 0 })); } From bbcb8ee7788dcd1dbd1cdb3d8abc9cd71934a3ee Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:37:14 +0000 Subject: [PATCH 16/84] inkling2: serve Mini natively on Metal --- zig/build/inkling2_host.zig | 20 + zig/inkling2_native_compile.zig | 4 + zig/src/families/inkling2/metal/backend.zig | 446 ++++++++++++++++++ zig/src/families/inkling2/metal/dspark.zig | 270 +++++++++++ .../families/inkling2/metal/dspark_state.zig | 159 +++++++ .../inkling2/metal/dspark_weights.zig | 176 +++++++ zig/src/families/inkling2/metal/forward.zig | 346 ++++++++++++++ zig/src/families/inkling2/metal/host_test.zig | 16 + zig/src/families/inkling2/metal/model.zig | 294 ++++++++++++ .../families/inkling2/metal/runtime_test.zig | 176 +++++++ zig/src/families/inkling2/metal/snapshot.zig | 85 ++++ zig/src/families/inkling2/metal/state.zig | 369 +++++++++++++++ zig/src/inkling2_metal_host_test.zig | 6 + zig/src/inkling2_native.zig | 3 + zig/src/native/inkling2.zig | 212 +++++++++ zig/src/native/metal.zig | 6 +- zig/src/tensorfold.zig | 3 + .../contract/metal_inkling2_controls_host.zig | 10 + 18 files changed, 2598 insertions(+), 3 deletions(-) create mode 100644 zig/inkling2_native_compile.zig create mode 100644 zig/src/families/inkling2/metal/backend.zig create mode 100644 zig/src/families/inkling2/metal/dspark.zig create mode 100644 zig/src/families/inkling2/metal/dspark_state.zig create mode 100644 zig/src/families/inkling2/metal/dspark_weights.zig create mode 100644 zig/src/families/inkling2/metal/forward.zig create mode 100644 zig/src/families/inkling2/metal/host_test.zig create mode 100644 zig/src/families/inkling2/metal/model.zig create mode 100644 zig/src/families/inkling2/metal/runtime_test.zig create mode 100644 zig/src/families/inkling2/metal/snapshot.zig create mode 100644 zig/src/families/inkling2/metal/state.zig create mode 100644 zig/src/inkling2_metal_host_test.zig create mode 100644 zig/src/inkling2_native.zig create mode 100644 zig/src/native/inkling2.zig create mode 100644 zig/tests/contract/metal_inkling2_controls_host.zig diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 3212e0f94c6..03a0ae21548 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -12,6 +12,18 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin core.addImport("living", b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true })); m.addImport("core", core); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); + m.addImport("bf16_round", b.createModule(.{ .root_source_file = b.path(dir ++ "bf16_round.zig"), .target = target, .optimize = optimize })); + m.addImport("inkling2_metal", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize })); + m.addImport("metal", b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize })); + m.addImport("kernel_sources", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = target, .optimize = optimize })); + const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); + inkling2_metal_ref.addImport("metal", m.import_table.get("metal").?); + m.addImport("inkling2_metal_ref", inkling2_metal_ref); + m.addImport("inkling2_glue_plan", b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig"), .target = target, .optimize = optimize })); + m.addImport("inkling2_loop_plan", b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/loop_plan.zig"), .target = target, .optimize = optimize })); + const lanes = b.createModule(.{ .root_source_file = b.path(dir ++ "lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); + m.addImport("lanes", lanes); + m.addImport("engine_api", b.createModule(.{ .root_source_file = b.path(dir ++ "engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} })); return m; } @@ -19,4 +31,12 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/families/inkling2/host_test.zig") })); b.step("test-inkling2-host", "Inkling 2 family package: config, weight map, layer plan, chat template and tokenizer").dependOn(&run.step); test_step.dependOn(&run.step); + + const metal_run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/inkling2_metal_host_test.zig") })); + b.step("test-inkling2-metal-host", "Inkling 2 Mini Metal launch plans and arithmetic references").dependOn(&metal_run.step); + test_step.dependOn(&metal_run.step); + const native = b.addObject(.{ .name = "inkling2-native", .root_module = module(b, target, .Debug, "zig/inkling2_native_compile.zig") }); + _ = native.getEmittedBin(); + b.step("compile-inkling2-native-host", "Analyze the actual Inkling 2 Mini native opener without shaders or devices").dependOn(&native.step); + test_step.dependOn(&native.step); } diff --git a/zig/inkling2_native_compile.zig b/zig/inkling2_native_compile.zig new file mode 100644 index 00000000000..0d09fb133c1 --- /dev/null +++ b/zig/inkling2_native_compile.zig @@ -0,0 +1,4 @@ +//! Analyze the actual Inkling 2 Mini native opener without loading a device or checkpoint. +export fn compileInkling2Native() usize { + return @intFromPtr(&@import("src/inkling2_native.zig").open); +} diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig new file mode 100644 index 00000000000..8b7bc6e2c2c --- /dev/null +++ b/zig/src/families/inkling2/metal/backend.zig @@ -0,0 +1,446 @@ +//! Inkling 2 Mini behind the lane engine: independent visit state and exact copy-window rollback. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const fwd = @import("forward.zig"); +const Model = @import("model.zig").Model; +const snapshot = @import("snapshot.zig"); +const cfg = @import("../config.zig"); +const be = lanes.backend; + +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64 }; +const ring = 4096; + +/// The prompt cache gets the bytes left by live streams and never evicts the state being restored. +pub const Room = struct { ctx: *anyopaque, fit: *const fn (ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void }; + +/// Mini's DSpark ABI is fixed: four visit taps in checkpoint order. +pub fn validateTaps(c: *const cfg.Config, taps: []const u32) !void { + const mtp = c.mtp orelse return error.UnsupportedInkling2Taps; + const expected = [_]u32{ 5, 23, 41, 48 }; + if (mtp.taps_n != expected.len or !std.mem.eql(u32, mtp.taps[0..mtp.taps_n], &expected) or !std.mem.eql(u32, taps, &expected)) + return error.UnsupportedInkling2Taps; +} + +pub const Metal = struct { + gpa: std.mem.Allocator, + model: *Model, + options: Options, + scratch: st.Scratch, + prompt: st.Scratch, + caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, + held: u64 = 0, + room: ?Room = null, + tokens: []u32, + next: u64 = 0, + values: []f32, + prepared: bool = false, + sink: ?be.FeatureSink = null, + tap_gen: u64 = 0, + + pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { + const out = try gpa.create(Metal); + errdefer gpa.destroy(out); + var scratch = try st.Scratch.init(model.device, st.batch_rows); + errdefer scratch.deinit(); + var prompt = try st.Scratch.init(model.device, st.prompt_rows); + errdefer prompt.deinit(); + const tokens = try gpa.alloc(u32, ring); + errdefer gpa.free(tokens); + const values = try gpa.alloc(f32, model.config.text.unpadded_vocab); + out.* = .{ .gpa = gpa, .model = model, .options = options, .scratch = scratch, .prompt = prompt, .tokens = tokens, .values = values }; + return out; + } + + pub fn deinit(self: *Metal) void { + var it = self.caches.valueIterator(); + while (it.next()) |cache| { + cache.*.deinit(); + self.gpa.destroy(cache.*); + } + self.caches.deinit(self.gpa); + self.scratch.deinit(); + self.prompt.deinit(); + self.gpa.free(self.tokens); + self.gpa.free(self.values); + self.gpa.destroy(self); + } + + pub fn createCache(self: *Metal, capacity: usize) !*st.Cache { + const cache = try self.gpa.create(st.Cache); + errdefer self.gpa.destroy(cache); + cache.* = try st.Cache.init(self.model.device, capacity, &self.model.weight_plan); + return cache; + } + + pub fn facts(self: *const Metal) lanes.Model { + return .{ .exact_width = st.window_rows, .gpu_tokens = false, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true }; + } + + fn prepareFn(ptr: *anyopaque, taps: []const u32) !void { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (self.prepared) return; + const device = self.model.device; + const decode = self.scratch.taps orelse try device.buffer(st.captureBytes(st.batch_rows), mtl.ResourceOptions.shared); + errdefer if (self.scratch.taps == null) decode.deinit(); + const prompt = self.prompt.taps orelse try device.buffer(st.captureBytes(st.prompt_rows), mtl.ResourceOptions.shared); + errdefer if (self.prompt.taps == null) prompt.deinit(); + self.scratch.taps = decode; + self.prompt.taps = prompt; + self.prepared = true; + } + + fn featuresFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, start: u64, count: u32) !be.Features { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (!self.prepared) return error.UnpreparedInkling2Taps; + const tp = (try self.cacheOf(stream)).tap; + 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 }; + } + + fn prefillFeaturesFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) !void { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (!self.prepared) return error.UnpreparedInkling2Taps; + self.sink = sink; + defer self.sink = null; + return prefillFn(ptr, stream); + } + + fn nextTapGeneration(self: *Metal) u64 { + self.tap_gen +%= 1; + return self.tap_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 } }; + } + + fn cast(ptr: *anyopaque) *Metal { + return @ptrCast(@alignCast(ptr)); + } + + fn cacheOf(self: *Metal, stream: *lanes.Stream) !*st.Cache { + return self.caches.get(stream) orelse error.UnknownInklingStream; + } + + fn vocab(self: *const Metal) usize { + return self.model.config.text.unpadded_vocab; + } + + fn logits(self: *Metal, cache: *st.Cache) []const f32 { + return cache.logits.slice(f32, self.vocab()); + } + + fn draw(self: *Metal, l: []const f32, sampling: ?lanes.Sampling, position: u64, mask: []const u32) !u32 { + const t = sampled(sampling) orelse { + var best: ?usize = null; + for (l, 0..) |w, id| { + if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; + if (best == null or w > l[best.?]) best = id; + } + return @intCast(best orelse return error.InklingEmptyTokenMask); + }; + const values = if (mask.len == 0) l else blk: { + for (l, self.values, 0..) |w, *v, id| v.* = if (lanes.grammar.allows(mask, id)) w else -std.math.inf(f32); + break :blk self.values; + }; + return lanes.gpu_full.draw(self.gpa, values, t, @intCast(position), null); + } + + fn sampled(sampling: ?lanes.Sampling) ?lanes.Sampling { + const t = sampling orelse return null; + return if (t.temperature > 0) t else null; + } + + fn take(self: *Metal) u64 { + const h = self.next; + self.next += 1; + return h; + } + + fn put(self: *Metal, token: u32) u64 { + const h = self.take(); + self.tokens[h % ring] = token; + return h; + } + + fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream) !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; + const capture = self.prepared and stream != null; + if (capture) _ = self.nextTapGeneration(); + const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = taps }); + 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)); + } + } + + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + 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; + if (stream.images.len > 0) return error.InklingHasNoImageTower; + const need = st.cacheBytes(ids.len + stream.max_new); + 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(ids.len + stream.max_new); + 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 snapshot.Snap = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) { + if (snapshot.restore(cache, self.model.queue, snap)) stream.cached = @intCast(snap.at) else |_| stream.reuse_failed = true; + } else stream.reuse_failed = true; + } + try self.feed(cache, ids[cache.len..], stream); + } + + pub fn warm(self: *Metal) !void { + var cache = try st.Cache.init(self.model.device, st.prompt_rows + st.window_rows, &self.model.weight_plan); + defer cache.deinit(); + var ids: [st.prompt_rows]u32 = undefined; + for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000); + try self.feed(&cache, &ids, null); + try fwd.run(self.model, &self.scratch, &cache, ids[0..st.window_rows], .{ .all = true }); + } + + fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64) !u64 { + return cast(ptr).firstSlot(stream, position, &.{}); + } + + fn firstMaskedFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 { + return cast(ptr).firstSlot(stream, position, mask); + } + + fn firstSlot(self: *Metal, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 { + const cache = try self.cacheOf(stream); + if (position != cache.len or cache.pending != null) return error.InvalidInklingPosition; + return self.put(try self.draw(self.logits(cache), stream.sampling, position, mask)); + } + + fn queueFn(ptr: *anyopaque, stream: *lanes.Stream, what: be.Feed, position: u64) !u64 { + const self = cast(ptr); + const cache = try self.cacheOf(stream); + if (position != cache.len + 1 or cache.pending != null) return error.InvalidInklingPosition; + const token = switch (what) { + .handle => |h| try self.read(h), + .value => |v| v, + }; + if (token >= self.vocab()) return error.InvalidInklingToken; + const generation = if (self.prepared) self.nextTapGeneration() else 0; + const taps: ?st.Ref = if (self.prepared) .{ .buf = self.scratch.taps.? } else null; + try fwd.run(self.model, &self.scratch, cache, &.{token}, .{ .taps = taps }); + if (self.prepared) cache.tap = .{ .buf = self.scratch.taps, .start = @intCast(cache.len), .rows = 1, .gen = generation }; + cache.len += 1; + return self.put(try self.draw(self.logits(cache), stream.sampling, position, &.{})); + } + + fn read(self: *Metal, handle: u64) !u32 { + if (handle >= self.next) return error.InvalidInklingTokenHandle; + const token = self.tokens[handle % ring]; + if (token >= self.vocab()) return error.InvalidInklingToken; + return token; + } + + fn readFn(ptr: *anyopaque, handle: u64) !u32 { + return cast(ptr).read(handle); + } + + fn firstRowFn(ptr: *anyopaque, stream: *lanes.Stream) !lanes.LogprobRow { + const self = cast(ptr); + const l = self.logits(try self.cacheOf(stream)); + return firstLogprobRow(l, self.tokens, self.next, stream.logprobs orelse 0); + } + + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const self = cast(ptr); + const words = (self.vocab() + 31) / 32; + if (windows.len != out.len or windows.len > st.batch_rows) return error.InvalidInklingWindows; + var segments: [st.batch_rows]fwd.Segment = undefined; + var ids: [st.batch_rows]u32 = undefined; + var total: usize = 0; + var begun: usize = 0; + errdefer for (segments[0..begun]) |seg| seg.cache.rollback(self.model.queue) catch {}; + for (windows, out, 0..) |w, o, i| { + const rows = w.rows(); + if (rows == 0 or rows > st.window_rows or total + rows > st.batch_rows or w.parents != null or w.held != 0 or o.sampled.len != rows or o.drafts.len != rows - 1 or w.positions.len != rows) return error.UnsupportedInklingWindow; + const cache = try self.cacheOf(w.stream); + if (cache.pending != null) return error.InklingWindowAlreadyOpen; + for (w.positions, 0..) |p, r| if (p != cache.len + r + 1) return error.InvalidInklingPosition; + segments[i] = .{ .cache = cache, .rows = rows }; + ids[total] = w.pending; + @memcpy(ids[total + 1 ..][0..w.tokens.len], w.tokens); + total += rows; + } + for (segments[0..windows.len]) |seg| { + try seg.cache.begin(self.model.queue, seg.rows); + begun += 1; + } + const generation = if (self.prepared) self.nextTapGeneration() else 0; + const taps: ?st.Ref = if (self.prepared) .{ .buf = self.scratch.taps.? } else null; + try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true, .taps = taps }); + const all = self.scratch.logits_all.slice(f32, total * self.vocab()); + var base: usize = 0; + for (windows, out, segments[0..windows.len]) |w, o, seg| { + if (self.prepared) seg.cache.tap = .{ .buf = self.scratch.taps, .off = base * st.feature_row_bytes, .start = @intCast(seg.cache.len), .rows = seg.rows, .gen = generation }; + @memcpy(o.drafts, w.tokens); + for (0..seg.rows) |r| { + const l = all[(base + r) * self.vocab() ..][0..self.vocab()]; + const mask = if (w.masks.len >= (r + 1) * words) w.masks[r * words ..][0..words] else &.{}; + o.sampled[r] = try self.draw(l, w.stream.sampling, w.positions[r], mask); + if (o.rows.len == seg.rows) o.rows[r] = logprobRow(l, o.sampled[r], w.stream.logprobs orelse 0); + } + @memcpy(seg.cache.logits.slice(f32, self.vocab()), all[(base + seg.rows - 1) * self.vocab() ..][0..self.vocab()]); + base += seg.rows; + } + } + + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const self = cast(ptr); + if (windows.len != paths.len) return error.InvalidInklingWindows; + for (windows, paths) |w, path| { + const cache = try self.cacheOf(w.stream); + for (path, 0..) |r, i| if (r != i) return error.UnsupportedInklingTree; + if (path.len == 0 or path.len > w.rows() or cache.pending == null or cache.pending.? != w.rows()) return error.UnsupportedInklingWindow; + try cache.commit(self.model.queue, path.len); + } + } + + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) !void { + _ = ptr; + for (requests) |r| if (r.depth != 0 or r.lanes != null or r.plan != null) return error.InklingHasNoDraftHead; + } + + fn heldFn(_: *anyopaque, _: *lanes.Stream, out: []u32) !void { + if (out.len > 0) return error.InklingDraftsNotHeld; + } + + fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { + const self = cast(ptr); + if (self.caches.fetchRemove(stream)) |entry| { + const cache = entry.value; + if (cache.pending != null) cache.rollback(self.model.queue) catch |err| std.log.err("inkling2_loop rollback at release: {s}", .{@errorName(err)}); + self.held -= st.cacheBytes(cache.capacity); + cache.deinit(); + self.gpa.destroy(cache); + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, null, &.{}); + } + } + + pub fn snapBytes(ptr: *anyopaque, at: u32) u64 { + _ = ptr; + return snapshot.bytes(at); + } + + pub fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const self = cast(ptr); + const cache = try self.cacheOf(@ptrCast(@alignCast(owner orelse return error.NoStream))); + if (cache.len != at or cache.pending != null) return error.SnapshotOutOfStep; + const snap = try self.gpa.create(snapshot.Snap); + errdefer self.gpa.destroy(snap); + snap.* = try snapshot.save(self.model.device, self.model.queue, cache); + return snap; + } + + pub fn snapRestore(_: *anyopaque, _: ?*anyopaque, _: *anyopaque) anyerror!void { + return error.BackendRestores; + } + + pub fn snapDrop(ptr: *anyopaque, saved: *anyopaque) void { + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + snap.free(); + cast(ptr).gpa.destroy(snap); + } +}; + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +fn firstLogprobRow(l: []const f32, tokens: []const u32, next: usize, count: u8) lanes.LogprobRow { + std.debug.assert(tokens.len == ring and next > 0); + return logprobRow(l, tokens[(next - 1) % ring], count); +} + +fn logprobRow(l: []const f32, pick: u32, count: u8) lanes.LogprobRow { + const top = lanes.logprob.max_top; + var most: f64 = -std.math.inf(f64); + for (l) |w| most = @max(most, w); + var sum: f64 = 0; + for (l) |w| sum += @exp(@as(f64, w) - most); + const lse: f32 = @floatCast(most + @log(sum)); + var r: lanes.LogprobRow = .{ .token = pick, .logprob = l[pick] - lse, .count = 0 }; + var filled: usize = 0; + for (l, 0..) |w, id| { + if (filled == top and w <= r.logprobs[top - 1] + lse) continue; + var at = @min(filled, top - 1); + while (at > 0 and w > r.logprobs[at - 1] + lse) : (at -= 1) { + r.ids[at] = r.ids[at - 1]; + r.logprobs[at] = r.logprobs[at - 1]; + } + r.ids[at] = @intCast(id); + r.logprobs[at] = w - lse; + filled = @min(filled + 1, top); + } + r.count = @min(count, top); + return r; +} + +test "sampled first-token logprob uses the last written handle, not argmax" { + const logits = [_]f32{ 0, -1, -2, -3 }; + var tokens: [ring]u32 = @splat(0); + tokens[2] = 3; + const row = firstLogprobRow(&logits, &tokens, 3, 0); + try std.testing.expectEqual(@as(u32, 3), row.token); + try std.testing.expect(std.math.isFinite(row.logprob)); + const lse = @log(@as(f64, 1) + @exp(-@as(f64, 1)) + @exp(-@as(f64, 2)) + @exp(-@as(f64, 3))); + try std.testing.expectApproxEqAbs(@as(f32, -3) - @as(f32, @floatCast(lse)), row.logprob, 1e-6); +} diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig new file mode 100644 index 00000000000..cb13f807e10 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -0,0 +1,270 @@ +//! Inkling 2 Mini DSpark: committed target features, three-layer proposal blocks, folded Markov logits. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const gpu_rule = lanes.gpu_rule; +const ck = @import("../../../core/checkpoint_metal.zig"); +const Model = @import("model.zig").Model; +const fwd = @import("forward.zig"); +const glue = @import("glue.zig"); +const k = @import("dspark_kernels.zig"); +const weight_loader = @import("dspark_weights.zig"); +const state = @import("dspark_state.zig"); + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const Ref = k.Ref; +const tap_list = [_]u32{ 5, 23, 41, 48 }; + +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn failed(cb: mtl.CommandBuffer, what: []const u8) !void { + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop DSpark {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +pub const Drafter = struct { + gpa: std.mem.Allocator, + target: *const Model, + weights: weight_loader.Loaded, + pipelines: k.Pipelines, + scratch: state.Scratch, + scores: ?mtl.Buffer = null, + capacity: usize = 1, + contexts: std.AutoHashMapUnmanaged(*Stream, state.Lane) = .empty, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, target: *const Model, drafter_dir: []const u8) !*Drafter { + _ = io; // Native factory convention; Checkpoint.addFile uses platform file calls. + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const d = try gpa.create(Drafter); + errdefer gpa.destroy(d); + d.* = .{ + .gpa = gpa, + .target = target, + .weights = weight_loader.load(gpa, target, drafter_dir) catch |err| return err, + .pipelines = undefined, + .scratch = undefined, + }; + errdefer d.weights.deinit(); + d.pipelines = try k.Pipelines.load(device); + errdefer d.pipelines.deinit(); + d.scratch = try state.Scratch.init(device); + errdefer d.scratch.deinit(); + return d; + } + + pub fn deinit(d: *Drafter) void { + var it = d.contexts.valueIterator(); + while (it.next()) |lane| lane.deinit(); + d.contexts.deinit(d.gpa); + if (d.scores) |scores| scores.deinit(); + d.scratch.deinit(); + d.pipelines.deinit(); + d.weights.deinit(); + d.gpa.destroy(d); + } + + pub fn fixedBytes(d: *const Drafter) u64 { + return d.weights.fixedBytes() + state.scratchBytes(); + } + + pub fn scoreBytes(capacity: usize) u64 { + return state.scoreBytes(capacity); + } + + pub fn streamBytes(capacity: usize) u64 { + return state.laneBytes(capacity); + } + + /// The selected target window fixes every new lane's global ring and the shared attention score allocation. + pub fn setContext(d: *Drafter, window: u32) !void { + const capacity: usize = @intCast(window); + if (capacity == 0 or capacity > 1048576) return error.DSparkLaneGeometry; + if (d.contexts.count() != 0) return error.DSparkContextActive; + const scores = try d.target.device.buffer(@intCast(state.scoreBytes(capacity)), mtl.ResourceOptions.private); + if (d.scores) |old| old.deinit(); + d.scores = scores; + d.capacity = capacity; + } + + pub fn drafter(d: *Drafter) dr.Drafter { + return .{ .ptr = d, .vtable = &.{ .taps = tapsFn, .facts = factsFn, .open = openFn, .absorb = absorbFn, .hold = holdFn, .held = heldFn, .release = releaseFn } }; + } + + fn cast(ptr: *anyopaque) *Drafter { + return @ptrCast(@alignCast(ptr)); + } + + fn tapsFn(_: *anyopaque) []const u32 { + return &tap_list; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + const d = cast(ptr); + return .{ .depth = 7, .step_ms = 0, .plain_guard = true, .stream_bytes = @intCast(state.laneBytes(d.capacity)) }; + } + + fn openFn(ptr: *anyopaque, stream: *Stream) anyerror!void { + const d = cast(ptr); + if (d.contexts.contains(stream)) return error.DraftStreamOpen; + const lane = try state.Lane.init(d.target.device, d.capacity); + errdefer { + var owned = lane; + owned.deinit(); + } + try d.contexts.put(d.gpa, stream, lane); + } + + fn releaseFn(ptr: *anyopaque, stream: *Stream) void { + const d = cast(ptr); + if (d.contexts.fetchRemove(stream)) |entry| { + var lane = entry.value; + lane.deinit(); + } + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, out: []const []u32) anyerror!void { + const d = cast(ptr); + for (streams, out) |stream, tokens| { + const lane = d.contexts.getPtr(stream) orelse return error.DraftStreamUnknown; + if (tokens.len > lane.held_len) return error.DraftHeldFewer; + @memcpy(tokens, lane.held[0..tokens.len]); + } + } + + fn absorbRows(d: *Drafter, e: mtl.ComputeEncoder, lane: *const state.Lane, taps: Ref, start: u64, rows: usize) void { + const n: u32 = @intCast(rows); + k.fuseTaps(&d.pipelines, e, taps, r(d.weights.weights.fuse), at(d.weights.dflare, 0), at(d.scratch.fused, 0), at(lane.newest, 0), n); + for (d.weights.weights.layers, 0..) |layer, i| { + const c = at(d.scratch.fused, i * rows * state.hidden * 2); + fwd.dense(d.target, e, layer.k_ctx, c, at(d.scratch.ck, 0), rows); + fwd.dense(d.target, e, layer.v_ctx, c, at(d.scratch.cv, 0), rows); + k.commitContext(&d.pipelines, e, at(d.scratch.ck, 0), at(d.scratch.cv, 0), r(layer.k_norm_ctx), at(lane.k[i], 0), at(lane.v[i], 0), @intCast(start), n, @intCast(lane.rings[i])); + } + } + + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const d = cast(ptr); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + if (items.len == 0) return; + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + const row_bytes = 4 * state.hidden * 2; + for (items) |item| { + const lane = d.contexts.getPtr(item.stream) orelse return error.DraftStreamUnknown; + const features = item.features; + if (features.space != .device or features.dtype != .bf16 or features.row_bytes != row_bytes) return error.DraftFeaturesUnsupported; + if (item.rows != null) return error.TreesNotBuilt; + if (features.rows == 0 or features.rows > 1048576) return error.DraftFeaturesUnsupported; + if (item.start < lane.end) return error.DraftContextGap; + if (item.start > lane.end) lane.from = item.start; + const end = item.start + features.rows; + if (end > 1048576) return error.DraftContextGap; + const source = mtl.Buffer{ .id = @ptrFromInt(features.buffer) }; + var position = item.start; + while (position < end) { + const rows: usize = @intCast(@min(state.absorb_rows, end - position)); + const offset = features.offset + @as(usize, @intCast(position - item.start)) * row_bytes; + d.absorbRows(e, lane, at(source, offset), position, rows); + position += rows; + } + lane.end = end; + lane.held_len = 0; + } + e.end(); + cb.commit(); + try failed(cb, "absorb"); + } + + fn encodeBlock(d: *Drafter, e: mtl.ComputeEncoder, lane: *const state.Lane, pending: u32, anchor: u64) void { + const s = &d.scratch; + s.ids.slice(u32, 1)[0] = pending; + glue.embedNorm(&d.target.glue, e, at(s.ids, 0), r(d.target.weights.embed), r(d.target.weights.embed_norm), at(s.x, 0), 1); + k.initializeRows(&d.pipelines, e, at(s.x, 0), r(d.weights.weights.mask), at(s.x, 0)); + k.residualNorm(&d.pipelines, e, at(s.x, 0), at(s.resid, 0), r(d.weights.weights.layers[0].input_norm), at(s.resid, 0), at(s.x, 0), 8, true); + for (d.weights.weights.layers, 0..) |layer, i| { + fwd.dense(d.target, e, layer.q, at(s.x, 0), at(s.q_raw, 0), 8); + fwd.dense(d.target, e, layer.k, at(s.x, 0), at(s.k_raw, 0), 8); + fwd.dense(d.target, e, layer.v, at(s.x, 0), at(s.v_raw, 0), 8); + k.blockQkv(&d.pipelines, e, at(s.q_raw, 0), at(s.k_raw, 0), at(s.v_raw, 0), r(layer.q_norm), r(layer.k_norm), at(s.q, 0), at(s.kb, 0), at(s.vb, 0), @intCast(anchor)); + k.attend(&d.pipelines, e, at(s.q, 0), at(s.kb, 0), at(s.vb, 0), at(lane.k[i], 0), at(lane.v[i], 0), at(d.scores.?, 0), at(s.attn, 0), @intCast(lane.end), @intCast(lane.rings[i]), i != 1, @intCast(lane.from)); + fwd.dense(d.target, e, layer.o, at(s.attn, 0), at(s.y, 0), 8); + k.residualNorm(&d.pipelines, e, at(s.y, 0), at(s.resid, 0), r(layer.post_norm), at(s.next_resid, 0), at(s.x, 0), 8, false); + fwd.dense(d.target, e, layer.gate, at(s.x, 0), at(s.gate, 0), 8); + fwd.dense(d.target, e, layer.up, at(s.x, 0), at(s.up, 0), 8); + k.swiglu(&d.pipelines, e, at(s.gate, 0), at(s.up, 0), at(s.act, 0), 8 * state.intermediate); + fwd.dense(d.target, e, layer.down, at(s.act, 0), at(s.y, 0), 8); + const next_norm = if (i + 1 < d.weights.weights.layers.len) d.weights.weights.layers[i + 1].input_norm else d.weights.weights.norm; + k.residualNorm(&d.pipelines, e, at(s.y, 0), at(s.next_resid, 0), r(next_norm), at(s.resid, 0), at(s.x, 0), 8, false); + } + k.base(&d.pipelines, e, r(d.target.weights.unembed), at(s.x, state.hidden * 2), at(s.base, 0), 7, state.vocabulary); + k.kappa(&d.pipelines, e, at(s.x, state.hidden * 2), at(lane.newest, 0), r(d.weights.weights.rnn), r(d.weights.weights.rnn_bias), at(s.kappa, 0), 7); + } + + fn recurrent(d: *Drafter, e: mtl.ComputeEncoder, step: usize, previous: u32, second_bank: bool) void { + const s = &d.scratch; + const current = if (second_bank) s.next_state else s.state; + const next = if (second_bank) s.state else s.next_state; + k.recurrentStep(&d.pipelines, e, at(current, 0), at(s.kappa, step * 3 * state.rank * 4), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(s.z, 0), at(next, 0), at(s.lambda, 0), previous); + k.finalLogits(&d.pipelines, e, at(s.base, step * state.vocabulary * 2), at(d.weights.phi, 0), at(d.weights.beta, 0), at(s.lambda, 0), at(s.logits, 0)); + } + + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const d = cast(ptr); + for (items) |item| { + const lane = d.contexts.getPtr(item.stream) orelse return error.DraftStreamUnknown; + if (item.depth == 0 or item.position == 0) return error.DraftDepth; + const anchor = item.position - 1; + if (lane.end != anchor) return error.DraftContextGap; + const depth: usize = @min(item.depth, 7); + @memset(d.scratch.state.slice(u16, state.rank), 0); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeBlock(e, lane, item.pending, anchor); + d.recurrent(e, 0, item.pending, false); + e.end(); + cb.commit(); + try failed(cb, "block"); + const values = try d.gpa.alloc(f32, state.vocabulary); + defer d.gpa.free(values); + var previous = item.pending; + var second_bank = false; + for (0..depth) |step| { + if (step != 0) { + second_bank = !second_bank; + const next_cb = d.target.queue.commandBuffer(); + const next_e = next_cb.compute(.serial); + d.recurrent(next_e, step, previous, second_bank); + next_e.end(); + next_cb.commit(); + try failed(next_cb, "recurrent step"); + } + const raw = d.scratch.logits.slice(u16, state.vocabulary); + for (raw, values) |bits, *value| value.* = @bitCast(@as(u32, bits) << 16); + const base_position = std.math.cast(u32, item.position) orelse return error.DraftDepth; + const position = std.math.add(u32, base_position, @intCast(step)) catch return error.DraftDepth; + previous = try gpu_rule.sample(d.gpa, values, item.sampling, position, null); + if (previous >= state.vocabulary) return error.DraftNonfinite; + lane.held[step] = previous; + } + lane.held_len = @intCast(depth); + } + } +}; + +test "Mini taps and block depth match checkpoint section eight" { + try std.testing.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, &tap_list); + try std.testing.expectEqual(@as(u32, 48), tap_list[3]); + try std.testing.expectEqual(@as(u64, 768 * 1032), Drafter.scoreBytes(1024)); +} diff --git a/zig/src/families/inkling2/metal/dspark_state.zig b/zig/src/families/inkling2/metal/dspark_state.zig new file mode 100644 index 00000000000..eb20bd1cd6d --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_state.zig @@ -0,0 +1,159 @@ +//! Fixed eight-row DSpark scratch and committed-only per-stream context rings. +const std = @import("std"); +const mtl = @import("metal"); + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const intermediate = 9216; +pub const rank = 256; +pub const vocabulary = 200058; +pub const block = 8; +pub const absorb_rows = 64; +pub const local_ring = std.mem.alignForward(usize, 1024 + block, 128); + +const fields = [_][]const u8{ + "ids", "resid", "next_resid", "x", "y", "q_raw", "k_raw", "v_raw", "q", "kb", "vb", "attn", + "gate", "up", "act", "base", "fused", "ck", "cv", "kappa", "state", "next_state", "z", "lambda", + "logits", +}; + +fn sizes() [fields.len]usize { + const r = block; + const a = absorb_rows; + const b = 2; + return .{ + r * 4, r * hidden * b, r * hidden * b, r * hidden * b, r * hidden * b, + r * query * b, r * kv * b, r * kv * b, r * query * b, r * kv * b, + r * kv * b, r * query * b, r * intermediate * b, r * intermediate * b, r * intermediate * b, + (r - 1) * 201024 * b, 4 * a * hidden * b, a * kv * b, a * kv * b, (r - 1) * 3 * rank * 4, + rank * b, rank * b, rank * b, rank * b, vocabulary * b, + }; +} + +pub fn scratchBytes() usize { + var bytes: usize = 0; + for (sizes()) |n| bytes += n; + return bytes; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + resid: mtl.Buffer, + next_resid: mtl.Buffer, + x: mtl.Buffer, + y: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + q: mtl.Buffer, + kb: mtl.Buffer, + vb: mtl.Buffer, + attn: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + act: mtl.Buffer, + base: mtl.Buffer, + fused: mtl.Buffer, + ck: mtl.Buffer, + cv: mtl.Buffer, + kappa: mtl.Buffer, + state: mtl.Buffer, + next_state: mtl.Buffer, + z: mtl.Buffer, + lambda: mtl.Buffer, + logits: mtl.Buffer, + + pub fn init(device: mtl.Device) !Scratch { + @setEvalBranchQuota(10_000); + const ns = sizes(); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| @field(s, f).deinit(); + s.* = undefined; + } +}; +pub fn globalRing(capacity: usize) usize { + return std.mem.alignForward(usize, capacity, 128); +} + +pub fn scoreBytes(capacity: usize) u64 { + return @as(u64, 8 * 24 * 4) * (capacity + block); +} + +/// Two sliding layers hold two fixed K/V rings; layer 1 holds two global K/V rings. +pub fn laneFixedBytes() u64 { + return 2 * 2 * local_ring * kv * 2 + hidden * 2; +} + +pub fn laneTokenBytes() u64 { + return 2 * kv * 2; +} + +pub fn laneBytes(capacity: usize) u64 { + return laneFixedBytes() + globalRing(capacity) * laneTokenBytes(); +} + +pub const Lane = struct { + k: [3]mtl.Buffer, + v: [3]mtl.Buffer, + rings: [3]usize, + newest: mtl.Buffer, + from: u64 = 0, + end: u64 = 0, + held: [7]u32 = @splat(0), + held_len: u32 = 0, + + pub fn init(device: mtl.Device, capacity: usize) !Lane { + if (capacity == 0 or capacity > 1048576) return error.DSparkLaneGeometry; + var l: Lane = .{ .k = undefined, .v = undefined, .rings = .{ local_ring, globalRing(capacity), local_ring }, .newest = undefined }; + var made: usize = 0; + errdefer { + for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + } + for (l.rings, 0..) |ring, i| { + const bytes = ring * kv * 2; + l.k[i] = try device.buffer(bytes, mtl.ResourceOptions.private); + l.v[i] = device.buffer(bytes, mtl.ResourceOptions.private) catch |err| { + l.k[i].deinit(); + return err; + }; + made += 1; + } + l.newest = try device.buffer(hidden * 2, mtl.ResourceOptions.private); + return l; + } + + pub fn deinit(l: *Lane) void { + l.newest.deinit(); + for (0..3) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + l.* = undefined; + } +}; + +comptime { + if (local_ring != 1152 or laneTokenBytes() != 4096) @compileError("DSpark ring geometry drift"); +} + +test "DSpark stream accounting includes sliding, global and shared attention scratch" { + try std.testing.expectEqual(@as(u64, 9_437_184 + 4608), laneFixedBytes()); + try std.testing.expectEqual(laneFixedBytes() + 128 * 4096, laneBytes(1)); + try std.testing.expectEqual(laneFixedBytes() + 1152 * 4096, laneBytes(1025)); + try std.testing.expectEqual(@as(u64, 768 * 1032), scoreBytes(1024)); + // Ring and scores bytes are reserved with the target cache before the lane opens. +} diff --git a/zig/src/families/inkling2/metal/dspark_weights.zig b/zig/src/families/inkling2/metal/dspark_weights.zig new file mode 100644 index 00000000000..b9260e1b88f --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_weights.zig @@ -0,0 +1,176 @@ +//! Validated mtp.safetensors weights and the one-time folded Markov output head. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const cfg = @import("../config.zig"); +const Model = @import("model.zig").Model; +const fold = @import("dspark_fold.zig"); + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const intermediate = 9216; +pub const rank = 256; +pub const vocabulary = 201024; + +pub const Layer = struct { + dflare: ck.Tensor, + input_norm: ck.Tensor, + post_norm: ck.Tensor, + q_norm: ck.Tensor, + k_norm: ck.Tensor, + k_norm_ctx: ck.Tensor, + q: ck.Tensor, + k: ck.Tensor, + v: ck.Tensor, + k_ctx: ck.Tensor, + v_ctx: ck.Tensor, + o: ck.Tensor, + gate: ck.Tensor, + up: ck.Tensor, + down: ck.Tensor, +}; + +pub const Weights = struct { + fuse: ck.Tensor, + mask: ck.Tensor, + norm: ck.Tensor, + markov_norm: ck.Tensor, + hidden_out: ck.Tensor, + hidden_bias: ck.Tensor, + markov_w1: ck.Tensor, + rnn: ck.Tensor, + rnn_bias: ck.Tensor, + layers: [3]Layer, +}; + +pub const Loaded = struct { + checkpoint: ck.Checkpoint, + weights: Weights, + dflare: mtl.Buffer, // four H-wide rows: three layers, then the Markov head + phi: mtl.Buffer, // [201024,256] BF16, folded once in binary64 + beta: mtl.Buffer, // [201024] BF16 + + pub fn deinit(l: *Loaded) void { + l.beta.deinit(); + l.phi.deinit(); + l.dflare.deinit(); + l.checkpoint.deinit(); + l.* = undefined; + } + + pub fn fixedBytes(l: *const Loaded) u64 { + return l.checkpoint.residentBytes() + l.dflare.length() + l.phi.length() + l.beta.length(); + } +}; + +fn require(t: ck.Tensor, dims: []const usize, name: []const u8) !ck.Tensor { + if (t.dtype != .bf16 or t.rank != dims.len) { + std.log.err("DSpark tensor {s} must be BF16 with rank {d}", .{ name, dims.len }); + return error.DSparkTensorShape; + } + var count: usize = 1; + for (dims, 0..) |d, i| { + if (t.shape[i] != d) { + std.log.err("DSpark tensor {s} dimension {d} must be {d}, not {d}", .{ name, i, d, t.shape[i] }); + return error.DSparkTensorShape; + } + count = std.math.mul(usize, count, d) catch return error.DSparkTensorShape; + } + if (t.bytes != count * 2) return error.DSparkTensorShape; + return t; +} + +fn get(c: *const ck.Checkpoint, name: []const u8, dims: []const usize) !ck.Tensor { + const t = c.get(name) catch { + std.log.err("DSpark mtp.safetensors is missing {s}", .{name}); + return error.DSparkMissingTensor; + }; + return require(t, dims, name); +} + +fn admit(c: *const cfg.Config) !void { + const m = c.mtp orelse return error.DSparkNotConfigured; + if (m.layers != 3 or m.q_heads != 24 or m.kv_heads != 8 or m.head_dim != 128 or m.inter != intermediate or + m.window != 1024 or m.block != 8 or m.rank != rank or m.rope_theta != 1e6 or m.taps_n != 4 or + !m.local[0] or m.local[1] or !m.local[2] or !std.mem.eql(u32, m.taps[0..4], &.{ 5, 23, 41, 48 })) + return error.UnsupportedDSparkConfig; +} + +fn layer(c: *const ck.Checkpoint, i: usize) !Layer { + var b: [128]u8 = undefined; + const g = struct { + fn layerTensor(cp: *const ck.Checkpoint, buf: []u8, i_: usize, suffix: []const u8, dims: []const usize) !ck.Tensor { + const name = try std.fmt.bufPrint(buf, "layers.{d}.{s}", .{ i_, suffix }); + return get(cp, name, dims); + } + }.layerTensor; + return .{ + .dflare = try g(c, &b, i, "dflare_norm.weight", &.{hidden}), + .input_norm = try g(c, &b, i, "input_layernorm.weight", &.{hidden}), + .post_norm = try g(c, &b, i, "post_attention_layernorm.weight", &.{hidden}), + .q_norm = try g(c, &b, i, "self_attn.q_norm.weight", &.{128}), + .k_norm = try g(c, &b, i, "self_attn.k_norm.weight", &.{128}), + .k_norm_ctx = try g(c, &b, i, "self_attn.k_norm_ctx.weight", &.{128}), + .q = try g(c, &b, i, "self_attn.q_proj.weight", &.{ query, hidden }), + .k = try g(c, &b, i, "self_attn.k_proj.weight", &.{ kv, hidden }), + .v = try g(c, &b, i, "self_attn.v_proj.weight", &.{ kv, hidden }), + .k_ctx = try g(c, &b, i, "self_attn.k_proj_ctx.weight", &.{ kv, hidden }), + .v_ctx = try g(c, &b, i, "self_attn.v_proj_ctx.weight", &.{ kv, hidden }), + .o = try g(c, &b, i, "self_attn.o_proj.weight", &.{ hidden, query }), + .gate = try g(c, &b, i, "mlp.gate_proj.weight", &.{ intermediate, hidden }), + .up = try g(c, &b, i, "mlp.up_proj.weight", &.{ intermediate, hidden }), + .down = try g(c, &b, i, "mlp.down_proj.weight", &.{ hidden, intermediate }), + }; +} + +pub fn load(gpa: std.mem.Allocator, target: *const Model, dir: []const u8) !Loaded { + try admit(&target.config); + var checkpoint = ck.Checkpoint.init(gpa); + errdefer checkpoint.deinit(); + const path: [:0]u8 = if (std.mem.endsWith(u8, dir, ".safetensors")) + try std.fmt.allocPrintSentinel(gpa, "{s}", .{dir}, 0) + else + try std.fmt.allocPrintSentinel(gpa, "{s}/mtp.safetensors", .{dir}, 0); + defer gpa.free(path); + checkpoint.addFile(target.device, path, "") catch |err| { + std.log.err("DSpark cannot open {s}: {s}", .{ path, @errorName(err) }); + return error.DSparkMissingFile; + }; + const c = &checkpoint; + var layers: [3]Layer = undefined; + for (&layers, 0..) |*l, i| l.* = try layer(c, i); + const weights: Weights = .{ + .fuse = try get(c, "fuse_weight", &.{ 4, 4 }), + .mask = try get(c, "mask_embed", &.{hidden}), + .norm = try get(c, "norm.weight", &.{hidden}), + .markov_norm = try get(c, "markov_head.dflare_norm.weight", &.{hidden}), + .hidden_out = try get(c, "markov_head.hidden_out.weight", &.{ hidden, rank }), + .hidden_bias = try get(c, "markov_head.hidden_out.bias", &.{hidden}), + .markov_w1 = try get(c, "markov_head.markov_w1.weight", &.{ vocabulary, rank }), + .rnn = try get(c, "markov_head.rnn_proj.weight", &.{ 3 * rank, 2 * hidden + 2 * rank }), + .rnn_bias = try get(c, "markov_head.rnn_proj.bias", &.{3 * rank}), + .layers = layers, + }; + const dflare = try target.device.buffer(4 * hidden * 2, mtl.ResourceOptions.shared); + errdefer dflare.deinit(); + const dflare_packed = dflare.slice(u16, 4 * hidden); + for (weights.layers, 0..) |l, i| @memcpy(dflare_packed[i * hidden ..][0..hidden], l.dflare.host(u16)); + @memcpy(dflare_packed[3 * hidden ..][0..hidden], weights.markov_norm.host(u16)); + const phi = try target.device.buffer(vocabulary * rank * 2, mtl.ResourceOptions.shared); + errdefer phi.deinit(); + const beta = try target.device.buffer(vocabulary * 2, mtl.ResourceOptions.shared); + errdefer beta.deinit(); + try fold.fold(gpa, target.weights.unembed.host(u16), weights.hidden_out.host(u16), weights.hidden_bias.host(u16), phi.slice(u16, vocabulary * rank), beta.slice(u16, vocabulary)); + return .{ .checkpoint = checkpoint, .weights = weights, .dflare = dflare, .phi = phi, .beta = beta }; +} + +test "a misshapen DSpark tensor has a named refusal" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; + var t: ck.Tensor = .{ .buffer = undefined, .offset = 0, .bytes = 8, .dtype = .bf16, .rank = 1 }; + t.shape[0] = 4; + _ = try require(t, &.{4}, "witness"); + try std.testing.expectError(error.DSparkTensorShape, require(t, &.{ 2, 2 }, "witness")); + t.dtype = .f32; + try std.testing.expectError(error.DSparkTensorShape, require(t, &.{4}, "witness")); +} diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig new file mode 100644 index 00000000000..e75b57a089e --- /dev/null +++ b/zig/src/families/inkling2/metal/forward.zig @@ -0,0 +1,346 @@ +//! Mini's whole 48-visit forward, encoded entirely on Metal for prompt chunks and decode. +const std = @import("std"); +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 experts = @import("experts.zig"); +const loop = @import("loop.zig"); +const state = @import("state.zig"); +const model_file = @import("model.zig"); +const Model = model_file.Model; + +pub const Ref = state.Ref; +pub const Segment = struct { cache: *state.Cache, rows: usize }; +pub const Options = struct { + all: bool = false, + ids: ?Ref = null, + flight: ?*mtl.CommandBuffer = null, + taps: ?state.Ref = null, +}; + +pub const FinalPlan = struct { work_rows: usize, logits_rows: usize, logits_row: usize, capture_rows: usize }; + +/// Features normalize all rows; without full logits, only the last unembeds. taps=null preserves the original plan. +pub fn finalPlan(rows: usize, all: bool, taps: bool) FinalPlan { + std.debug.assert(rows > 0); + return .{ + .work_rows = if (all or taps) rows else 1, + .logits_rows = if (all) rows else 1, + .logits_row = if (!all and taps) rows - 1 else 0, + .capture_rows = if (taps) rows else 0, + }; +} + +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 }; +const DenseArgs = extern struct { rows: u32, n: u32, k: u32, ldy: u32 }; + +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 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 }; +} +fn arRow(s: *state.Scratch, role: usize, rows: usize, i: usize, gated: bool) Ref { + return at(if (gated) s.gated else s.ar, (role * rows + i) * state.hidden * 4); +} +fn messageRow(s: *state.Scratch, core: usize, role: usize, i: usize) Ref { + return at(s.messages, ((i * state.message_entries + core * 4 + role) * state.hidden) * 4); +} + +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); +} +fn widen(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .widen, &.{ from, to }, count, 0); +} + +fn norm(m: *const Model, e: mtl.ComputeEncoder, input: Ref, weight: ck.Tensor, out: Ref, rows: usize) void { + e.setPipeline(m.norm); + inline for (.{ input, r(weight), out }, 0..) |v, i| e.setBuffer(v.buf, v.off, i); + e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// Every projection uses the shared BF16 matvec's FP32 reduction and one BF16 store. +pub fn dense(m: *const Model, e: mtl.ComputeEncoder, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) void { + const k = weight.shape[weight.rank - 1]; + const n = weight.shape[weight.rank - 2]; + var base: usize = 0; + while (base < rows) { + const left = rows - base; + const take: usize = if (left >= 32) 32 else if (left >= 16) 16 else if (left >= 8) 8 else if (left >= 4) 4 else if (left >= 2) 2 else 1; + const variant: usize = switch (take) { + 1 => 0, + 2 => 1, + 4 => 2, + 8 => 3, + 16 => 4, + 32 => 5, + else => unreachable, + }; + e.setPipeline(m.dense[variant]); + e.setBuffer(input.buf, input.off + base * k * 2, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(DenseArgs{ .rows = @intCast(take), .n = @intCast(n), .k = @intCast(k), .ldy = @intCast(n) }, 2); + e.setBuffer(out.buf, out.off + base * n * 2, 3); + e.dispatchGroups(mtl.Size.of((n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + base += take; + } +} + +/// One row because M2's AR ABI is [sources,H] -> [queries,H]. Batch composition never mixes rows. +fn residual(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, queries: ck.Tensor, sources: usize, rows: usize) void { + for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(queries), row(s.mlp_ar, i, state.hidden * 4), @intCast(sources), 1); +} + +fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, rows: usize) void { + for (0..rows) |i| { + // The second completed block of the previous pass is B12; its final p is P18. + 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); + 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); +} + +fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize) void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + if (v.layer == 0) { + widen(m, e, at(s.p, 0), at(s.ar, 0), rows * state.hidden); + } else { + const q = m.weights.attn_queries[v.layer - 1]; + for (0..lp.attn_queries) |role| { + const query = at(q.buffer, q.offset + role * state.hidden * 4); + for (0..rows) |i| glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), query, arRow(s, role, rows, i, false), lp.attn_sources, 1); + } + } + if (v.hasMessages()) { + const controllers = w.controllers.?; + const core = v.layer - 6; + for (0..3) |role| for (0..rows) |i| { + const c = controllers[role]; + const source_role = if (lp.kind == .local) 0 else role; + loop.gates(&m.loop, e, l(arRow(s, source_role, rows, i, false)), l(messageRow(s, core, role, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(arRow(s, role, rows, i, true)), 1); + }; + } + 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) { + norm(m, e, arRow(s, 0, rows, 0, false), w.attn.q_norm, at(s.q_norm, 0), rows); + } else { + norm(m, e, arRow(s, 0, rows, 0, gated), w.attn.q_norm, at(s.q_norm, 0), rows); + norm(m, e, arRow(s, 1, rows, 0, gated), w.attn.k_norm, at(s.k_norm, 0), rows); + norm(m, e, arRow(s, 2, rows, 0, gated), w.attn.v_norm, at(s.v_norm, 0), rows); + } +} + +fn staticPostConv(m: *const Model, e: mtl.ComputeEncoder, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, weight: ck.Tensor, out: Ref, base: usize, rows: usize) void { + 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); + 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) !void { + 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); + const layer = ap.Layer{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = layer0.chunk, .tau = layer0.tau }; + const start = cache.len; + const rr = ap.Rows{ .rows = @intCast(rows), .heads = 24, .kv_heads = 8, .last_pos = @intCast(start + rows - 1), .streams = 1 }; + 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 meta = attention.RowMeta{ + .pos = a(at(s.pos, base * 4)), + .seg_of = a(at(s.seg_of, base * 4)), + .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)) }; + try convInputForAttention(m, e, s, cache, v, base, rows, true); + try convInputForAttention(m, e, s, cache, v, base, rows, false); + attention.prep(&m.attention, e, rr, layer, prep, meta, .{ 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)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * 24 * ap.extent * 2)), kv); + attention.relTable(&m.attention, e, rr, a(at(s.rel_prep, base * 24 * ap.extent * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.rel_tab, base * 24 * ap.extent * 2))); + try attention.attend(&m.attention, e, rr, layer, state.max_attention_stride, 0, meta, a(at(s.q_prep, base * state.query_width * 2)), kv, a(at(s.rel_tab, base * 24 * ap.extent * 2)), a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)), a(at(s.sink, base * 24 * 2)), a(at(s.gate, base * state.query_width * 2)), a(at(s.att, base * state.query_width * 2))); + base += rows; + } +} + +fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool) !void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + const raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2); + const projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2); + const normalized = if (key) at(s.k_norm, 0) else if (v.hasMessages() or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + const taps = cache.staged(v.cache_slot, if (key) 0 else 1, 0); + copyBf16(m, e, cache.history(v.cache_slot, if (key) 0 else 1), taps, 3 * state.kv_width); + copyBf16(m, e, projected, cache.staged(v.cache_slot, if (key) 0 else 1, 3), rows * state.kv_width); + switch (if (key) w.attn.k_conv else w.attn.v_conv) { + .static => |weight| glue.convStatic(&m.glue, e, taps, r(weight), raw, @intCast(rows), state.kv_width), + .dynamic => |d| glue.convDynamic(&m.glue, e, taps, at(normalized.buf, normalized.off + base * state.hidden * 2), r(d.static_w), r(d.projection), raw, @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 precision: experts.Format = switch (m.weight_plan.at(@intCast(layer)).precision) { + .nvfp4 => .nvfp4, + .mxfp8 => .mxfp8, + }; + const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; + const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = precision }; + if (precision == .nvfp4) { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), 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.route_ids, 0)), x(at(s.gu, 0)), gu_call); + } else { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), 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, segments: []const Segment, rows: usize, taps: ?state.Ref) !void { + const lp = m.weight_plan.at(v.layer); + const gated = v.hasMessages(); + if (taps) |to| { + const channel: ?usize = switch (v.cache_slot) { + 5 => 0, + 23 => 1, + 41 => 2, + else => null, + }; + if (channel) |ch| captureTap(m, e, at(s.p, 0), to, rows, ch); + } + if (v.pass > 1 and v.layer == 6) bankAndReset(m, e, s, rows); + const w = &m.weights.layers[v.layer]; + // The running BF16 p is the partial AR source before attention replaces it with t. + widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + prepareAttentionInputs(m, e, s, v, rows); + 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); + dense(m, e, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); + dense(m, e, w.attn.wk, knorm, at(s.k_raw, 0), rows); + dense(m, e, w.attn.wv, vnorm, at(s.v_raw, 0), rows); + dense(m, e, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); + dense(m, e, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); + dense(m, e, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); + try attendSegments(m, e, s, v, segments); + dense(m, e, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + var base: usize = 0; + for (segments) |seg| { + staticPostConv(m, e, seg.cache, v.cache_slot, 2, at(s.attn_dense, 0), w.attn_conv, at(s.attn_conv, 0), base, seg.rows); + base += seg.rows; + } + runtime(m, e, .attention_partial, &.{ at(s.p, 0), at(s.attn_conv, 0), at(s.blocks, 0), at(s.partial, 0) }, rows * state.hidden, if (lp.boundary) lp.blocks_in + 1 else 0); + residual(m, e, s, m.weights.mlp_queries[v.layer], lp.mlp_sources, rows); + if (gated) { + const c = w.controllers.?[3]; + const core = v.layer - 6; + for (0..rows) |i| loop.gates(&m.loop, e, l(row(s.mlp_ar, i, state.hidden * 4)), l(messageRow(s, core, 3, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(row(s.mlp_gated, i, state.hidden * 4)), 1); + norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + } else norm(m, e, at(s.mlp_ar, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + 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); + base = 0; + for (segments) |seg| { + staticPostConv(m, e, seg.cache, v.cache_slot, 3, at(s.mlp_out, 0), w.mlp_conv, at(s.mlp_conv, 0), base, seg.rows); + base += seg.rows; + } + 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); +} + +fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment) void { + _ = s; + 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)); + }; +} + +pub fn run(m: *const Model, s: *state.Scratch, cache: *state.Cache, ids: []const u32, options: Options) !void { + return runShared(m, s, &.{.{ .cache = cache, .rows = ids.len }}, ids, options); +} + +pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, ids: []const u32, options: Options) !void { + const rows = ids.len; + 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; + var total: usize = 0; + var base: usize = 0; + for (segments, 0..) |seg, si| { + if (seg.rows == 0 or seg.rows > state.max_rows or seg.cache.len + seg.rows > seg.cache.capacity) return error.Inkling2ContextFull; + if (seg.rows > state.window_rows and seg.cache.pending != null) return error.Inkling2CacheTransaction; + if (seg.cache.pending) |pending| if (pending != seg.rows) return error.Inkling2CacheTransaction; + total += seg.rows; + for (0..seg.rows) |i| { + s.pos.slice(i32, rows)[base + i] = @intCast(seg.cache.len + i); + s.seg_of.slice(i32, rows)[base + i] = 0; + } + s.segs.slice(ap.Seg, state.max_segments)[si] = .{ .row0 = 0, .n = @intCast(seg.rows), .p0 = @intCast(seg.cache.len), .off = 0 }; + base += seg.rows; + } + if (total != rows) return error.Inkling2Segments; + if (options.ids == null) { + for (ids) |id| if (id >= m.config.text.vocab) return error.Inkling2Token; + @memcpy(s.ids.slice(u32, rows), ids); + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = m.queue.commandBuffer(); + const e = cb.compute(.serial); + 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)); + for (m.weight_plan.visits[0..m.weight_plan.n_visits]) |*v| try visit(m, e, s, v, segments, rows, options.taps); + widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + const final = finalPlan(rows, options.all, options.taps != null); + for (0..final.work_rows) |j| { + const i = if (final.work_rows == rows) j else rows - 1; + glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(m.weights.output_query), row(s.mlp_ar, j, state.hidden * 4), m.weight_plan.final_sources, 1); + } + norm(m, e, at(s.mlp_ar, 0), m.weights.norm, at(s.mlp_normed, 0), final.work_rows); + 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); + commitFullHistories(m, e, s, segments); + e.end(); + cb.commit(); + if (options.flight) |flight| { + flight.* = cb.retain(); + return; + } + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop forward: {s}", .{msg}); + return error.GpuFailed; + } +} diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig new file mode 100644 index 00000000000..e9e1998f151 --- /dev/null +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -0,0 +1,16 @@ +//! Host-only Inkling 2 Mini Metal launch plans and scalar arithmetic references. + +test { + _ = @import("attention_test.zig"); + _ = @import("glue_test.zig"); + _ = @import("experts_test.zig"); + _ = @import("loop_test.zig"); + _ = @import("runtime_test.zig"); + _ = @import("runtime_kernels_test.zig"); + _ = @import("dspark_kernels_test.zig"); + _ = @import("dspark_fold.zig"); + _ = @import("dspark_weights.zig"); + _ = @import("dspark_state.zig"); + _ = @import("dspark.zig"); + _ = @import("backend.zig"); +} diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig new file mode 100644 index 00000000000..078104e1f62 --- /dev/null +++ b/zig/src/families/inkling2/metal/model.zig @@ -0,0 +1,294 @@ +//! Inkling 2 Mini's resident text model: validated checkpoint weights and every Metal pipeline. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const cfg = @import("../config.zig"); +const layer_plan = @import("../plan.zig"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const shards = @import("../../../core/checkpoint.zig"); +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const experts = @import("experts.zig"); +const loop = @import("loop.zig"); + +pub const Tensor = ck.Tensor; +pub const DynamicConv = struct { static_w: Tensor, projection: Tensor }; +pub const Conv = union(enum) { static: Tensor, dynamic: DynamicConv }; +pub const Controller = struct { down: Tensor, forget: Tensor, gain: Tensor }; +pub const AttentionWeights = struct { + wq: Tensor, + wk: Tensor, + wv: Tensor, + wr: Tensor, + wo: Tensor, + gate: Tensor, + sink: Tensor, + q_scale: Tensor, + rel_scale: Tensor, + rel_projection: Tensor, + k_conv: Conv, + v_conv: Conv, + q_norm: Tensor, + k_norm: Tensor, + v_norm: Tensor, +}; +pub const ExpertMatrix = struct { + weight: Tensor, + scale: Tensor, + amax: ?Tensor = null, + denominator: ?Tensor = null, +}; +pub const LayerWeights = struct { + attn: AttentionWeights, + attn_conv: Tensor, + mlp_norm: Tensor, + mlp_conv: Tensor, + router_weight: Tensor, + router_bias: Tensor, + gu: ExpertMatrix, + down: ExpertMatrix, + controllers: ?[4]Controller, +}; +pub const Weights = struct { + embed: Tensor, + embed_norm: Tensor, + norm: Tensor, + unembed: Tensor, + output_query: Tensor, + cross_queries: Tensor, + cross_kv_queries: Tensor, + attn_queries: [23]Tensor, + mlp_queries: [24]Tensor, + layers: [24]LayerWeights, +}; + +/// Scalar copies and residuals around dispatch stay on Metal; forward never reads tensors back to the host. +pub const runtime_source = sources.inkling2_runtime; + +pub const RuntimeOp = enum { copy_bf16, copy_f32, widen, attention_partial, mlp_partial, capture_tap }; +pub const runtime_names = [_][:0]const u8{ + "tf_ink2_copy_bf16", + "tf_ink2_copy_f32", + "tf_ink2_widen", + "tf_ink2_attention_partial", + "tf_ink2_mlp_partial", + "tf_ink2_capture_tap", +}; + +pub fn admitConfig(c: *const cfg.Config) !void { + const t = c.text; + const l = t.loop orelse return error.Inkling2NotMini; + if (l.passes != 3 or l.core_start != 6 or l.core_end != 18 or l.gate_rank != 64) + return error.UnsupportedInkling2Loop; + if (t.hidden != 2304 or t.layers != 24 or t.vocab != 201024 or t.unpadded_vocab != 200058 or + t.window != 1024 or t.d_rel != 16 or t.rel_extent != 1024 or t.log_floor != 8192 or + t.block != 6 or t.experts != 128 or t.topk != 8 or t.expert_inter != 1152 or + t.max_context != 1048576) return error.UnsupportedInkling2Geometry; + for ([_]cfg.Heads{ t.local, t.global }) |h| if (h.q != 24 or h.kv != 8 or h.dim != 128) + return error.UnsupportedInkling2Geometry; + if (t.eps != 1e-6 or t.log_alpha != 0.1 or t.qk_clip != 22.627416997969522 or + t.rel_clip != 8 or t.route_scale != 8 or t.gate_cap != 4 or t.up_cap != 25 or + t.logit_cap != 30) return error.UnsupportedInkling2Constants; +} + +fn require(t: Tensor, dtype: ck.DType, dims: []const usize) !Tensor { + if (t.dtype != dtype or t.rank != dims.len) return error.UnexpectedInkling2Tensor; + for (dims, 0..) |d, i| if (t.shape[i] != d) return error.UnexpectedInkling2Tensor; + var count: usize = 1; + for (dims) |d| count = std.math.mul(usize, count, d) catch return error.UnexpectedInkling2Tensor; + if (t.bytes != count * dtype.size()) return error.UnexpectedInkling2Tensor; + return t; +} + +fn get(c: *const ck.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: ck.DType, dims: []const usize) !Tensor { + var buf: [256]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return require(try c.get(name), dtype, dims); +} + +fn matrix(c: *const ck.Checkpoint, layer: u32, comptime suffix: []const u8, precision: layer_plan.Precision, rows: usize, k: usize) !ExpertMatrix { + const base = "model.llm.layers.{d}.mlp.experts." ++ suffix; + const e = 128; + switch (precision) { + .nvfp4 => return .{ + .weight = try get(c, base ++ "_weight", .{layer}, .u8, &.{ e, rows, k / 2 }), + .scale = try get(c, base ++ "_weight_scale", .{layer}, .f8_e4m3, &.{ e, rows, k / 16 }), + .amax = try get(c, base ++ "_weight_amax", .{layer}, .f32, &.{e}), + .denominator = try get(c, base ++ "_weight_outer_scale_denominator", .{layer}, .f32, &.{1}), + }, + .mxfp8 => return .{ + .weight = try get(c, base ++ "_weight", .{layer}, .f8_e4m3, &.{ e, rows, k }), + .scale = try get(c, base ++ "_weight_scale", .{layer}, .u8, &.{ e, rows, k / 32 }), + }, + } +} + +fn loadConv(c: *const ck.Checkpoint, layer: u32, comptime role: []const u8, global: bool) !Conv { + if (!global) return .{ .static = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.weight", .{layer}, .bf16, &.{ 1024, 1, 4 }) }; + return .{ .dynamic = .{ + .static_w = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.static_w", .{layer}, .bf16, &.{ 4, 1024 }), + .projection = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.weight_proj", .{layer}, .bf16, &.{ 32, 2304 }), + } }; +} + +fn loadWeights(c: *const ck.Checkpoint, config: *const cfg.Config, wp: *const layer_plan.Plan) !Weights { + var w: Weights = undefined; + w.embed = try get(c, "model.llm.embed.weight", .{}, .bf16, &.{ 201024, 2304 }); + w.embed_norm = try get(c, "model.llm.embed_norm.weight", .{}, .bf16, &.{2304}); + w.norm = try get(c, "model.llm.norm.weight", .{}, .bf16, &.{2304}); + w.unembed = try get(c, "model.llm.unembed.weight", .{}, .bf16, &.{ 201024, 2304 }); + w.output_query = try get(c, "model.llm.attn_res.output_query", .{}, .f32, &.{2304}); + w.cross_queries = try get(c, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 24, 2304 }); + w.cross_kv_queries = try get(c, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 24, 2304 }); + for (&w.attn_queries, 0..) |*q, i| { + const global = cfg.isGlobal(@intCast(i + 1)); + const dims: []const usize = if (global) &.{ 3, 2304 } else &.{2304}; + q.* = try get(c, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); + } + for (&w.mlp_queries, 0..) |*q, i| q.* = try get(c, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{2304}); + for (&w.layers, 0..) |*l, i| { + const layer: u32 = @intCast(i); + const p = wp.at(layer); + const global = p.kind == .global; + const q_width: usize = @as(usize, p.heads.q) * p.heads.dim; + const local_norm = if (!global) try get(c, "model.llm.layers.{d}.attn_norm.weight", .{layer}, .bf16, &.{2304}) else undefined; + l.attn = .{ + .wq = try get(c, "model.llm.layers.{d}.attn.wq_du.weight", .{layer}, .bf16, &.{ q_width, 2304 }), + .wk = try get(c, "model.llm.layers.{d}.attn.wk_dv.weight", .{layer}, .bf16, &.{ 1024, 2304 }), + .wv = try get(c, "model.llm.layers.{d}.attn.wv_dv.weight", .{layer}, .bf16, &.{ 1024, 2304 }), + .wr = try get(c, "model.llm.layers.{d}.attn.wr_du.weight", .{layer}, .bf16, &.{ 384, 2304 }), + .wo = try get(c, "model.llm.layers.{d}.attn.wo_ud.weight", .{layer}, .bf16, &.{ 2304, q_width }), + .gate = try get(c, "model.llm.layers.{d}.attn.gate_attn.weight", .{layer}, .bf16, &.{ q_width, 2304 }), + .sink = try get(c, "model.llm.layers.{d}.attn.attn_sink_proj.weight", .{layer}, .bf16, &.{ 24, 2304 }), + .q_scale = try get(c, "model.llm.layers.{d}.attn.q_l2_clip.scale", .{layer}, .bf16, &.{ 24, 128 }), + .rel_scale = try get(c, "model.llm.layers.{d}.attn.rel_l2_clip.scale", .{layer}, .bf16, &.{ 24, 16 }), + .rel_projection = try get(c, "model.llm.layers.{d}.attn.rel_logits_proj.proj", .{layer}, .bf16, &.{ 16, p.extent }), + .k_conv = try loadConv(c, layer, "k", global), + .v_conv = try loadConv(c, layer, "v", global), + .q_norm = if (global) try get(c, "model.llm.layers.{d}.q_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + .k_norm = if (global) try get(c, "model.llm.layers.{d}.k_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + .v_norm = if (global) try get(c, "model.llm.layers.{d}.v_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + }; + l.attn_conv = try get(c, "model.llm.layers.{d}.attn_sconv.weight", .{layer}, .bf16, &.{ 2304, 1, 4 }); + l.mlp_norm = try get(c, "model.llm.layers.{d}.mlp_norm.weight", .{layer}, .bf16, &.{2304}); + l.mlp_conv = try get(c, "model.llm.layers.{d}.mlp_sconv.weight", .{layer}, .bf16, &.{ 2304, 1, 4 }); + l.router_weight = try get(c, "model.llm.layers.{d}.mlp.gate.weight", .{layer}, .bf16, &.{ 128, 2304 }); + l.router_bias = try get(c, "model.llm.layers.{d}.mlp.gate.bias", .{layer}, .f32, &.{128}); + l.gu = try matrix(c, layer, "w13", p.precision, 2304, 2304); + l.down = try matrix(c, layer, "w2", p.precision, 2304, 1152); + l.controllers = null; + if (config.text.loop) |lp| if (layer >= lp.core_start and layer < lp.core_end) { + var controllers: [4]Controller = undefined; + inline for (.{ "attn", "k", "v", "mlp" }, 0..) |role, j| controllers[j] = .{ + .down = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".down_weight", .{layer}, .bf16, &.{ 64, 4608 }), + .forget = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".forget_weight", .{layer}, .bf16, &.{ 2304, 64 }), + .gain = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".gain_weight", .{layer}, .bf16, &.{ 2304, 64 }), + }; + l.controllers = controllers; + }; + } + return w; +} + +pub const Model = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + config: cfg.Config, + checkpoint: ck.Checkpoint, + weights: Weights, + weight_plan: layer_plan.Plan, + attention: attention.Kernels, + glue: glue.Pipelines, + experts: experts.Pipelines, + loop: loop.Pipelines, + dense: [6]mtl.Pipeline, + norm: mtl.Pipeline, + runtime: [runtime_names.len]mtl.Pipeline, + + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try gpa.create(Model); + errdefer gpa.destroy(m); + m.gpa = gpa; + const config_path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(config_path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 24)); + defer gpa.free(text); + var why: cfg.Why = .{}; + m.config = cfg.parse(gpa, text, &why) catch |err| { + std.log.err("inkling2_loop: {s}", .{why.text()}); + return err; + }; + try admitConfig(&m.config); + m.device = try mtl.Device.init(); + errdefer m.device.deinit(); + m.queue = try m.device.queue(); + errdefer m.queue.deinit(); + m.checkpoint = ck.Checkpoint.init(gpa); + errdefer m.checkpoint.deinit(); + const files = try shards.shardFiles(gpa, io, dir); + defer shards.freeShardFiles(gpa, files); + + // Mini uses NVFP4 for layers 0-19 and MXFP8 for 20-23; matrix() rechecks all stored tensor metadata and bytes. + var precisions: [24]layer_plan.Precision = undefined; + for (&precisions, 0..) |*p, i| p.* = if (i < 20) .nvfp4 else .mxfp8; + m.weight_plan = try layer_plan.build(&m.config.text, &precisions); + if (m.weight_plan.n_visits != 48) return error.UnsupportedInkling2Loop; + for (files) |path| try m.checkpoint.addFileSelected(m.device, path, "", "model.llm."); + m.weights = try loadWeights(&m.checkpoint, &m.config, &m.weight_plan); + + m.attention = try attention.Kernels.init(gpa, m.device); + errdefer m.attention.deinit(); + m.glue = try glue.Pipelines.load(m.device); + errdefer m.glue.deinit(); + m.experts = try experts.Pipelines.load(m.device); + errdefer m.experts.deinit(); + m.loop = try loop.Pipelines.load(m.device); + errdefer m.loop.deinit(); + { + const lib = try mtl.Library.fromSource(m.device, sources.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.dense[0..made]) |p| p.deinit(); + for ([_]u32{ 1, 2, 4, 8, 16, 32 }, 0..) |rows, i| { + var buf: [32]u8 = undefined; + const name = try std.fmt.bufPrintSentinel(&buf, "sp_matvec_{d}", .{rows}, 0); + m.dense[i] = try mtl.Pipeline.init(m.device, lib, name, false); + made += 1; + } + m.norm = try mtl.Pipeline.init(m.device, lib, "sp_norm", false); + } + errdefer { + m.norm.deinit(); + for (m.dense) |p| p.deinit(); + } + { + const lib = try mtl.Library.fromSource(m.device, runtime_source, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.runtime[0..made]) |p| p.deinit(); + for (runtime_names, 0..) |name, i| { + m.runtime[i] = try mtl.Pipeline.init(m.device, lib, name, false); + made += 1; + } + } + errdefer for (m.runtime) |p| p.deinit(); + return m; + } + + pub fn deinit(m: *Model) void { + for (m.runtime) |p| p.deinit(); + m.norm.deinit(); + for (m.dense) |p| p.deinit(); + m.loop.deinit(); + m.experts.deinit(); + m.glue.deinit(); + m.attention.deinit(); + m.checkpoint.deinit(); + m.queue.deinit(); + m.device.deinit(); + m.gpa.destroy(m); + } +}; diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig new file mode 100644 index 00000000000..f8346da47e3 --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -0,0 +1,176 @@ +//! Host-only schedule, cache-layout, accepted-history and compact-snapshot checks. +const std = @import("std"); +const cfg = @import("../config.zig"); +const layer_plan = @import("../plan.zig"); +const state = @import("state.zig"); +const snapshot = @import("snapshot.zig"); +const model = @import("model.zig"); +const fwd = @import("forward.zig"); +const backend = @import("backend.zig"); + +fn mini() cfg.Config { + return .{ + .text = .{ + .hidden = 2304, + .layers = 24, + .vocab = 201024, + .unpadded_vocab = 200058, + .local = .{ .q = 24, .kv = 8, .dim = 128 }, + .global = .{ .q = 24, .kv = 8, .dim = 128 }, + .window = 1024, + .d_rel = 16, + .rel_extent = 1024, + .log_floor = 8192, + .log_alpha = 0.1, + .eps = 1e-6, + .qk_clip = 22.627416997969522, + .rel_clip = 8, + .block = 6, + .experts = 128, + .topk = 8, + .expert_inter = 1152, + .route_scale = 8, + .gate_cap = 4, + .up_cap = 25, + .logit_cap = 30, + .max_context = 1048576, + .loop = .{ .core_start = 6, .core_end = 18, .passes = 3, .gate_rank = 64 }, + }, + .vision = undefined, + .mtp = null, + .eos = 200055, + .image_token = 200054, + }; +} + +fn schedule() layer_plan.Plan { + const c = mini(); + var precision: [24]layer_plan.Precision = @splat(.nvfp4); + for (precision[4..]) |*p| p.* = .mxfp8; + return layer_plan.build(&c.text, &precision) catch unreachable; +} + +test "Mini admits only its fixed geometry and expands 24 weights to 48 visits" { + const c = mini(); + try model.admitConfig(&c); + const p = schedule(); + try std.testing.expectEqual(@as(u32, 48), p.n_visits); + try std.testing.expectEqual(@as(u32, 8), p.visitCount(.global)); + try std.testing.expectEqual(@as(u32, 5), p.final_sources); + for (p.visits[0..p.n_visits], 0..) |v, i| { + try std.testing.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try std.testing.expect(v.layer < 24); + } + for ([_]usize{ 18, 30 }) |i| { + try std.testing.expect(p.visits[i].pass > 1); + try std.testing.expectEqual(@as(u32, 6), p.visits[i].layer); + try std.testing.expect(p.visits[i].hasMessages()); + } + try std.testing.expect(!p.visits[0].hasMessages()); + try std.testing.expect(!(p.visits[17].pass > 1 and p.visits[17].layer == 6)); +} + +test "Every visit and convolution role has disjoint persistent and staged bytes" { + var previous_persistent: usize = 0; + for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| { + const off = state.convByteOffset(slot, cs, 0, 3); + const len = 3 * state.convWidth(cs) * 2; + 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); + 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); + try std.testing.expectEqual(old + accepted * state.hidden * 2, selected); + } +} + +test "Compact snapshots charge global prefixes and sliding physical rings" { + const one_layer_pair: u64 = state.kv_width * 2 * 2; + for ([_]usize{ 0, 1, 1024, state.sliding_ring, state.sliding_ring + 1 }) |at| { + const n: u64 = @intCast(at); + const live = @as(u64, 8) * n + @as(u64, 40) * @as(u64, @intCast(@min(at, state.sliding_ring))); + const kv = live * one_layer_pair; + const expected = kv + state.conv_bytes; + try std.testing.expectEqual(expected, snapshot.bytes(at)); + } + try std.testing.expect(snapshot.bytes(4096) < snapshot.bytes(8192)); + try std.testing.expectEqual(state.conv_bytes, state.visit_slots * 3 * state.conv_row_values * 2); +} + +test "DSpark feature rows are 4x2304 BF16 and ranges expose only live accepted rows" { + try std.testing.expectEqual(@as(usize, 4 * 2304 * 2), state.feature_row_bytes); + try std.testing.expectEqual(@as(usize, 7 * 4 * 2304 * 2), state.captureBytes(7)); + const off = 3 * state.feature_row_bytes; + const tp = state.Tap{ .buf = null, .off = off, .start = 100, .rows = 4, .gen = 9 }; + try std.testing.expectEqual(off, try state.featureOffset(tp, 100, 4, 9)); + try std.testing.expectEqual(off + 2 * state.feature_row_bytes, try state.featureOffset(tp, 102, 2, 9)); + try std.testing.expectError(error.StaleInkling2Taps, state.featureOffset(tp, 100, 1, 10)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 99, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 102, 3, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 104, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 100, 0, 9)); + var accepted = tp; + accepted.rows = 2; + try std.testing.expectEqual(off + state.feature_row_bytes, try state.featureOffset(accepted, 101, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(accepted, 102, 1, 9)); + accepted.gen = null; // the copied prompt-last row survives later scratch generations + try std.testing.expectEqual(off, try state.featureOffset(accepted, 100, 1, 1000)); +} + +test "tap48 captures every final-norm row but last-row-only logits keep their exact source" { + const captured = fwd.finalPlan(7, false, true); + try std.testing.expectEqual(@as(usize, 7), captured.work_rows); + try std.testing.expectEqual(@as(usize, 7), captured.capture_rows); + try std.testing.expectEqual(@as(usize, 1), captured.logits_rows); + try std.testing.expectEqual(@as(usize, 6), captured.logits_row); + try std.testing.expectEqual(@as(usize, 6 * state.hidden * 2), captured.logits_row * state.hidden * 2); + const all = fwd.finalPlan(7, true, true); + try std.testing.expectEqual(@as(usize, 7), all.logits_rows); + try std.testing.expectEqual(@as(usize, 0), all.logits_row); +} + +test "no-draft defaults retain KIM2's single last-row final norm and no capture" { + const options: fwd.Options = .{}; + try std.testing.expect(options.taps == null); + const plain = fwd.finalPlan(7, false, options.taps != null); + try std.testing.expectEqual(@as(usize, 1), plain.work_rows); + try std.testing.expectEqual(@as(usize, 0), plain.capture_rows); + try std.testing.expectEqual(@as(usize, 1), plain.logits_rows); + try std.testing.expectEqual(@as(usize, 0), plain.logits_row); + const all = fwd.finalPlan(7, true, false); + try std.testing.expectEqual(@as(usize, 7), all.work_rows); + try std.testing.expectEqual(@as(usize, 7), all.logits_rows); + try std.testing.expectEqual(@as(usize, 0), all.capture_rows); +} + +test "prepare_features requires exactly Mini's checkpoint tap list" { + var c = mini(); + c.mtp = .{ + .layers = 3, + .q_heads = 24, + .kv_heads = 8, + .head_dim = 128, + .inter = 9216, + .rope_theta = 1e6, + .window = 1024, + .local = .{ true, false, true, false, false, false, false, false }, + .block = 8, + .rank = 256, + .taps = .{ 5, 23, 41, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .taps_n = 4, + }; + try backend.validateTaps(&c, &.{ 5, 23, 41, 48 }); + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41 })); + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 11, 41, 48 })); + c.mtp.?.taps[1] = 22; + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); + c.mtp = null; + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); +} diff --git a/zig/src/families/inkling2/metal/snapshot.zig b/zig/src/families/inkling2/metal/snapshot.zig new file mode 100644 index 00000000000..4004e4dce88 --- /dev/null +++ b/zig/src/families/inkling2/metal/snapshot.zig @@ -0,0 +1,85 @@ +//! Compact retained snapshots of every live KV ring prefix and all convolution states. +const std = @import("std"); +const mtl = @import("metal"); +const state = @import("state.zig"); + +/// Eight global layers retain [0,at); forty sliding layers retain ring prefixes, with independent K/V pieces per visit. +pub fn bytes(at: usize) u64 { + const keys = @as(u64, 8) * @as(u64, @intCast(at)) + @as(u64, 40) * @as(u64, @intCast(@min(at, state.sliding_ring))); + return keys * @as(u64, state.kv_width) * 4 + state.conv_bytes; +} + +pub const Snap = struct { + buf: mtl.Buffer, + at: usize, + bytes: u64, + freed: bool = false, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn free(s: *Snap) void { + if (!s.freed) { + s.setResident(null); + s.buf.deinit(); + s.freed = true; + } + } + + pub fn deinit(s: *Snap) void { + s.free(); + } + + pub fn setResident(s: *Snap, hook: ?mtl.ResidencySet.Follow) void { + if (s.freed) return; + if (s.follow) |f| f.leave(f.ctx, s.buf); + s.follow = hook; + if (hook) |f| f.join(f.ctx, s.buf); + } +}; + +fn encode(queue: mtl.Queue, cache: *const state.Cache, snap_buf: mtl.Buffer, snap: ?*const Snap, comptime what: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + var at: usize = 0; + const len = if (snap) |image| image.at else cache.len; + for (0..state.visit_slots) |slot| { + const live = if (cache.globals[slot]) len else @min(len, cache.ring(slot)); + const n = live * state.kv_width * 2; + if (n != 0) if (snap) |image| { + e.copy(image.buf, at, cache.kv, cache.key_at[slot], n); + at += n; + e.copy(image.buf, at, cache.kv, cache.value_at[slot], n); + } else { + e.copy(cache.kv, cache.key_at[slot], snap_buf, at, n); + at += n; + e.copy(cache.kv, cache.value_at[slot], snap_buf, at, n); + }; + at += n; + } + if (snap) |image| e.copy(image.buf, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, snap_buf, at, state.conv_bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop snapshot {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +/// GPU-private snapshots retain only live global and sliding prefixes, never full-capacity allocations. +pub fn save(device: mtl.Device, queue: mtl.Queue, cache: *const state.Cache) !Snap { + if (cache.pending != null) return error.Inkling2CacheTransaction; + const size = bytes(cache.len); + const buf = try device.buffer(@intCast(size), mtl.ResourceOptions.private); + errdefer buf.deinit(); + try encode(queue, cache, buf, null, "save"); + return .{ .buf = buf, .at = cache.len, .bytes = size }; +} + +/// Restore into an empty, large-enough cache; global capacity may grow while sliding positions stay unchanged. +pub fn restore(cache: *state.Cache, queue: mtl.Queue, snap: *const Snap) !void { + if (snap.freed or cache.len != 0 or cache.pending != null or snap.at > cache.capacity or snap.bytes < bytes(snap.at)) return error.Inkling2SnapshotGeometry; + try encode(queue, cache, snap.buf, snap, "restore"); + cache.len = snap.at; +} diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig new file mode 100644 index 00000000000..01c2085e4b7 --- /dev/null +++ b/zig/src/families/inkling2/metal/state.zig @@ -0,0 +1,369 @@ +//! Forty-eight independent visit caches and the GPU buffers used by one whole-loop forward. +const std = @import("std"); +const mtl = @import("metal"); +const plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); + +pub const window_rows = 16; +pub const batch_rows = 32; +pub const prompt_rows = 64; +pub const max_rows = 64; +pub const max_segments = batch_rows; +pub const max_attention_stride = 64; +pub const hidden = 2304; +pub const feature_taps = 4; +pub const feature_row_bytes = feature_taps * hidden * 2; + +pub fn captureBytes(rows: usize) usize { + return rows * feature_row_bytes; +} +pub const query_width = 3072; +pub const kv_width = 1024; +pub const rel_width = 384; +pub const experts_per_token = 8; +pub const intermediate = 1152; +pub const vocabulary = 200058; +pub const message_entries = 48; +pub const block_slots = 4; +pub const conv_states = 4; +pub const visit_slots = 48; +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; + +pub fn globalSlots(capacity: usize) usize { + return std.mem.alignForward(usize, capacity, ap.tile_keys); +} + +pub fn globalStride(capacity: usize) usize { + return @max(@as(usize, ap.sliding_chunk / ap.tile_keys + 2), std.math.divCeil(usize, capacity, ap.global_chunk) catch unreachable); +} + +pub fn kvBytes(capacity: usize) usize { + const row_bytes = kv_width * 2; + return 40 * sliding_ring * 2 * row_bytes + 8 * globalSlots(capacity) * 2 * row_bytes; +} + +pub fn cacheBytes(capacity: usize) usize { + return kvBytes(capacity) + conv_bytes + taps_bytes + conv_bytes + vocabulary * 4; +} + +pub fn convWidth(state: usize) usize { + std.debug.assert(state < conv_states); + return conv_widths[state]; +} + +/// Values before a convolution state's rows in one slot's tightly sized layout. +pub fn convBase(state: usize, tap_rows: usize) usize { + var out: usize = 0; + for (0..state) |s| out += tap_rows * conv_widths[s]; + return out; +} + +pub fn convByteOffset(slot: usize, state: usize, rows_before: usize, tap_rows: usize) usize { + std.debug.assert(slot < visit_slots and rows_before <= tap_rows); + return (slot * tap_rows * conv_row_values + convBase(state, tap_rows) + rows_before * convWidth(state)) * 2; +} + +pub const Ref = @import("inkling2_metal_ref").Ref; + +/// Tap rows cover [start,start+rows); scratch rows carry a generation, unlike the prompt's stable last row. +pub const Tap = struct { buf: ?mtl.Buffer = null, off: usize = 0, start: u64 = 0, rows: usize = 0, gen: ?u64 = null }; + +/// Byte offset of a requested held feature range, rejecting stale and rejected rows. +pub fn featureOffset(t: Tap, start: u64, count: u32, generation: u64) !usize { + if (t.gen) |g| if (g != generation) return error.StaleInkling2Taps; + if (count == 0 or start < t.start) return error.Inkling2TapsNotHeld; + const delta = start - t.start; + const held: u64 = @intCast(t.rows); + if (delta >= held or count > held - delta) return error.Inkling2TapsNotHeld; + return t.off + @as(usize, @intCast(delta)) * feature_row_bytes; +} + +pub const Cache = struct { + kv: mtl.Buffer, + conv: mtl.Buffer, + taps: mtl.Buffer, + backup: mtl.Buffer, + logits: mtl.Buffer, + tap: Tap = .{}, + last_tap: ?mtl.Buffer = null, + key_at: [visit_slots]usize, + value_at: [visit_slots]usize, + rings: [visit_slots]u32, + globals: [visit_slots]bool, + capacity: usize, + len: usize = 0, + pending: ?usize = null, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn init(device: mtl.Device, capacity: usize, schedule: *const plan.Plan) !Cache { + if (capacity == 0 or capacity > 1048576 or schedule.n_visits != visit_slots) return error.Inkling2CacheShape; + var out: Cache = .{ + .kv = undefined, + .conv = undefined, + .taps = undefined, + .backup = undefined, + .logits = undefined, + .key_at = undefined, + .value_at = undefined, + .rings = undefined, + .globals = undefined, + .capacity = capacity, + }; + var at: usize = 0; + for (0..visit_slots) |slot| { + const global = schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global; + const ring_size = if (global) globalSlots(capacity) else sliding_ring; + out.globals[slot] = global; + out.rings[slot] = @intCast(ring_size); + out.key_at[slot] = at; + at += ring_size * kv_width * 2; + out.value_at[slot] = at; + at += ring_size * kv_width * 2; + } + std.debug.assert(at == kvBytes(capacity)); + out.kv = try device.buffer(@max(at, 16), mtl.ResourceOptions.private); + errdefer out.kv.deinit(); + out.conv = try device.buffer(conv_bytes, mtl.ResourceOptions.private); + errdefer out.conv.deinit(); + out.taps = try device.buffer(taps_bytes, mtl.ResourceOptions.private); + errdefer out.taps.deinit(); + out.backup = try device.buffer(conv_bytes, mtl.ResourceOptions.private); + errdefer out.backup.deinit(); + out.logits = try device.buffer(vocabulary * 4, mtl.ResourceOptions.shared); + errdefer out.logits.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.fill(out.conv, 0, conv_bytes, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache clear: {s}", .{msg}); + return error.GpuFailed; + } + return out; + } + + pub fn setResident(c: *Cache, hook: ?mtl.ResidencySet.Follow) void { + const buffers = [_]mtl.Buffer{ c.kv, c.conv, c.taps, c.backup, c.logits }; + if (c.follow) |f| { + for (buffers) |b| f.leave(f.ctx, b); + if (c.last_tap) |b| f.leave(f.ctx, b); + } + c.follow = hook; + if (hook) |f| { + for (buffers) |b| f.join(f.ctx, b); + if (c.last_tap) |b| f.join(f.ctx, b); + } + } + + pub fn ring(c: *const Cache, slot: usize) usize { + return c.rings[slot]; + } + + pub fn keys(c: *const Cache, slot: usize) Ref { + return .{ .buf = c.kv, .off = c.key_at[slot] }; + } + + pub fn values(c: *const Cache, slot: usize) Ref { + return .{ .buf = c.kv, .off = c.value_at[slot] }; + } + + pub fn history(c: *const Cache, slot: usize, state: usize) Ref { + return .{ .buf = c.conv, .off = convByteOffset(slot, state, 0, 3) }; + } + + 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) }; + } + + pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { + std.debug.assert(rows <= max_rows); + var layer = if (schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); + layer.ring = @intCast(c.ring(slot)); + return layer; + } + + /// Save all four pre-window three-tap histories before KV/conv speculation. + pub fn begin(c: *Cache, queue: mtl.Queue, rows: usize) !void { + if (c.pending != null or rows == 0 or rows > window_rows or c.len + rows > c.capacity) return error.Inkling2CacheTransaction; + try copyGpu(queue, c.conv, 0, c.backup, 0, conv_bytes, "begin"); + c.pending = rows; + } + + /// Commit accepted rows: staged taps select the new state; rejected KV positions are overwritten on replay. + pub fn commit(c: *Cache, queue: mtl.Queue, accepted: usize) !void { + const rows = c.pending orelse return error.Inkling2NoTransaction; + if (accepted > rows) return error.Inkling2CacheTransaction; + if (accepted < rows) { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + 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.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache commit: {s}", .{msg}); + return error.GpuFailed; + } + } + const start = c.len; + c.len += accepted; + if (c.tap.buf != null and c.tap.start == start) { + c.tap.rows = accepted; + } else c.tap = .{}; + c.pending = null; + } + + pub fn rollback(c: *Cache, queue: mtl.Queue) !void { + _ = c.pending orelse return error.Inkling2NoTransaction; + try copyGpu(queue, c.backup, 0, c.conv, 0, conv_bytes, "rollback"); + c.pending = null; + c.tap = .{}; + } + + pub fn deinit(c: *Cache) void { + c.setResident(null); + c.logits.deinit(); + if (c.last_tap) |b| b.deinit(); + c.backup.deinit(); + c.taps.deinit(); + c.conv.deinit(); + c.kv.deinit(); + c.* = undefined; + } +}; + +fn copyGpu(queue: mtl.Queue, from: mtl.Buffer, from_off: usize, to: mtl.Buffer, to_off: usize, bytes: usize, comptime what: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.copy(from, from_off, to, to_off, bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +pub const fields = [_][]const u8{ + "ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages", + "partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw", + "v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "rel_tab", "part_o", + "part_ml", "att", "attn_dense", "attn_conv", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", + "mlp_conv", "logits_all", +}; + +fn sizes(rows: usize) [fields.len]usize { + const r = rows; + const h = hidden; + const q = query_width; + const kv = kv_width; + const bf = 2; + const fp = 4; + return .{ + r * 4, r * 4, r * 4, max_segments * @sizeOf(ap.Seg), r * h * bf, r * h * bf, r * block_slots * h * bf, + r * h * bf, r * h * bf, r * message_entries * h * fp, r * h * fp, 3 * r * h * fp, 3 * r * h * fp, 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 * ap.extent * 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, + }; +} + +pub fn scratchBytes(rows: usize) usize { + var out: usize = 0; + for (sizes(rows)) |n| out += n; + return out; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + pos: mtl.Buffer, + seg_of: mtl.Buffer, + segs: mtl.Buffer, + p: mtl.Buffer, + prelude: mtl.Buffer, + blocks: mtl.Buffer, + bank0: mtl.Buffer, + bank1: mtl.Buffer, + messages: mtl.Buffer, + partial: mtl.Buffer, + ar: mtl.Buffer, + gated: mtl.Buffer, + mlp_ar: mtl.Buffer, + mlp_gated: mtl.Buffer, + q_norm: mtl.Buffer, + k_norm: mtl.Buffer, + v_norm: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + rel_raw: mtl.Buffer, + sink: mtl.Buffer, + gate: mtl.Buffer, + k_conv: mtl.Buffer, + v_conv: mtl.Buffer, + q_prep: mtl.Buffer, + rel_prep: mtl.Buffer, + rel_tab: mtl.Buffer, + part_o: mtl.Buffer, + part_ml: mtl.Buffer, + att: mtl.Buffer, + attn_dense: mtl.Buffer, + attn_conv: mtl.Buffer, + mlp_normed: mtl.Buffer, + route_ids: mtl.Buffer, + route_weights: mtl.Buffer, + gu: mtl.Buffer, + down: mtl.Buffer, + mlp_out: mtl.Buffer, + mlp_conv: mtl.Buffer, + logits_all: mtl.Buffer, + /// Opt-in DSpark features [row][tap][H], allocated by prepare_features. + taps: ?mtl.Buffer = null, + rows: usize, + + pub fn init(device: mtl.Device, rows: usize) !Scratch { + @setEvalBranchQuota(10_000); + if (rows == 0 or rows > max_rows) return error.Inkling2ScratchRows; + const ns = sizes(rows); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + s.taps = null; + s.rows = rows; + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| @field(s, f).deinit(); + if (s.taps) |b| b.deinit(); + s.* = undefined; + } +}; + +comptime { + if (sliding_ring != 1088 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); +} diff --git a/zig/src/inkling2_metal_host_test.zig b/zig/src/inkling2_metal_host_test.zig new file mode 100644 index 00000000000..eb76bab6406 --- /dev/null +++ b/zig/src/inkling2_metal_host_test.zig @@ -0,0 +1,6 @@ +//! Inkling 2 Mini Metal host tests rooted with the production engine sources. + +test { + _ = @import("families/inkling2/metal/host_test.zig"); + _ = @import("inkling2_native.zig"); +} diff --git a/zig/src/inkling2_native.zig b/zig/src/inkling2_native.zig new file mode 100644 index 00000000000..9101c4a644f --- /dev/null +++ b/zig/src/inkling2_native.zig @@ -0,0 +1,3 @@ +//! Module root for the Inkling 2 Mini native backend and its zig/src family dependencies. +pub const open = @import("native/inkling2.zig").open; +pub const refusal = @import("native/inkling2.zig").refusal; diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig new file mode 100644 index 00000000000..f32af564323 --- /dev/null +++ b/zig/src/native/inkling2.zig @@ -0,0 +1,212 @@ +//! Text-only Inkling 2 Mini on Metal, with exact prompt reuse and budgeted stream state. +const std = @import("std"); +const mtl = @import("metal"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const Model = @import("../families/inkling2/metal/model.zig").Model; +const st = @import("../families/inkling2/metal/state.zig"); +const backend = @import("../families/inkling2/metal/backend.zig"); +const dspark = @import("../families/inkling2/metal/dspark.zig"); + +const Host = struct { + gpa: std.mem.Allocator, + io: std.Io, + model: *Model, + metal: *backend.Metal, + drafter: ?*dspark.Drafter = null, + drafted: ?lanes.drafted.Drafted = null, + warm: mtl.keepalive.Target, + clock: lanes.backend.WallClock, + config: lanes.Config = undefined, + core: lanes.Engine, + host: api.LaneHost, + cache: ?api.prompt_cache.Store = null, + cache_cap: u64 = 0, + + fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.host.stop(); + if (h.cache) |*store| store.deinit(); + h.core.deinit(); + h.config.deinit(h.gpa); + if (h.drafted) |*d| d.deinit(); + if (h.drafter) |d| d.deinit(); + h.metal.deinit(); + h.model.deinit(); + h.gpa.destroy(h); + } +}; + +pub fn refusal(o: api.Open) ?[]const u8 { + if (o.vision != null or o.cfg_enabled or o.cfg_batched) return "inkling2_loop: this Metal engine serves text only; images and audio are unsupported"; + if (o.loops != null) return "inkling2_loop: the model has exactly three core passes; --loops cannot override them"; + if (o.mtp_drafts != null or o.mtp_confidence != null) return "inkling2_loop: use --drafter for the checkpoint's DSpark head; external draft controls remain unsupported"; + if (o.precision != null) return "inkling2_loop: the checkpoint's NVFP4, MXFP8 and BF16 arithmetic is fixed; serve without --precision"; + if (o.speed_up != null) return "inkling2_loop: this Metal engine serves one Mac; --speed-up is unsupported"; + if (o.learn != null or o.learn_conversations) return "inkling2_loop: learned disk states are not implemented; serve without --learn and --learn-conversations"; + if (o.prompt_cache_gib) |g| if (!std.math.isFinite(g) or g < 0 or g > 1024 * 1024) return "inkling2_loop: --prompt-cache-gib must be a finite, nonnegative budget"; + return null; +} + +fn drafterDirectory(o: api.Open) ?[]const u8 { + return if (o.drafts) o.drafter else null; +} + +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (refusal(o)) |why| { + problem.* = why; + return null; + } + if (try o.slideRefusal(a, "Macs")) |why| { + problem.* = why; + return null; + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const model = Model.load(gpa, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the native Inkling 2 Mini engine cannot load this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + const drafter_dir = drafterDirectory(o); + errdefer model.deinit(); + const drafter = if (drafter_dir) |dir| dspark.Drafter.init(gpa, io, model.device, model, dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "--drafter: Inkling 2 Mini DSpark cannot load {s} ({s})", .{ dir, @errorName(err) }); + model.deinit(); + return null; + } else null; + var ram: u64 = 0; + var len: usize = @sizeOf(u64); + if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; + const scratch: u64 = st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows); + const resident = model.checkpoint.residentBytes() + scratch + if (drafter) |d| d.fixedBytes() + dspark.Drafter.scoreBytes(0) else 0; + const budget = cacheBudget(ram, model.device.maxWorkingSet(), @import("sys").getenv("INKLING2_LOAD_LIMIT_GB"), resident) catch { + if (drafter) |d| d.deinit(); + model.deinit(); + problem.* = "INKLING2_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 75% of RAM"; + return null; + }; + const streams: u64 = @max(o.lanes, 1); + const draft_fixed = if (drafter != null) dspark.Drafter.streamBytes(0) + 127 * (dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0)) else 0; + const draft_token = if (drafter) |_| dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0) else 0; + const draft_shared_token = if (drafter) |_| dspark.Drafter.scoreBytes(1) - dspark.Drafter.scoreBytes(0) else 0; + const fits = longest(budget, model.config.text.max_context, streams, draft_fixed, draft_token, draft_shared_token); + const window: i64 = o.context orelse @intCast(fits); + if (window < 1 or window > fits) { + if (drafter) |d| d.deinit(); + model.deinit(); + return null; + } + std.log.info("inkling2_loop: {d:.1} GiB for stream and prompt state, context up to {d} tokens", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window }); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.io = io; + h.model = model; + h.drafter = drafter; + const reserved = if (drafter != null) streams * dspark.Drafter.streamBytes(@intCast(window)) + dspark.Drafter.scoreBytes(@intCast(window)) - dspark.Drafter.scoreBytes(0) else 0; + if (reserved > budget) return error.DSparkReservationExceeded; + h.metal = try backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget - reserved }); + errdefer h.metal.deinit(); + try h.metal.warm(); + h.drafted = null; + if (drafter) |d| { + try d.setContext(@intCast(window)); + h.drafted = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter()); + } + errdefer if (h.drafted) |*d| d.deinit(); + const facts = if (h.drafted) |*d| d.facts(h.metal.facts()) else h.metal.facts(); + h.config = try lanes.Config.init(gpa, facts, st.window_rows, st.window_rows - 1); + errdefer h.config.deinit(gpa); + h.clock = .{ .io = io }; + h.core = lanes.Engine.init(gpa, &h.config, if (h.drafted) |*d| d.backend() else h.metal.backend(), h.clock.clock()); + errdefer h.core.deinit(); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter_dir) |dir| .{ .kind = "DSpark", .name = o.drafter_name orelse dir } else null } }); + h.cache = null; + h.cache_cap = if (o.prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; + if (h.cache_cap > 0) { + const M = backend.Metal; + const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = st.prompt_rows, .min_prompt = 0 }; + h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = M.snapBytes, .save = M.snapSave, .restore = M.snapRestore, .drop = M.snapDrop } }, rules, @min(h.cache_cap, budget)); + h.host.cache = &h.cache.?; + h.host.info_.prompt_cache = true; + h.metal.room = .{ .ctx = h, .fit = fitCache }; + } + errdefer if (h.cache) |*store| store.deinit(); + h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; + try h.host.start(); + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} + +fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 { + var limit: u64 = @intFromFloat(@as(f64, @floatFromInt(ram)) * 0.75); + const value = std.mem.trim(u8, text orelse "", " \t"); + if (value.len > 0) { + const gb = std.fmt.parseFloat(f64, value) catch return error.BadLoadLimit; + if (!std.math.isFinite(gb) or gb <= 0) return error.BadLoadLimit; + const cap = @min(ram, working_set); + const bytes = gb * 1e9; + limit = if (bytes >= @as(f64, @floatFromInt(cap))) cap else @intFromFloat(bytes); + } + const margin: u64 = 2 << 30; + return if (limit > resident + margin) limit - resident - margin else 0; +} + +fn longest(bytes: u64, most: u32, streams: u64, draft_fixed: u64, draft_token: u64, draft_shared_token: u64) usize { + const one: u64 = st.cacheBytes(1) + streams * (draft_fixed + draft_token) + draft_shared_token; + if (one > bytes) return 0; + var lo: usize = 1; + var hi: usize = most; + while (lo < hi) { + const mid = lo + (hi - lo + 1) / 2; + const need = st.cacheBytes(mid) + streams * (draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); + if (need <= bytes) lo = mid else hi = mid - 1; + } + return lo; +} + +fn fitCache(ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + const store = if (h.cache) |*owned| owned else return; + store.budget = @min(h.cache_cap, bytes); + const Left = struct { + s: *const api.prompt_cache.Store, + pub fn fits(l: @This()) bool { + return l.s.held <= l.s.budget; + } + }; + _ = store.giveBack(restoring, prompt, Left{ .s = store }); +} + +test "Inkling native admission keeps DSpark opt-in and refuses learned modes" { + var o: api.Open = .{ .dir = "checkpoint", .model_type = "inkling2_loop" }; + try std.testing.expect(refusal(o) == null); + try std.testing.expect(drafterDirectory(o) == null); + o.drafter = "checkpoint"; + try std.testing.expectEqualStrings("checkpoint", drafterDirectory(o).?); + o.drafts = false; + try std.testing.expect(drafterDirectory(o) == null); + o.speed_up = "distributed"; + try std.testing.expect(refusal(o) != null); + o.speed_up = null; + o.learn = "learned"; + try std.testing.expect(refusal(o) != null); +} + +test "Inkling native load limit clamps before integer conversion" { + const gib: u64 = 1 << 30; + try std.testing.expectEqual(8_000_000_000 - 5 * gib, try cacheBudget(16 * gib, 14 * gib, "8", 3 * gib)); + try std.testing.expectEqual(9 * gib, try cacheBudget(16 * gib, 14 * gib, "1e30", 3 * gib)); + try std.testing.expectEqual(0, try cacheBudget(4 * gib, 4 * gib, null, 3 * gib)); + for ([_][]const u8{ "0", "-1", "nan", "inf", "bad" }) |text| { + try std.testing.expectError(error.BadLoadLimit, cacheBudget(16 * gib, 14 * gib, text, 3 * gib)); + } +} + +test "Inkling native longest context accounts target, streams and shared draft scores" { + const budget = st.cacheBytes(7) + 2 * (11 + 7 * 13) + 7 * 17; + try std.testing.expectEqual(@as(usize, 7), longest(budget, 8, 2, 11, 13, 17)); + try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1) - 1, 8, 1, 0, 0, 0)); + const per_token = dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0); + const conservative = dspark.Drafter.streamBytes(0) + 127 * per_token + 129 * per_token; + try std.testing.expect(conservative >= dspark.Drafter.streamBytes(129)); +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 499fda3bc07..b71dcade457 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -41,7 +41,6 @@ const affine_widths = blk: { }; /// Gemma 4's: MLX affine 2-6 or 8 bits in groups of 64, uniform or per module (oQ packs). const gemma4_widths: []const []const u8 = &.{ "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" }; - pub const families: []const api.Family = &.{ .{ .model_type = "kimi_k3", .formats = &.{"mxfp4"} }, .{ .model_type = "kimi_k31", .formats = &.{"mxfp4"} }, @@ -62,6 +61,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "gemma4_unified", .formats = gemma4_widths }, .{ .model_type = "step5_vl", .formats = &.{"mlx-q2g128"} }, .{ .model_type = "spark2_5", .formats = &.{ "bf16", "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" } }, + .{ .model_type = "inkling2_loop", .formats = &.{"nvfp4"} }, .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, .{ .model_type = "hy_v4_flash", .formats = &.{ "mlx-q4g64", "mlx-q8g64" } }, .{ .model_type = "qwen3", .formats = &.{"bf16"} }, @@ -69,7 +69,6 @@ pub const families: []const api.Family = &.{ .{ .model_type = "flint", .formats = &.{"mlx-q4g64"} }, .{ .model_type = "unlimited-ocr", .formats = &.{"bf16"} }, }; - /// Gemma 4 31B (gemma4) and 12B (gemma4_unified, its text model): one native family, gemma4.zig's host. fn isGemma4(model_type: []const u8) bool { return std.mem.eql(u8, model_type, "gemma4") or std.mem.eql(u8, model_type, "gemma4_unified"); @@ -166,6 +165,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (std.mem.eql(u8, o.model_type, "qwen3_5")) return @import("qwen35.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "step5_vl")) return @import("step5.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "spark2_5")) return @import("spark25.zig").open(a, gpa, io, o, problem); + if (std.mem.eql(u8, o.model_type, "inkling2_loop")) return @import("tensorfold").inkling2_native.open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "minimax_m3_vl")) return @import("minimax_m3.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "llama")) return @import("llama.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "flint")) return @import("flint.zig").open(a, gpa, io, o, problem); @@ -295,7 +295,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.kv8) return "--kv-cache fp8 keeps fp8 caches on CUDA; the Metal engines keep bf16: serve without it"; if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; - if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5) and Llama (a smaller Llama on the same tokenizer)"; + if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark) and Llama (a smaller Llama on the same tokenizer)"; const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 5a29cf3aef1..ae6bfd08603 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -31,6 +31,9 @@ pub const npy = @import("core/npy.zig"); pub const picture = @import("core/picture/picture.zig"); pub const ids_json = @import("core/ids_json.zig"); pub const lanes = @import("lanes"); +pub const inkling2_native = @import("inkling2_native.zig"); +pub const inkling2_metal_host = @import("families/inkling2/metal/metal.zig"); +pub const inkling2_dspark_host = @import("families/inkling2/metal/dspark_kernels.zig"); pub const segments = @import("core/segments.zig"); pub const prompt_tail = @import("core/prompt_tail.zig"); pub const row_projection = @import("core/row_projection.zig"); diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig new file mode 100644 index 00000000000..f60081c09ce --- /dev/null +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -0,0 +1,10 @@ +//! Every Inkling 2 Mini source control must apply once without a Metal compiler. + +test { + _ = @import("metal_inkling2_attention_controls.zig"); + _ = @import("metal_inkling2_glue_controls.zig"); + _ = @import("metal_inkling2_experts_controls.zig"); + _ = @import("metal_inkling2_loop_controls.zig"); + _ = @import("metal_inkling2_runtime_controls.zig"); + _ = @import("metal_inkling2_dspark_controls.zig"); +} From 11c3e3c4d98d0ae836f96c0a26431342d5ab51b3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:40:45 +0000 Subject: [PATCH 17/84] inkling2: document Mini fixture and reference provenance --- THIRD_PARTY_NOTICES.md | 24 +++++++ tools/zig/inkling2_fixtures.py | 64 ++++++++++++++++--- .../inkling2/fixtures/mini_config.json | 7 ++ .../inkling2/fixtures/mini_model_header.txt | 4 +- .../inkling2/fixtures/mini_mtp_header.txt | 2 +- 5 files changed, 89 insertions(+), 12 deletions(-) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c653a7a7531..0a8da983d22 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -554,6 +554,30 @@ those files. `tiny_config.json` and the tensor tables `0a57c72e4e5b68aafe1d983dbb62980344a5fcd7`, a randomly initialised model whose model card names that release as its base model and states no licence; no weights are included. `tools/zig/inkling2_fixtures.py` rebuilds all of these files. +## Inkling 2 Mini fixtures and loop references + +`mini_config.json`, `mini_model_header.txt` and `mini_mtp_header.txt` in +`zig/src/families/inkling2/fixtures/` come from the 2026-11-20 published snapshot of +[thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini), under the Apache License 2.0 +stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)). The config is the published `config.json` plus +its explicit `_fixture_provenance` annotation; the folded tables contain only metadata from the model and MTP safetensors +headers, no tensor data or weights. `tools/zig/inkling2_fixtures.py` rebuilds all three from the Mini release, or from its +extracted headers. None of the supplied config, generation config, quantization config, model card, tensor headers or +Mini specification records the release's full Hugging Face commit SHA. The fixtures therefore mark it unavailable rather +than deriving a revision from their digests. + +The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, +`loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and +`zig/kernels/cuda/inkling2/modelopt.cu` are independent TensorFold implementations of the supplied math-only Mini +specification. Its primary reference is huggingface/transformers PR #51050 at head `6173a2f6`: the Mini configuration and +forward pass in `models/inkling2_loop/modular_inkling2_loop.py` and `modeling_inkling2_loop.py`, with the temporary +NVFP4/MXFP8 expert dequantization in `core_model_loading.py` and the checkpoint mappings in `conversion_mapping.py`. +ModelOpt here names the checkpoint format and that Transformers arithmetic; no NVIDIA Model Optimizer source was used or +vendored. The specification also records Neywa-Labs/mlx-vlm at `fd6404fb` as its second reading of the loop and DSpark +implementation (`mlx_vlm/models/inkling2/` and `mlx_vlm/speculative/drafters/inkling2_dspark/`). Transformers is Apache-2.0; +mlx-vlm is MIT (see [`LICENSES/MIT.txt`](LICENSES/MIT.txt)). No reference source code is vendored. The supplied materials +give only these two abbreviated reference heads, not their full commit SHAs. + ## Inkling 2 attention kernels `zig/kernels/cuda/inkling2/attention.cu`, `zig/kernels/cuda/inkling2/prompt_attention.cu` and diff --git a/tools/zig/inkling2_fixtures.py b/tools/zig/inkling2_fixtures.py index 21af5106f97..e9dc31a617b 100644 --- a/tools/zig/inkling2_fixtures.py +++ b/tools/zig/inkling2_fixtures.py @@ -1,4 +1,4 @@ -"""Rebuild zig/src/families/inkling2/fixtures from the Inkling 2 Small release and tiny-random/inkling-2.""" +"""Rebuild zig/src/families/inkling2/fixtures from the Small, tiny-random and Mini checkpoint inputs.""" import argparse import hashlib import json @@ -10,6 +10,18 @@ FIXTURES = ROOT / "zig/src/families/inkling2/fixtures" RELEASE = "thinkingmachines/Inkling-2-Small@2ad1157016e1aac77b6ff1b770e7c05229403134" TINY = "tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7" +MINI_RELEASE = "thinkingmachines/Inkling-2-Mini" +MINI_PROVENANCE = { + "release": MINI_RELEASE, + "revision": None, + "revision_status": "full commit SHA absent from the supplied published metadata", + "published": "2026-11-20", + "license": "apache-2.0", +} +MINI_HEADER_PROVENANCE = ( + f"release={MINI_RELEASE} revision=unavailable-full-commit-SHA-absent-from-supplied-inputs " + "published=2026-11-20 license=apache-2.0" +) PINS = {"transformers": "5.20.0", "tokenizers": "0.23.3", "jinja2": "3.1.6"} MERGES = 1500 @@ -46,13 +58,35 @@ def dump(value, depth=0): def read_header(path): - """The tensors of a safetensors file as {name: (dtype tag, shape)}, read from its first bytes only.""" - with open(path, "rb") as f: - (length,) = struct.unpack(" Date: Sat, 21 Nov 2026 13:43:10 +0000 Subject: [PATCH 18/84] inkling2: normalize before CUDA query reductions --- zig/kernels/cuda/inkling2/loop_math.cu | 21 ++++--- zig/kernels/cuda/inkling2/ops.cu | 60 ++++++++++--------- .../contract_inkling2_loop_math_extra.zig | 26 ++++++-- zig/tests/cuda/contract_inkling2_ops_mix.zig | 27 ++++++++- 4 files changed, 92 insertions(+), 42 deletions(-) diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu index 64b5cfce451..5d1e5d04891 100644 --- a/zig/kernels/cuda/inkling2/loop_math.cu +++ b/zig/kernels/cuda/inkling2/loop_math.cu @@ -67,18 +67,25 @@ __device__ void ar(const ArArgs a) { : static_cast(a.partial)[row * a.C + c]; }; for (int j = 0; j < n; ++j) { - float v[1 + kMaxQueries] = {0.0f, 0.0f, 0.0f, 0.0f}; + float ss[1] = {0.0f}; for (int c = threadIdx.x; c < a.C; c += blockDim.x) { const float x = entry(j, c); - v[0] = __fmaf_rn(x, x, v[0]); - for (int q = 0; q < a.nq; ++q) v[1 + q] = __fmaf_rn(x, a.query[static_cast(q) * a.C + c], v[1 + q]); + ss[0] = __fmaf_rn(x, x, ss[0]); } - blockSums<1 + kMaxQueries>(v, sh); - if (threadIdx.x == 0) { - rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(v[0], static_cast(a.C)), a.eps)); + blockSums<1>(ss, sh); + if (threadIdx.x == 0) rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(a.C)), a.eps)); + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + const float normalized = __fmul_rn(entry(j, c), rr[j]); for (int q = 0; q < a.nq; ++q) - wts[q][j] = __fmul_rn(__fmul_rn(v[1 + q], rr[j]), queryScale(a.C)); + dots[q] = __fmaf_rn(a.query[static_cast(q) * a.C + c], normalized, dots[q]); } + blockSums(dots, sh); + if (threadIdx.x == 0) + for (int q = 0; q < a.nq; ++q) wts[q][j] = __fmul_rn(dots[q], queryScale(a.C)); } __syncthreads(); if (threadIdx.x < a.nq) { diff --git a/zig/kernels/cuda/inkling2/ops.cu b/zig/kernels/cuda/inkling2/ops.cu index 2e26fc6892c..648eb50686d 100644 --- a/zig/kernels/cuda/inkling2/ops.cu +++ b/zig/kernels/cuda/inkling2/ops.cu @@ -3,7 +3,6 @@ #include #include #include - #include "exl3_decode.cuh" namespace ink2o { @@ -97,10 +96,20 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { return a.partial_bf16 ? bf(reinterpret_cast(sp)[i]) : reinterpret_cast(sp)[i]; }; if (a.query) { - // every block's sums in one pass and one reduction: each sum adds in the order it did block by block - float v[kV]; + // Normalize each source before its query dot; both passes retain the declared strided/shuffle reduction. + float ss[kMaxBlocks + 1] = {}; + for (int c0 = 0; c0 < C; c0 += kMixCols) { + mixStage(a, row, c0, sb, sp); + for (int i = threadIdx.x; i < kMixCols && c0 + i < C; i += blockDim.x) { #pragma unroll - for (int i = 0; i < kV; ++i) v[i] = 0.0f; + for (int j = 0; j < kMaxBlocks + 1; ++j) + if (j < n) { const float x = entry(j, i); ss[j] += x * x; } + } + __syncthreads(); + } + blockSums(ss, sh); + if (threadIdx.x == 0) for (int j = 0; j < n; ++j) rr[j] = rsqrtf(ss[j] / C + 1e-6f); __syncthreads(); + float v[kV] = {}; for (int c0 = 0; c0 < C; c0 += kMixCols) { mixStage(a, row, c0, sb, sp); for (int i = threadIdx.x; i < kMixCols && c0 + i < C; i += blockDim.x) { @@ -109,26 +118,18 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { #pragma unroll for (int q = 0; q < kMaxQueries; ++q) qc[q] = q < a.nq ? a.query[static_cast(q) * C + c] : 0.0f; #pragma unroll - for (int j = 0; j < kMaxBlocks + 1; ++j) { - if (j < n) { - const float x = entry(j, i); - v[j * (1 + kMaxQueries)] += x * x; + for (int j = 0; j < kMaxBlocks + 1; ++j) if (j < n) { + const float normalized = entry(j, i) * rr[j]; #pragma unroll - for (int q = 0; q < kMaxQueries; ++q) - if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += x * qc[q]; - } + for (int q = 0; q < kMaxQueries; ++q) + if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += qc[q] * normalized; } } - __syncthreads(); // the next slice overwrites the staged one + __syncthreads(); } blockSums(v, sh); - if (threadIdx.x == 0) - for (int j = 0; j < n; ++j) { - const float r = rsqrtf(v[j * (1 + kMaxQueries)] / C + 1e-6f); - rr[j] = r; - for (int q = 0; q < a.nq; ++q) - wts[q][j] = v[j * (1 + kMaxQueries) + 1 + q] * r * rsqrtf(static_cast(C)); - } + if (threadIdx.x == 0) for (int j = 0; j < n; ++j) for (int q = 0; q < a.nq; ++q) wts[q][j] = + v[j * (1 + kMaxQueries) + 1 + q] * rsqrtf(static_cast(C)); __syncthreads(); if (threadIdx.x < a.nq) { float* l = wts[threadIdx.x]; @@ -199,18 +200,19 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix_rows(const MixArgs }; if (a.query) { for (int j = 0; j < n; ++j) { - float v[1 + kMaxQueries] = {0.0f, 0.0f, 0.0f, 0.0f}; + float ss[1] = {0.0f}; + for (int c = threadIdx.x; c < C; c += blockDim.x) { const float x = entry(j, c); ss[0] += x * x; } + blockSums<1>(ss, sh); if (threadIdx.x == 0) rr[j] = rsqrtf(ss[0] / C + 1e-6f); + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; for (int c = threadIdx.x; c < C; c += blockDim.x) { - const float x = entry(j, c); - v[0] += x * x; - for (int q = 0; q < a.nq; ++q) v[1 + q] += x * a.query[static_cast(q) * C + c]; - } - blockSums<1 + kMaxQueries>(v, sh); - const float r = rsqrtf(v[0] / C + 1e-6f); - if (threadIdx.x == 0) { - rr[j] = r; - for (int q = 0; q < a.nq; ++q) wts[q][j] = v[1 + q] * r * rsqrtf(static_cast(C)); + const float normalized = entry(j, c) * rr[j]; for (int q = 0; q < a.nq; ++q) + dots[q] += a.query[static_cast(q) * C + c] * normalized; } + blockSums(dots, sh); + if (threadIdx.x == 0) for (int q = 0; q < a.nq; ++q) wts[q][j] = dots[q] * rsqrtf(static_cast(C)); } __syncthreads(); if (threadIdx.x < a.nq) { diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig index 38e3b3d9a4c..49bd3ae650e 100644 --- a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig +++ b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig @@ -257,8 +257,8 @@ pub const Ar = struct { for (0..self.shape.k) |q| { var logits: [3]ref.Iv = undefined; for (0..3) |j| { - for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(ref.Iv.of(self.query[q * cols + i])); - logits[j] = s.sum(terms, depth(self.shape), scratch).mul(inv[j]).mul(queryScale(cols)); + for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]).mul(ref.Iv.of(self.query[q * cols + i])); + logits[j] = s.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); } softmax(&logits); for (0..cols) |i| { @@ -294,8 +294,7 @@ pub const Ar = struct { var m = -std.math.inf(f32); for (0..sources) |j| { const query = self.query[q * cols ..][0..cols]; - for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); - logits[j] = reduce(query, raw, 512) * invs[j] * scale(cols); + logits[j] = reduce(query, beta[j * cols ..][0..cols], 512) * scale(cols); m = cudaMax(m, logits[j]); } var den: f32 = 0; @@ -317,6 +316,25 @@ pub const Ar = struct { } }; +test "AR normalizes each FP32 query term before reduction and scales after its dot" { + const source = [_]f32{ + @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), + @bitCast(@as(u32, 0x40400001)), 0, + }; + const query = [_]f32{ + @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), + @bitCast(@as(u32, 0xc0000001)), 0, + }; + const inv: f32 = @bitCast(@as(u32, 0x3f800001)); + var normalized: [4]f32 = undefined; + for (&normalized, source) |*v, x| v.* = x * inv; + const dot = reduce(&query, &normalized, 512); + const old = reduce(&query, &source, 512) * inv * scale(source.len); + const scaled = dot * scale(source.len); + try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); + try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); +} + const round_shapes = [_]c.Shape{ .{ .rows = 1, .n = mini_h, .k = 1 }, .{ .rows = 2048, .n = 32, .k = 1 }, diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index 8c86f2e6ed8..b837c657b8b 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -187,8 +187,8 @@ pub const Mix = struct { for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(Iv.of(self.at(j, r, col))); rr[j] = ref.rms(s.sum(terms, d, scratch), C, 1e-6); for (0..q) |qi| { - for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(Iv.of(self.query[qi * C + col])); - w[qi][j] = s.sum(terms, d, scratch).mul(rr[j]).mul(root); + for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(rr[j]).mul(Iv.of(self.query[qi * C + col])); + w[qi][j] = s.sum(terms, d, scratch).mul(root); } } for (0..q) |qi| softmax(w[qi][0..n]); @@ -225,3 +225,26 @@ fn softmax(l: []Iv) void { } for (l, 0..) |*v, j| v.* = e[j].div(t); } + +test "mix normalizes each FP32 query term before reduction and scales after its dot" { + const source = [_]f32{ + @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), + @bitCast(@as(u32, 0x40400001)), 0, + }; + const query = [_]f32{ + @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), + @bitCast(@as(u32, 0xc0000001)), 0, + }; + const inv: f32 = @bitCast(@as(u32, 0x3f800001)); + var dot: f32 = 0; + var raw_dot: f32 = 0; + for (source, query) |x, q| { + dot = @mulAdd(f32, q, x * inv, dot); + raw_dot = @mulAdd(f32, q, x, raw_dot); + } + const inverse_root_h: f32 = 0.5; + const scaled = dot * inverse_root_h; + const old = raw_dot * inv * inverse_root_h; + try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); + try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); +} From 840a700d40334da2c28684cecaba05278438e5d4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:44:52 +0000 Subject: [PATCH 19/84] inkling2: control packed-expert contracts by phase --- zig/kernels/cuda/inkling2/experts.cu | 92 ------ zig/tests/cuda/contract_inkling2_experts.zig | 17 +- zig/tests/cuda/contract_inkling2_modelopt.zig | 265 +++++++++++++----- 3 files changed, 211 insertions(+), 163 deletions(-) diff --git a/zig/kernels/cuda/inkling2/experts.cu b/zig/kernels/cuda/inkling2/experts.cu index 622b8813562..cd0b81c7803 100644 --- a/zig/kernels/cuda/inkling2/experts.cu +++ b/zig/kernels/cuda/inkling2/experts.cu @@ -334,44 +334,6 @@ namespace ink2m { __device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } __device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } -__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } -__device__ __forceinline__ float warpSum(float v) { - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} - -template -__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; - for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); - __syncthreads(); - if (lane == 0) - for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; - __syncthreads(); - for (int i = 0; i < N; ++i) { - float t = lane < nw ? sh[i * 32 + lane] : 0.0f; - v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); - } -} - -struct GateUpArgs { - const uint16_t* x; // bf16 [rows, x_stride], pair p reads row p / slots - const uint8_t *codes, *scales; - const float *amax, *denominator; - const int* pick; // int32 [P] - uint16_t* out; // bf16 [P, N], the rounded softcapped SwiGLU - int x_stride, p, slots, n, k, experts, format; - float gate_cap, up_cap; -}; - -struct DownArgs { - const uint16_t* x; // bf16 [P, K], gateup's output - const uint8_t *codes, *scales; - const float *amax, *denominator; - const int* pick; - uint16_t* out; // bf16 [P, N], each selected expert's rounded output - int p, n, k, experts, format; -}; struct CombineArgs { const uint16_t* experts; // bf16 [rows * slots, H] @@ -387,65 +349,11 @@ struct TensorActArgs { int n; }; -__device__ __forceinline__ float e2m1(unsigned code) { - const float values[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; - const float v = values[code & 7u]; - return code & 8u ? -v : v; -} - -// The checkpoint's stored codes and scales become one bf16 weight, with no activation quantization. -__device__ __forceinline__ float weight(const uint8_t* codes, const uint8_t* scales, const float* amax, - const float* denominator, int e, int r, int c, int n, int k, int format) { - const int er = e * n + r; - if (format == 0) { - const uint8_t packed = codes[(size_t)er * (k / 2) + c / 2]; - const unsigned code = c & 1 ? packed >> 4 : packed & 15u; - const float scale = tf_common::e4m3f(scales[(size_t)er * (k / 16) + c / 16]); - const float phi = __fdiv_rn(bfr(amax[e]), bfr(denominator[0])); - return bfr(__fmul_rn(__fmul_rn(e2m1(code), scale), phi)); - } - const float value = tf_common::e4m3f(codes[(size_t)er * k + c]); - const float scale = ldexpf(1.0f, static_cast(scales[(size_t)er * (k / 32) + c / 32]) - 127); - return bfr(__fmul_rn(value, scale)); -} __device__ __forceinline__ float cap(float x, float c) { return c * tanhf(x / c); } } // namespace ink2m -// One (routed pair, intermediate unit): two stored NVFP4/MXFP8 rows and the rounded SwiGLU epilogue. -extern "C" __global__ void __launch_bounds__(128) tf_ink2moe_gateup(const ink2m::GateUpArgs a) { - __shared__ float sh[64]; - const int p = blockIdx.y, unit = blockIdx.x, e = a.pick[p]; - const uint16_t* x = a.x + static_cast(p / a.slots) * a.x_stride; - float v[2] = {0.0f, 0.0f}; - for (int c = threadIdx.x; c < a.k; c += blockDim.x) { - const float xv = ink2m::bf(x[c]); - const float g = ink2m::weight(a.codes, a.scales, a.amax, a.denominator, e, 2 * unit, c, 2 * a.n, a.k, a.format); - const float u = ink2m::weight(a.codes, a.scales, a.amax, a.denominator, e, 2 * unit + 1, c, 2 * a.n, a.k, a.format); - v[0] = __fmaf_rn(xv, g, v[0]); - v[1] = __fmaf_rn(xv, u, v[1]); - } - ink2m::blockSums<2>(v, sh); - if (threadIdx.x == 0) { - const float g = ink2m::cap(ink2m::bfr(v[0]), a.gate_cap); - const float u = ink2m::cap(ink2m::bfr(v[1]), a.up_cap); - a.out[(size_t)p * a.n + unit] = ink2m::tobf(g * (1.0f / (1.0f + expf(-ink2m::bfr(v[0])))) * u); - } -} - -// One (routed pair, hidden output): the down projection, rounded to bf16 before routing weights are applied. -extern "C" __global__ void __launch_bounds__(128) tf_ink2moe_down(const ink2m::DownArgs a) { - __shared__ float sh[32]; - const int p = blockIdx.y, row = blockIdx.x, e = a.pick[p]; - float v[1] = {0.0f}; - for (int c = threadIdx.x; c < a.k; c += blockDim.x) { - const float w = ink2m::weight(a.codes, a.scales, a.amax, a.denominator, e, row, c, a.n, a.k, a.format); - v[0] = __fmaf_rn(ink2m::bf(a.x[(size_t)p * a.k + c]), w, v[0]); - } - ink2m::blockSums<1>(v, sh); - if (threadIdx.x == 0) a.out[(size_t)p * a.n + row] = ink2m::tobf(v[0]); -} // Tensor-core gate/up rows are interleaved; keep the scalar baseline's softcapped SwiGLU arithmetic. extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_tensor_act(const ink2m::TensorActArgs a) { diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig index fe5fabbd9f0..73f89cff366 100644 --- a/zig/tests/cuda/contract_inkling2_experts.zig +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -19,7 +19,7 @@ pub const Set = struct { mk: ink.modelopt.Kernels = undefined, groups: [2]grouped.Group = undefined, projections: [4]grouped.Grouped = undefined, - moe: [7]modelopt.ModelOpt = undefined, + moe: [11]modelopt.ModelOpt = undefined, embeds: [2]ref.Gated(vision.Embed) = undefined, ropes: [2]ref.Gated(vision.Rope) = undefined, adds: [2]ref.Gated(vision.ScaleAdd) = undefined, @@ -37,16 +37,19 @@ pub const Set = struct { for (&set.groups, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .wrong_run = i == 1 }; const forms = [4]@import("contract_inkling2_experts_ref.zig").Form{ .rows, .rows, .wide, .wide }; for (&set.projections, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = &set.ek, .form = f, .fault = if (i == 1) .short else if (i == 3) .swapped else .none }; + const prompt = [11]bool{ false, true, false, true, false, true, false, false, false, true, false }; for (&set.moe, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.mk, - .format = if (i <= 2) .nvfp4 else .mxfp8, + .format = if (i < 4) .nvfp4 else .mxfp8, + .phase = if (prompt[i]) .prompt else .decode, .fault = switch (i) { - 0, 1 => .none, - 2, 3 => .wrong_combine, - 4 => .wrong_plan, - 5 => .wrong_up, - 6 => .wrong_act, + 0, 1, 4, 5 => .none, + 2, 6 => .wrong_combine, + 3, 9 => .wrong_prompt_up, + 7 => .wrong_plan, + 8 => .wrong_up, + 10 => .wrong_act, else => unreachable, }, }; diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig index 524accd67b3..6524ea8a3e2 100644 --- a/zig/tests/cuda/contract_inkling2_modelopt.zig +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -1,4 +1,4 @@ -//! Mini's packed NVFP4/MXFP8 expert pipeline on BF16 activations, against a sampled full-width host reference. +//! Mini's packed NVFP4/MXFP8 expert pipeline on BF16 activations, with bit-exact and float64 references. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -92,9 +92,9 @@ fn mxfp8Weight(code: u8, scale: u8) u16 { return c.toBf16(e4m3(code) * ue8m0(scale)); } -const Fault = enum { none, wrong_combine, wrong_plan, wrong_up, wrong_act }; - -fn rawSpec(format: mo.Format, fault: Fault) c.Spec { +const Phase = enum { decode, prompt }; +const Fault = enum { none, wrong_combine, wrong_plan, wrong_up, wrong_prompt_up, wrong_act }; +fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { const served = &[_]c.Shape{ .{ .rows = 1, .n = 2304, .k = 1152 }, .{ .rows = 16, .n = 2304, .k = 1152 }, @@ -103,32 +103,44 @@ fn rawSpec(format: mo.Format, fault: Fault) c.Spec { .{ .rows = 2048, .n = 2304, .k = 1152 }, }; const name = switch (fault) { - .none => if (format == .nvfp4) "inkling2 Mini NVFP4 w13/w2 tensor-core experts" else "inkling2 Mini MXFP8 w13/w2 tensor-core experts", + .none => if (format == .nvfp4) + (if (phase == .decode) "inkling2 Mini NVFP4 decode w13/w2 tensor-core experts" else "inkling2 Mini NVFP4 prompt w13/w2 tensor-core experts") + else + (if (phase == .decode) "inkling2 Mini MXFP8 decode w13/w2 tensor-core experts" else "inkling2 Mini MXFP8 prompt w13/w2 tensor-core experts"), .wrong_combine => if (format == .nvfp4) "control: inkling2 Mini NVFP4 int32 route IDs reinterpreted as FP32 weights" else "control: inkling2 Mini MXFP8 int32 route IDs reinterpreted as FP32 weights", .wrong_plan => "control: inkling2 Mini MXFP8 plan routes to the next expert IDs", - .wrong_up => "control: inkling2 Mini MXFP8 up projection clears the planted up-row code", + .wrong_up => "control: inkling2 Mini MXFP8 decode up projection clears the planted up-row code", + .wrong_prompt_up => if (format == .nvfp4) "control: inkling2 Mini NVFP4 prompt up projection clears the planted up-row code" else "control: inkling2 Mini MXFP8 prompt up projection clears the planted up-row code", .wrong_act => "control: inkling2 Mini MXFP8 activation uses gate cap eight", }; + const shapes = if (fault == .wrong_prompt_up or (fault == .none and phase == .prompt)) + served[3..] + else if (fault == .none) + served[0..3] + else + served[0..2]; return .{ .name = name, - .accum = .none, - .depth = noSums, - .out = .raw, + .accum = .f32, + .depth = depth, + .ops = 8, + .mids = 4, + .out = .bf16, .replaces = "host-dequantized BF16 tensor projections, softcapped SwiGLU, ascending FP32 routing", .nan = .{ .stated = "a non-finite BF16 input row propagates through its selected experts" }, .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{ .size = 32 } }, - .served = if (fault == .none) served else served[0..2], + .served = shapes, + .sums = .{ .f16 = 30, .bf16 = 30 }, }; } - -fn noSums(_: c.Shape) usize { - return 0; +fn depth(s: c.Shape) usize { + return s.n + s.k + 2 * core.attention_range.mma_step + slots; } - pub const ModelOpt = struct { rig: rig_.Rig, k: *const mo.Kernels, format: mo.Format, + phase: Phase, shape: c.Shape = undefined, fault: Fault = .none, arena: ?std.heap.ArenaAllocator = null, @@ -140,6 +152,7 @@ pub const ModelOpt = struct { pick: u64 = 0, weights: u64 = 0, out: u64 = 0, + stress: bool = false, scratch: u64 = 0, base_pick: u64 = 0, base_w13: u64 = 0, @@ -151,10 +164,9 @@ pub const ModelOpt = struct { base_down: u64 = 0, base_out: u64 = 0, baseline: ?Baseline = null, - msg: [200]u8 = undefined, pub fn kernel(self: *ModelOpt) g.Kernel { - return .{ .spec = rawSpec(self.format, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + return .{ .spec = rawSpec(self.format, self.phase, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; } const vt = g.hooks(ModelOpt); @@ -175,19 +187,36 @@ pub const ModelOpt = struct { self.rig.reset(); } - fn projectionRef(a: std.mem.Allocator, format: mo.Format, nexperts: usize, n: usize, k: usize, gate_up: bool) !struct { codes: []u8, scales: []u8, amax: []f32, den: [1]f32, ref: []u16 } { + fn projectionRef(a: std.mem.Allocator, format: mo.Format, nexperts: usize, n: usize, k: usize, gate_up: bool, fill: g.Fill) !struct { codes: []u8, scales: []u8, amax: []f32, den: [1]f32, ref: []u16 } { const values = nexperts * n * k; const raw = try a.alloc(u8, if (format == .nvfp4) values / 2 else values); const ref = try a.alloc(u16, values); const group: usize = if (format == .nvfp4) 16 else 32; const scales = try a.alloc(u8, values / group); const amax = try a.alloc(f32, if (format == .nvfp4) nexperts else 0); - if (format == .nvfp4) @memset(amax, test_amax); + if (format == .nvfp4) @memset(amax, if (fill == .stress) bf(test_den) else test_amax); const codes = [16]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; const fp8 = [16]u8{ 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8 }; const nv_scales = [4]u8{ 0x38, 0x30, 0x40, 0x34 }; // General controls stay finite; the dedicated scale-255 test covers +inf without masking faults as shared NaNs. const mx_scales = [4]u8{ 127, 128, 126, 129 }; + if (fill == .stress) { + for (0..nexperts) |e| for (0..n) |row| { + const base = (e * n + row) * k; + const scale_base = (e * n + row) * (k / group); + @memset(scales[scale_base..][0 .. k / group], if (format == .nvfp4) 0x38 else 127); + for (0..k) |col| { + // Mirrored +/-1 terms cancel to small integers; eight up rows retain a down-projection nudge. + const zero = gate_up and (row & 1) == 1 and row / 2 < 8 and col == k / 2 + 8; + const code: u8 = if (zero) 0 else if (format == .nvfp4) (if (col < k / 2) 2 else 10) else (if (col < k / 2) 0x38 else 0xb8); + if (format == .nvfp4) { + if ((col & 1) == 0) raw[base / 2 + col / 2] = code else raw[base / 2 + col / 2] |= code << 4; + } else raw[base + col] = code; + ref[base + col] = c.toBf16(if (zero) 0 else if (col < k / 2) 1 else -1); + } + }; + return .{ .codes = raw, .scales = scales, .amax = amax, .den = .{test_den}, .ref = ref }; + } for (0..nexperts) |e| for (0..n) |row| { const base = (e * n + row) * k; const scale_base = (e * n + row) * (k / group); @@ -220,9 +249,11 @@ pub const ModelOpt = struct { pub fn prepare(self: *ModelOpt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { _ = seed; + if (self.phase == .prompt and shape.rows < 32 and fill != .stress) return false; if (shape.n != 2304 or shape.k != 1152 or shape.rows == 0 or shape.rows > 2048) return false; self.drop(); self.shape = shape; + self.stress = fill == .stress; self.arena = std.heap.ArenaAllocator.init(self.rig.gpu.gpa); const a = self.arena.?.allocator(); const h = shape.n; @@ -236,13 +267,17 @@ pub const ModelOpt = struct { @memset(x[0..h], 0); x[0] = c.toBf16(1); // One gate/up activation and one down product make token zero a decode probe. if (fill == .nonfinite) x[0] = 0x7fc0; + if (fill == .stress) for (0..shape.rows) |row| for (0..h) |col| { + const v: f32 = 4 * @as(f32, @floatFromInt(1 + col % 64)); + x[row * h + col] = c.toBf16(v + (if (col >= h / 2 and col < h / 2 + 8) 4 else 0)); + }; self.x = x; - const p13 = try projectionRef(a, self.format, experts, 2 * m, h, true); - const p2 = try projectionRef(a, self.format, experts, h, m, false); + const p13 = try projectionRef(a, self.format, experts, 2 * m, h, true, fill); + const p2 = try projectionRef(a, self.format, experts, h, m, false, fill); self.w13 = p13.ref; self.w2 = p2.ref; self.dev_x = try self.rig.input(std.mem.sliceAsBytes(x)); - const dev13 = if (self.fault == .wrong_up) blk: { + const dev13 = if (self.fault == .wrong_up or self.fault == .wrong_prompt_up) blk: { const wrong = try a.dupe(u8, p13.codes); for (0..experts) |e| { const code_stride: usize = if (self.format == .nvfp4) 2 else 1; @@ -299,6 +334,7 @@ pub const ModelOpt = struct { pub fn run(self: *ModelOpt) !void { const route_weights = if (self.fault == .wrong_combine) self.pick else self.weights; const caps = if (self.fault == .wrong_act) ink.experts.Caps{ .gate = 8, .up = 25 } else ink.experts.Caps{ .gate = 4, .up = 25 }; + if (self.stress and self.phase == .prompt and self.shape.rows < 32) return self.runPrompt(caps); try mo.run(self.k, self.rig.s, self.l, caps, self.dev_x, self.shape.n, self.pick, route_weights, self.shape.rows, slots, self.out, self.scratch); } @@ -369,65 +405,166 @@ pub const ModelOpt = struct { ca.add(CombineArgs{ .experts = self.base_down, .pick = self.base_pick, .weights = self.weights, .out = self.base_out, .rows = @intCast(self.shape.rows), .h = @intCast(h), .slots = slots }); const outputs = self.shape.rows * h; try cuda.launch.launch(b.combine, .{ .grid = .{ .x = @intCast((outputs + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); - return self.rig.bytes(self.base_out, self.count()); + return self.rig.bytes(self.base_out, 2 * self.count()); + } + + fn promptProjection(self: *ModelOpt, x: u64, stride: usize, pair_slots: usize, p: mo.Projection, row0: i32, step: i32, plan: mo.Layout, out: u64, bound: usize) !void { + const outputs: usize = @intCast(if (step == 2) p.n / 2 else p.n); + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i32, @intCast(stride))); + a.add(@as(i32, @intCast(pair_slots))); + a.add(p.codes); + a.add(p.scales); + a.add(p.amax); + a.add(p.denominator); + a.add(@as(i64, experts)); + a.add(@as(i64, p.n)); + a.add(@as(i64, p.k)); + a.add(@as(i32, if (self.format == .nvfp4) 16 else 32)); + a.add(@as(i32, @backingInt(self.format))); + a.add(row0); + a.add(step); + a.add(@as(i32, @intCast(p.k / 32))); + a.add(@as(i32, @intCast(outputs / 32))); + for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(outputs))); + a.add(@as(i32, -1)); + const grid = (bound * outputs / 32 + 3) / 4; + try cuda.launch.launch(self.k.prompt, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + fn runPrompt(self: *ModelOpt, caps: ink.experts.Caps) !void { + const pairs = self.shape.rows * slots; + const b = mo.layout(self.scratch, self.shape.rows, slots, self.shape.n, self.shape.k); + const bound = (pairs + 63) / 64 + @min(pairs, experts); + var plan_args: cuda.Args = .{}; + for ([_]u64{ self.pick, b.items, b.members, b.item_count }) |v| plan_args.add(v); + for ([_]i32{ @intCast(self.shape.rows), slots, experts, 64 }) |v| plan_args.add(v); + try cuda.launch.launch(self.k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, self.rig.s, &plan_args); + try self.promptProjection(self.dev_x, self.shape.n, slots, self.l.w13, 0, 2, b, b.gate, bound); + try self.promptProjection(self.dev_x, self.shape.n, slots, self.l.w13, 1, 2, b, b.up, bound); + var aa: cuda.Args = .{}; + for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); + aa.add(@as(i32, @intCast(pairs * self.shape.k))); + aa.add(caps.gate); + aa.add(caps.up); + try cuda.launch.launch(self.k.act, .{ .grid = .{ .x = @intCast((pairs * self.shape.k + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &aa); + try self.promptProjection(b.act, self.shape.k, 0, self.l.w2, 0, 1, b, b.down, bound); + var ca: cuda.Args = .{}; + for ([_]u64{ self.pick, self.weights, b.down, self.out }) |v| ca.add(v); + for ([_]i32{ @intCast(self.shape.rows), @intCast(self.shape.n), slots, experts }) |v| ca.add(v); + const output_count = self.shape.rows * self.shape.n; + try cuda.launch.launch(self.k.combine, .{ .grid = .{ .x = @intCast((output_count + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); } - fn dot(x: []const u16, w: []const u16) f32 { - var sum: f32 = 0; - for (x, w) |xv, wv| sum += c.fromBf16(xv) * c.fromBf16(wv); - return sum; + pub fn count(self: *const ModelOpt) usize { + return self.shape.rows * self.shape.n; } - fn one(self: *const ModelOpt, a: std.mem.Allocator, token: usize, col: usize) !f32 { + fn roundTo(acc: c.Accum, v: f64) f64 { + return switch (acc) { + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => c.fromBf16(c.toBf16(@floatCast(v))), + .none => v, + }; + } + fn rounded(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); + } + fn activate(gate: f64, up: f64) f64 { + const gate_f32: f32 = @floatCast(gate); + const up_f32: f32 = @floatCast(up); + const gc = 4 * @as(f32, @floatCast(std.math.tanh(gate_f32 / 4))); + const uc = 25 * @as(f32, @floatCast(std.math.tanh(up_f32 / 25))); + const sigmoid: f32 = 1 / (1 + @exp(-gate_f32)); + return rounded(gc * sigmoid * uc); + } + + fn evaluate(self: *const ModelOpt, acc: c.Accum, order: g.Order, out: []f64, mag: ?[]f64) !void { + const a = self.rig.gpu.gpa; + const pairs = self.shape.rows * slots; const h = self.shape.n; const m = self.shape.k; - const x = self.x[token * h ..][0..h]; - const act = try a.alloc(u16, m); + const t = try a.alloc(f64, h); + defer a.free(t); + const act = try a.alloc(f64, pairs * m); defer a.free(act); - var total: f32 = 0; - for (0..experts) |e| { - for (0..slots) |slot| { - if (route(slot) != e) continue; - for (0..m) |j| { - const x13 = self.w13[e * 2 * m * h ..]; - const gate = bf(dot(x, x13[(2 * j) * h ..][0..h])); - const up = bf(dot(x, x13[(2 * j + 1) * h ..][0..h])); - const gc = 4 * @as(f32, @floatCast(std.math.tanh(gate / 4))); - const uc = 25 * @as(f32, @floatCast(std.math.tanh(up / 25))); - const sigmoid: f32 = 1 / (1 + @exp(-gate)); - act[j] = c.toBf16(gc * sigmoid * uc); + const upstream = try a.alloc(f64, pairs * m); + defer a.free(upstream); + const down = try a.alloc(f64, pairs * h); + defer a.free(down); + const down_mag = try a.alloc(f64, pairs * h); + defer a.free(down_mag); + for (0..if (self.stress) 1 else pairs) |p| { + const token = p / slots; + const e = route(p % slots); + const x = self.x[token * h ..][0..h]; + const w = self.w13[e * 2 * m * h ..]; + for (0..m) |j| { + var gabs: f64 = 0; + var uabs: f64 = 0; + for (0..h) |i| { + const xv = c.fromBf16(x[i]); + t[i] = xv * c.fromBf16(w[(2 * j) * h + i]); + gabs += @abs(t[i]); } - const x2 = self.w2[e * h * m + col * m ..][0..m]; - total += routeWeight(token, slot) * bf(dot(act, x2)); + const gate = rounded(core.contract.rows.sumIn(acc, order, t)); + for (0..h) |i| { + t[i] = c.fromBf16(x[i]) * c.fromBf16(w[(2 * j + 1) * h + i]); + uabs += @abs(t[i]); + } + const up = rounded(core.contract.rows.sumIn(acc, order, t)); + act[p * m + j] = activate(gate, up); + upstream[p * m + j] = 32 * gabs + 8 * uabs; } } - return bf(total); - } - - pub fn check(self: *ModelOpt, _: g.Gate) !?[]const u8 { - const a = self.rig.gpu.gpa; - const samples = [2][2]usize{ .{ 0, 0 }, .{ self.shape.rows - 1, self.shape.n - 1 } }; - for (samples) |at| { - const got_bytes = try self.rig.bytes(self.out + 2 * (at[0] * self.shape.n + at[1]), 2); - const got = c.fromBf16(std.mem.readInt(u16, got_bytes[0..2], .little)); - const want = try self.one(a, at[0], at[1]); - if (got == want or (std.math.isNan(want) and std.math.isNan(got))) continue; - // The token-zero one-product probe separates A2's roughly 1.4% error from reduction noise. - const tolerance = if (at[0] == 0) @abs(want) * 0.001 else @max(@as(f32, 0.02), @abs(want) * 0.02); - if (!std.math.isFinite(got) or @abs(got - want) > tolerance) { - return try std.fmt.bufPrint(&self.msg, "row {d} col {d}: got {d}, full-width host reference {d} (allowance {d})", .{ at[0], at[1], got, want, tolerance }); + if (self.stress) for (1..pairs) |p| { + @memcpy(act[p * m ..][0..m], act[0..m]); + @memcpy(upstream[p * m ..][0..m], upstream[0..m]); + }; + for (0..if (self.stress) 1 else pairs) |p| for (0..if (self.stress) 1 else h) |col| { + const w = self.w2[route(p % slots) * h * m + col * m ..][0..m]; + var abs: f64 = 0; + for (0..m) |j| { + t[j] = act[p * m + j] * c.fromBf16(w[j]); + abs += @abs(t[j]) + @abs(c.fromBf16(w[j])) * upstream[p * m + j]; } + down[p * h + col] = rounded(core.contract.rows.sumIn(acc, order, t[0..m])); + down_mag[p * h + col] = abs; + }; + if (self.stress) { + @memset(down, down[0]); + @memset(down_mag, down_mag[0]); } - return null; + for (0..self.shape.rows) |token| for (0..h) |col| { + var total: f64 = 0; + var abs: f64 = 0; + for (0..experts) |e| for (0..slots) |slot| { + if (route(slot) != e) continue; + const p = token * slots + slot; + const weight = routeWeight(token, slot); + total = roundTo(acc, total + roundTo(acc, weight * down[p * h + col])); + abs += @abs(weight) * down_mag[p * h + col]; + }; + out[token * h + col] = rounded(total); + if (mag) |v| v[token * h + col] = abs; + }; } - pub fn count(self: *const ModelOpt) usize { - return self.shape.rows * self.shape.n * 2; + pub fn reference(self: *ModelOpt, want: []f64, mag: []f64) !void { + if (self.x[0] == 0x7fc0) { + @memset(want, 0); + @memset(mag, 0); + @memset(want[0..self.shape.n], std.math.nan(f64)); + return; + } + return self.evaluate(.none, .sequential, want, mag); } - pub fn reference(_: *ModelOpt, want: []f64, mag: []f64) !void { - @memset(want, 0); - @memset(mag, 0); + pub fn simulate(self: *ModelOpt, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.evaluate(acc, order, out, null); } }; From 5acab1fc5c3ade92de9feb717a221f9a7154dcef Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:45:24 +0000 Subject: [PATCH 20/84] inkling2: fix native Metal Mini admission and serving --- zig/src/families/inkling2/metal/host_test.zig | 1 + .../families/inkling2/metal/serving_test.zig | 263 ++++++++++++++++++ zig/src/native/inkling2.zig | 18 +- zig/src/native/metal.zig | 2 +- 4 files changed, 281 insertions(+), 3 deletions(-) create mode 100644 zig/src/families/inkling2/metal/serving_test.zig diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index e9e1998f151..db8bce1b868 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -13,4 +13,5 @@ test { _ = @import("dspark_state.zig"); _ = @import("dspark.zig"); _ = @import("backend.zig"); + _ = @import("serving_test.zig"); } diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig new file mode 100644 index 00000000000..d24f8136269 --- /dev/null +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -0,0 +1,263 @@ +//! Real-checkpoint Mini serving: serial target references, cache restore, DSpark and exact transactions. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const api = @import("engine_api"); +const native = @import("../../../native/inkling2.zig"); +const Model = @import("model.zig").Model; +const backend = @import("backend.zig"); +const st = @import("state.zig"); +const native_metal = @import("../../../native/metal.zig"); + +const gpa = std.testing.allocator; +const io = std.testing.io; +const context = 256; +const made = 24; +const taps = [_]u32{ 5, 23, 41, 48 }; + +fn checkpoint() ![]const u8 { + return @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse error.SkipZigTest; +} + +fn prompt(comptime n: usize, salt: u32) [n]u32 { + var ids: [n]u32 = undefined; + for (&ids, 0..) |*id, i| id.* = @intCast(1000 + (i * 37 + @as(usize, salt) * 101) % 20000); + return ids; +} + +const TapSink = struct { + bytes: [st.feature_row_bytes]u8 = @splat(0), + seen: usize = 0, + + fn take(ptr: *anyopaque, s: *lanes.Stream, f: lanes.backend.Features, start: u64) !void { + const self: *TapSink = @ptrCast(@alignCast(ptr)); + try std.testing.expectEqual(lanes.backend.Features.Space.device, f.space); + try std.testing.expectEqual(lanes.backend.Features.Dtype.bf16, f.dtype); + try std.testing.expectEqual(@as(u32, st.feature_row_bytes), f.row_bytes); + try std.testing.expect(f.rows > 0); + if (start + f.rows != s.prompt_len) return; + const buf: mtl.Buffer = .{ .id = @ptrFromInt(f.buffer) }; + const bytes = buf.slice(u8, @intCast(f.offset + f.rows * f.row_bytes)); + const last = bytes[@intCast(f.offset + (f.rows - 1) * f.row_bytes)..][0..st.feature_row_bytes]; + @memcpy(&self.bytes, last); + self.seen += 1; + } +}; + +const Reference = struct { + tokens: [made]u32, + first: lanes.LogprobRow, + tap: [st.feature_row_bytes]u8, +}; + +fn serial(b: lanes.backend.Backend, ids: []const u32) !Reference { + var sink: TapSink = .{}; + var s = try lanes.Stream.init(gpa, .{ .id = "host-reference", .prompt = ids, .max_new = made, .drafts = false, .logprobs = 3 }); + defer s.deinit(gpa); + try b.vtable.prefill_features.?(b.ptr, &s, &taps, .{ .ptr = &sink, .take = TapSink.take }); + defer b.release(&s); + try std.testing.expectEqual(@as(usize, 1), sink.seen); + const first = try b.firstRow(&s); + var out: Reference = .{ .tokens = undefined, .first = first, .tap = sink.bytes }; + var next = try b.read(try b.first(&s, ids.len)); + out.tokens[0] = next; + try std.testing.expectEqual(next, first.token); + for (1..made) |i| { + next = try b.read(try b.queue(&s, .{ .value = next }, ids.len + i)); + out.tokens[i] = next; + } + return out; +} + +fn withReference(dir: []const u8, ids: []const u32, extended: ?[]const u32) !struct { first: Reference, second: ?Reference } { + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = 2 * st.cacheBytes(context) }); + defer target.deinit(); + try target.warm(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + const first = try serial(b, ids); + const repeated = try serial(b, ids); + try std.testing.expectEqualSlices(u8, &first.tap, &repeated.tap); + try std.testing.expectEqualSlices(u32, &first.tokens, &repeated.tokens); + try expectFirstRow(first.first, repeated.first); + const second = if (extended) |p| try serial(b, p) else null; + return .{ .first = first, .second = second }; +} + +fn expectFirstRow(want: lanes.LogprobRow, got: lanes.LogprobRow) !void { + try std.testing.expectEqual(want.token, got.token); + try std.testing.expectEqual(@as(u32, @bitCast(want.logprob)), @as(u32, @bitCast(got.logprob))); + try std.testing.expectEqual(want.count, got.count); + try std.testing.expectEqualSlices(u32, want.ids[0..want.count], got.ids[0..got.count]); + try std.testing.expectEqualSlices(f32, want.logprobs[0..want.count], got.logprobs[0..got.count]); +} + +const Reply = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + rows: std.ArrayList(lanes.LogprobRow) = .empty, + cached: ?u32 = null, + drafted: u64 = 0, + accepted: u64 = 0, + done: ?api.Reason = null, + + fn event(ptr: *anyopaque, _: api.Id, item: *const api.Event) void { + const self: *Reply = @ptrCast(@alignCast(ptr)); + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + switch (item.*) { + .tokens => |ids| self.tokens.appendSlice(gpa, ids) catch {}, + .logprobs => |rows| self.rows.appendSlice(gpa, rows) catch {}, + .prefilled => |n| self.cached = n, + .finished => |f| { + self.done = f.reason; + self.drafted = f.stats.drafted; + self.accepted = f.stats.accepted; + }, + else => {}, + } + } + + fn wait(self: *Reply) !api.Reason { + for (0..600_000) |_| { + self.mutex.lockUncancelable(io); + const done = self.done; + self.mutex.unlock(io); + if (done) |reason| return reason; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.Timeout; + } + + fn deinit(self: *Reply) void { + self.tokens.deinit(gpa); + self.rows.deinit(gpa); + } +}; + +fn serve(native_opened: api.Opened, id: api.Id, request: *const api.Request) !Reply { + var reply: Reply = .{}; + errdefer reply.deinit(); + try native_opened.engine.submit(id, request, .{ .ctx = &reply, .event = Reply.event }); + try std.testing.expectEqual(api.Reason.length, try reply.wait()); + try std.testing.expectEqual(@as(usize, made), reply.tokens.items.len); + return reply; +} + +fn opened(dir: []const u8, drafter: ?[]const u8, cache_gib: ?f64) !api.Opened { + var why: []const u8 = ""; + const result = try native.open(gpa, gpa, io, .{ + .dir = dir, + .model_type = "inkling2_loop", + .context = context, + .lanes = 1, + .drafts = drafter != null, + .drafter = drafter, + .prompt_cache_gib = cache_gib, + .decode_share = 0.5, + }, &why); + if (result == null) { + std.debug.print("Mini Metal open refused: {s}\n", .{why}); + return error.MiniMetalOpenRefused; + } + return result.?; +} + +fn expectTokens(want: *const Reference, got: *const Reply) !void { + try std.testing.expectEqualSlices(u32, &want.tokens, got.tokens.items); + try std.testing.expect(got.rows.items.len >= 1); + try expectFirstRow(want.first, got.rows.items[0]); +} + +fn transactions(dir: []const u8, ids: []const u32, want: *const Reference) !void { + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = st.cacheBytes(context) }); + defer target.deinit(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + var s = try lanes.Stream.init(gpa, .{ .id = "transactions", .prompt = ids, .max_new = made, .drafts = false, .logprobs = 3 }); + defer s.deinit(gpa); + try b.prefill(&s); + defer b.release(&s); + + const full_drafts = want.tokens[1..8]; + const full_positions = [_]u64{ ids.len + 1, ids.len + 2, ids.len + 3, ids.len + 4, ids.len + 5, ids.len + 6, ids.len + 7, ids.len + 8 }; + const full = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[0], .held = 0, .tokens = full_drafts, .parents = null, .positions = &full_positions }}; + var sampled: [8]u32 = undefined; + var echo: [7]u32 = undefined; + var full_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try b.verify(&full, &full_out); + try std.testing.expectEqualSlices(u32, want.tokens[1..9], &sampled); + try std.testing.expectEqualSlices(u32, full_drafts, &echo); + try b.keep(&full, &.{&.{ 0, 1, 2, 3, 4, 5, 6, 7 }}); + + var partial_drafts = want.tokens[9..16].*; + partial_drafts[6] = (want.tokens[15] + 1) % model.config.text.unpadded_vocab; + const partial_positions = [_]u64{ ids.len + 9, ids.len + 10, ids.len + 11, ids.len + 12, ids.len + 13, ids.len + 14, ids.len + 15, ids.len + 16 }; + const partial = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[8], .held = 0, .tokens = &partial_drafts, .parents = null, .positions = &partial_positions }}; + const path = [_]u32{ 0, 1, 2, 3, 4, 5, 6 }; + var partial_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try b.verify(&partial, &partial_out); + try std.testing.expectEqualSlices(u32, want.tokens[9..17], &sampled); + try b.keep(&partial, &.{&path}); + const next = try b.read(try b.queue(&s, .{ .value = want.tokens[15] }, ids.len + 16)); + try std.testing.expectEqual(want.tokens[16], next); +} + +test "Mini Metal serving matches the host reference token for token" { + const dir = try checkpoint(); + const ids = prompt(64, 1); + var turn: [80]u32 = undefined; + @memcpy(turn[0..64], &ids); + @memcpy(turn[64..], &prompt(16, 2)); + const refs = try withReference(dir, &ids, &turn); + var tap_nonzero = false; + for (refs.first.tap) |byte| tap_nonzero = tap_nonzero or byte != 0; + try std.testing.expect(tap_nonzero); + + const opened_once = try opened(dir, null, 1); + defer opened_once.close(opened_once.ctx); + try std.testing.expectEqual(@as(?f64, 0.5), opened_once.engine.info().decode_share); + const keepalive = opened_once.engine.keepaliveTarget() orelse return error.MissingMiniKeepalive; + keepalive.tick(keepalive.ctx); + const first = try serve(opened_once, 1, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer first.deinit(); + try expectTokens(&refs.first, &first); + const restored = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer restored.deinit(); + try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); + try expectTokens(&refs.second.?, &restored); +} + +test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back exactly" { + const dir = try checkpoint(); + const drafter = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + const ids = prompt(64, 3); + const refs = try withReference(dir, &ids, null); + try transactions(dir, &ids, &refs.first); + + const opened_once = try opened(dir, drafter, 0); + defer opened_once.close(opened_once.ctx); + const plain = try serve(opened_once, 10, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3 }); + defer plain.deinit(); + try expectTokens(&refs.first, &plain); + try std.testing.expectEqual(@as(u64, 0), plain.drafted); + const drafted = try serve(opened_once, 11, &.{ .prompt = &ids, .max_tokens = made, .drafts = true, .logprobs = 3 }); + defer drafted.deinit(); + try expectTokens(&refs.first, &drafted); + try std.testing.expect(drafted.drafted > 0); + try std.testing.expect(drafted.accepted > 0); +} + +test "Metal capabilities: inkling2_loop serves the checkpoint's ModelOpt NVFP4 weights" { + var found = false; + for (native_metal.families) |family| if (std.mem.eql(u8, family.model_type, "inkling2_loop")) { + found = true; + try std.testing.expectEqual(@as(usize, 1), family.formats.len); + try std.testing.expectEqualStrings("modelopt-nvfp4", family.formats[0]); + }; + try std.testing.expect(found); +} diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index f32af564323..9a09ef9f40b 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -52,6 +52,12 @@ fn drafterDirectory(o: api.Open) ?[]const u8 { return if (o.drafts) o.drafter else null; } +fn contextProblem(window: i64, fits: usize) ?[]const u8 { + if (window < 1) return "inkling2_loop: --context must be at least one token, and the selected context must fit the Metal state budget"; + if (window > fits) return "inkling2_loop: --context exceeds the largest window this Mac can afford beside the checkpoint and DSpark state"; + return null; +} + pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { if (refusal(o)) |why| { problem.* = why; @@ -74,6 +80,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope model.deinit(); return null; } else null; + errdefer if (drafter) |d| d.deinit(); var ram: u64 = 0; var len: usize = @sizeOf(u64); if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; @@ -91,9 +98,10 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope const draft_shared_token = if (drafter) |_| dspark.Drafter.scoreBytes(1) - dspark.Drafter.scoreBytes(0) else 0; const fits = longest(budget, model.config.text.max_context, streams, draft_fixed, draft_token, draft_shared_token); const window: i64 = o.context orelse @intCast(fits); - if (window < 1 or window > fits) { + if (contextProblem(window, fits)) |why| { if (drafter) |d| d.deinit(); model.deinit(); + problem.* = why; return null; } std.log.info("inkling2_loop: {d:.1} GiB for stream and prompt state, context up to {d} tokens", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window }); @@ -109,9 +117,11 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope errdefer h.metal.deinit(); try h.metal.warm(); h.drafted = null; + h.warm = .{ .queue = model.queue }; if (drafter) |d| { try d.setContext(@intCast(window)); h.drafted = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter()); + h.drafted.?.first_rows = true; } errdefer if (h.drafted) |*d| d.deinit(); const facts = if (h.drafted) |*d| d.facts(h.metal.facts()) else h.metal.facts(); @@ -120,7 +130,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.clock = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.config, if (h.drafted) |*d| d.backend() else h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter_dir) |dir| .{ .kind = "DSpark", .name = o.drafter_name orelse dir } else null } }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .decode_share = o.decode_share, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter_dir) |dir| .{ .kind = "DSpark", .name = o.drafter_name orelse dir } else null } }); h.cache = null; h.cache_cap = if (o.prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; if (h.cache_cap > 0) { @@ -190,6 +200,10 @@ test "Inkling native admission keeps DSpark opt-in and refuses learned modes" { o.speed_up = null; o.learn = "learned"; try std.testing.expect(refusal(o) != null); + try std.testing.expect(contextProblem(0, 10) != null); + try std.testing.expect(contextProblem(-1, 10) != null); + try std.testing.expect(contextProblem(11, 10) != null); + try std.testing.expect(contextProblem(10, 10) == null); } test "Inkling native load limit clamps before integer conversion" { diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index b71dcade457..13bd6c0f744 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -61,7 +61,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "gemma4_unified", .formats = gemma4_widths }, .{ .model_type = "step5_vl", .formats = &.{"mlx-q2g128"} }, .{ .model_type = "spark2_5", .formats = &.{ "bf16", "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" } }, - .{ .model_type = "inkling2_loop", .formats = &.{"nvfp4"} }, + .{ .model_type = "inkling2_loop", .formats = &.{"modelopt-nvfp4"} }, .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, .{ .model_type = "hy_v4_flash", .formats = &.{ "mlx-q4g64", "mlx-q8g64" } }, .{ .model_type = "qwen3", .formats = &.{"bf16"} }, From 0577913ab098be3e897d7263e5201bdc0079c69f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:47:07 +0000 Subject: [PATCH 21/84] inkling2: prove Mini CUDA serving equivalence --- CHANGELOG.md | 2 +- zig/tests/cuda/inkling2_serving_tests.zig | 287 ++++++++++++++++++++++ zig/tests/cuda/main.zig | 1 + zig/tests/cuda/main_usage.zig | 1 + 4 files changed, 290 insertions(+), 1 deletion(-) create mode 100644 zig/tests/cuda/inkling2_serving_tests.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 890b7ec31fb..d5ef2efba05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -146,7 +146,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds each 512-key chunk's two pages once instead of reading the page table at every 32-key step, with every token and cache row unchanged (#3180, part of #1293). Thanks to @CodingEmil. - Nemotron 3.5 Lightning on HIP: the MTP head file is read at the width its own metadata states, so it drafts beside an oQ checkpoint of any width, and a head at a width the launches do not read is refused by name (#3251, part of #3061). Thanks to @gilby. -- Inkling 2 Mini (`inkling2_loop`) on one CUDA rank: the 48-visit text loop now runs its cross-pass messages, rank-64 gates and separate sliding Q/K/V inputs, with per-visit KV and convolution state, prompt snapshots and exact rollback. Routed experts decode stored NVFP4 and MXFP8 weights to bf16 with the reference's rounding and ascending-expert FP32 accumulation; activation quantization is not used. TP, vision and DSpark loading remain refused by name. +- Inkling 2 Mini (`inkling2_loop`) now serves natively on one CUDA rank and on Metal. CUDA runs the 48-visit text loop's cross-pass messages, rank-64 gates and separate sliding Q/K/V inputs with per-visit KV and convolution state, prompt snapshots and exact rollback; routed experts decode stored NVFP4 and MXFP8 weights to bf16 with the reference's rounding and ascending-expert FP32 accumulation, without activation quantization. Metal's default serving path stays unchanged, while opt-in DSpark drafting preserves target tokens and rolls back exactly. CUDA TP, vision and DSpark loading remain refused by name. - Inkling 2 on CUDA: the family's grouped-expert launches match main's `tf_exl3_grouped_2` bit for bit under the kernel contract, and the vision tower's kernels pass gates 1 to 4 (refs #3476). Thanks to @ajensenwaud. diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig new file mode 100644 index 00000000000..60491f210f8 --- /dev/null +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -0,0 +1,287 @@ +//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots, admission and copied drafts. +const std = @import("std"); +const lanes = @import("lanes"); +const mini = @import("inkling2"); +const check = @import("check.zig"); + +const native = mini.native; +const Backend = @TypeOf(@as(native.Owned, undefined).backend); +const Gpu = check.Gpu; +const sampled: lanes.Sampling = .{ .seed = 37, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; + +const Trace = struct { + ids: []u32, + logits: []f32, + cached: u32, + failed: bool, + + fn deinit(t: *Trace, gpa: std.mem.Allocator) void { + gpa.free(t.ids); + gpa.free(t.logits); + } +}; + +fn target(loaded: *native.Loaded) *Backend { + return &loaded.target.backend; +} + +fn download(loaded: *native.Loaded, out: []f32) !void { + const b = target(loaded); + try b.s.synchronize(); + try b.m.logits.download(0, std.mem.sliceAsBytes(out)); +} + +/// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. +fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.Reuse) !Trace { + const t = target(loaded); + const v = t.m.w.c.text.vocab; + const unpadded = t.m.w.c.text.unpadded_vocab; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-trace", .prompt = prompt, .max_new = @intCast(n), .sampling = sampling, .reuse = reuse }); + defer s.deinit(gpu.gpa); + const b = loaded.backend; + defer b.release(&s); + const ids = try gpu.gpa.alloc(u32, n); + errdefer gpu.gpa.free(ids); + const logits = try gpu.gpa.alloc(f32, n * v); + errdefer gpu.gpa.free(logits); + try b.prefill(&s); + try download(loaded, logits[0..v]); + var handle: ?u64 = try b.first(&s, prompt.len); + for (0..n) |i| { + ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..unpadded], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); + if (i + 1 < n) { + handle = try b.queue(&s, .{ .value = ids[i] }, prompt.len + i + 1); + try download(loaded, logits[(i + 1) * v ..][0..v]); + } + } + return .{ .ids = ids, .logits = logits, .cached = s.cached, .failed = s.reuse_failed }; +} + +fn sameTrace(a: *const Trace, b: *const Trace) !void { + if (!std.mem.eql(u32, a.ids, b.ids)) return error.MiniServingTokenMismatch; + if (!std.mem.eql(u8, std.mem.sliceAsBytes(a.logits), std.mem.sliceAsBytes(b.logits))) return error.MiniServingLogitMismatch; +} + +fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var device = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); + defer device.deinit(gpu.gpa); + var host = try trace(gpu, loaded, prompt, sampling, 12, true, .{}); + defer host.deinit(gpu.gpa); + sameTrace(&device, &host) catch |err| { + std.debug.print("RESULT mini-serving host-reference case={d} mismatch={s}\n", .{ case, @errorName(err) }); + return err; + }; + } +} + +/// Save one complete state at `cut`, restore it through the genuine prompt-reuse hook and rerun the suffix. +fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling, fresh: *const Trace) !void { + const Saved = @TypeOf(loaded.target.model).Saved; + const Keeper = struct { + b: *Backend, + saved: ?*Saved = null, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved = k.b.saveState(s, mark) catch null; + } + }; + const t = target(loaded); + const saved = snapshot: { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-snapshot", .prompt = prompt, .max_new = 1, .reuse = .{ .marks = &.{cut} } }); + defer s.deinit(gpu.gpa); + const b = loaded.backend; + defer b.release(&s); + var keeper: Keeper = .{ .b = t }; + s.reuse.hook = .{ .ptr = &keeper, .at = Keeper.at }; + try b.prefill(&s); + break :snapshot keeper.saved orelse return error.MiniSnapshotNotSaved; + }; + defer t.dropState(saved); + var resumed = try trace(gpu, loaded, prompt, sampling, fresh.ids.len, false, .{ .saved = saved, .at = cut }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != cut or resumed.failed) return error.MiniSnapshotNotRestored; + try sameTrace(fresh, &resumed); +} + +fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var fresh = try trace(gpu, loaded, prompt, sampling, 8, false, .{}); + defer fresh.deinit(gpu.gpa); + const cuts: []const u32 = if (case == 0) &.{ 17, 2048 } else &.{ 2049, @intCast(prompt.len - 1) }; + for (cuts) |cut| try resumedAt(gpu, loaded, prompt, cut, sampling, &fresh); + } +} + +fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.Proposer) !void { + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + const clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + if (proposer) |p| s.proposer = p; + try e.addStream(s); + while (!s.finished) try e.step(); + if (s.reason != .length) return error.MiniServingDidNotFinish; +} + +fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) !void { + var plain_a = try trace(gpu, loaded, a, null, 10, false, .{}); + defer plain_a.deinit(gpu.gpa); + var plain_b = try trace(gpu, loaded, b, sampled, 10, false, .{}); + defer plain_b.deinit(gpu.gpa); + var first = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-first", .prompt = a, .max_new = 10 }); + defer first.deinit(gpu.gpa); + var second = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-second", .prompt = b, .max_new = 10, .sampling = sampled }); + defer second.deinit(gpu.gpa); + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + const clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + if (!native.fits(loaded.ctx, @intCast(a.len), first.max_new)) return error.MiniUnexpectedFreeSlot; + try e.addStream(&first); + if (native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniBusyAdmissionRefused; + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&second)); + while (!first.finished) try e.step(); + try std.testing.expectEqual(lanes.Reason.length, first.reason); + if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; + if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSlotNotReleased; + try e.addStream(&second); + while (!second.finished) try e.step(); + try std.testing.expectEqual(lanes.Reason.length, second.reason); + if (!std.mem.eql(u32, second.emitted(), plain_b.ids)) return error.MiniAdmissionChangedSecond; +} + +/// Priced copies deliberately alternate whole matches, first-row rejection and a prefix match. +const Copier = struct { + prompt_len: usize, + plain: []const u32, + out: [4]u32 = undefined, + calls: usize = 0, + rejected: bool = false, + partial: bool = false, + continued: bool = false, + full: bool = false, + was_rejected: bool = false, + + fn propose(ptr: *anyopaque, context: []const u32, most: i64) anyerror![]const u32 { + const c: *@This() = @ptrCast(@alignCast(ptr)); + const n = context.len - c.prompt_len; + if (n >= c.plain.len or most < 2) return &.{}; + if (c.was_rejected) c.continued = true; + const count = @min(c.out.len, @min(c.plain.len - n, @as(usize, @intCast(most)))); + for (c.out[0..count], 0..) |*token, i| token.* = c.plain[n + i]; + const mode = c.calls % 3; + c.was_rejected = false; + if (mode == 0 and count >= 2) { + c.full = true; + } else if (mode == 1 and count >= 2) { + c.out[0] = if (c.out[0] == 0) 1 else 0; + c.rejected = true; + c.was_rejected = true; + } else if (count >= 2) { + c.out[1] = if (c.out[1] == 0) 1 else 0; + c.partial = true; + } + c.calls += 1; + return c.out[0..count]; + } + + fn proposer(c: *Copier) lanes.Proposer { + return .{ .ptr = c, .vtable = &.{ + .propose = propose, + .last_match = struct { + fn f(_: *anyopaque) i64 { + return 1; + } + }.f, + .priced = true, + } }; + } +}; + +/// Rewind a rejected, partially accepted or fully accepted window, then compare continuation bits with serial decode. +fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, plain: []const u32, accepted: usize) !void { + const v = target(loaded).m.w.c.text.vocab; + const next = accepted + 1; + const ref = try gpu.gpa.alloc(f32, v); + defer gpu.gpa.free(ref); + var serial = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-serial", .prompt = prompt, .max_new = 12, .sampling = sampling }); + defer serial.deinit(gpu.gpa); + const b = loaded.backend; + try b.prefill(&serial); + for (plain[0 .. next + 1], 0..) |token, i| _ = try b.queue(&serial, .{ .value = token }, prompt.len + i + 1); + try download(loaded, ref); + b.release(&serial); + + var drafted = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-drafted", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); + defer drafted.deinit(gpu.gpa); + defer b.release(&drafted); + try b.prefill(&drafted); + const pending = plain[0]; + var tokens: [4]u32 = undefined; + for (&tokens, 0..) |*token, i| token.* = plain[i + 1]; + if (accepted < tokens.len) tokens[accepted] = if (tokens[accepted] == 0) 1 else 0; + var positions: [5]u64 = undefined; + for (&positions, 0..) |*p, i| p.* = prompt.len + i + 1; + const window: lanes.backend.Window = .{ .stream = &drafted, .tokens = &tokens, .parents = null, .positions = &positions, .pending = pending, .held = 0 }; + var picks: [5]u32 = undefined; + var drafts: [4]u32 = undefined; + var out = [1]lanes.backend.Verified{.{ .sampled = &picks, .drafts = &drafts }}; + try b.verify(&.{window}, &out); + if (picks[accepted] != plain[next]) return error.MiniWrongCorrection; + var path: [5]u32 = undefined; + for (path[0..next], 0..) |*p, i| p.* = @intCast(i); + try b.keep(&.{window}, &.{path[0..next]}); + const handle = try b.queue(&drafted, .{ .value = plain[next] }, prompt.len + next + 1); + const after = try gpu.gpa.alloc(f32, v); + defer gpu.gpa.free(after); + try download(loaded, after); + if (!std.mem.eql(u8, std.mem.sliceAsBytes(ref), std.mem.sliceAsBytes(after))) return error.MiniRollbackChangedLogits; + if (try b.read(handle) != plain[next + 1]) return error.MiniPostRejectionTokenChanged; +} + +fn copiedDrafts(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }) |sampling| { + var plain = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); + defer plain.deinit(gpu.gpa); + var copier: Copier = .{ .prompt_len = prompt.len, .plain = plain.ids }; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-copied", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); + defer s.deinit(gpu.gpa); + try serve(gpu, loaded, &s, copier.proposer()); + if (!std.mem.eql(u32, s.emitted(), plain.ids)) return error.MiniCopiesChangedTarget; + if (s.drafted == 0 or s.accepted == 0 or s.accepted == s.drafted) return error.MiniCopyCoverageMissing; + if (!(copier.full and copier.rejected and copier.partial and copier.continued)) return error.MiniCopyCaseMissing; + for ([_]usize{ 0, 1, 4 }) |accepted| try rollback(gpu, loaded, prompt, sampling, plain.ids, accepted); + } +} + +fn readIds(gpu: Gpu, path: []const u8) ![]u32 { + const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, path, gpu.gpa, .limited(1 << 26)); + defer gpu.gpa.free(text); + var out: std.ArrayList(u32) = .empty; + errdefer out.deinit(gpu.gpa); + var it = std.mem.tokenizeAny(u8, text, ", \n\r\t[]"); + while (it.next()) |t| try out.append(gpu.gpa, try std.fmt.parseInt(u32, t, 10)); + return out.toOwnedSlice(gpu.gpa); +} + +pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { + const ids = try readIds(gpu, ids_path); + defer gpu.gpa.free(ids); + if (ids.len < 4096) return error.MiniServingPromptTooShort; + const context = ids.len + 64; + var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true }); + defer loaded.deinit(loaded.ctx); + try hostReference(gpu, &loaded, ids[0..4096]); + check.pass("Mini CUDA serving matches the host reference token for token"); + try freshAndResumed(gpu, &loaded, ids[0..2309]); + check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens"); + try admission(gpu, &loaded, ids[0..257], ids[17..1042]); + check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens"); + try copiedDrafts(gpu, &loaded, ids[0..64]); + check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly"); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index d3fad1a5c2d..9faab17b09b 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -404,6 +404,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "kolibri-reference")) return kolibri_layer_tests.reference(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-layers")) return kolibri_layer_tests.layers(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-full")) return kolibri_tests.full(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "inkling2-serving")) return @import("inkling2_serving_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-pages")) return @import("kolibri_pages_tests.zig").pages(gpu, rest); if (std.mem.eql(u8, cmd, "kolibri-greedy")) return kolibri_tests.greedy(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "kolibri-logits")) return kolibri_tests.logits(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), if (rest.len > 3) rest[3] else null); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 817792de607..687f4f28d77 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -3,6 +3,7 @@ pub const usage = \\usage: tf-cuda-test \\ qwen4 synthetic native Qwen4: binary64 logits/tokens, state seams, lanes and copied drafts + \\ inkling2-serving MODEL IDS_FILE Mini CUDA host-reference, resume, admission and copy-rollback serving equivalence \\ qwen-draft-frames MODEL DRAFTER IDS OUT native 27B DFlash frames: raw bytes equal across partitions, controls red \\ experts-rows experts_rows.cu's windows and chunks against the decode kernel's one-row launches \\ route-rows route_rows.cu's router logits and softmax top-k against float64 (synthetic rows) From 56de51088ae7fef95f58ebe426b8b8e3001b1647 Mon Sep 17 00:00:00 2001 From: ashhart Date: Sat, 21 Nov 2026 14:22:59 +0000 Subject: [PATCH 22/84] inkling2: compile Mini CUDA tests against current lane types --- zig/build/inkling2_host.zig | 1 - zig/tests/cuda/contract_inkling2_modelopt.zig | 2 +- zig/tests/cuda/inkling2_serving_tests.zig | 44 +++++++++---------- zig/tests/cuda/main.zig | 2 +- 4 files changed, 24 insertions(+), 25 deletions(-) diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 03a0ae21548..6cb8bdf618f 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -12,7 +12,6 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin core.addImport("living", b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true })); m.addImport("core", core); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); - m.addImport("bf16_round", b.createModule(.{ .root_source_file = b.path(dir ++ "bf16_round.zig"), .target = target, .optimize = optimize })); m.addImport("inkling2_metal", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize })); m.addImport("metal", b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize })); m.addImport("kernel_sources", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = target, .optimize = optimize })); diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig index 6524ea8a3e2..0bf04642881 100644 --- a/zig/tests/cuda/contract_inkling2_modelopt.zig +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -269,7 +269,7 @@ pub const ModelOpt = struct { if (fill == .nonfinite) x[0] = 0x7fc0; if (fill == .stress) for (0..shape.rows) |row| for (0..h) |col| { const v: f32 = 4 * @as(f32, @floatFromInt(1 + col % 64)); - x[row * h + col] = c.toBf16(v + (if (col >= h / 2 and col < h / 2 + 8) 4 else 0)); + x[row * h + col] = c.toBf16(v + @as(f32, if (col >= h / 2 and col < h / 2 + 8) 4 else 0)); }; self.x = x; const p13 = try projectionRef(a, self.format, experts, 2 * m, h, true, fill); diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index 60491f210f8..ccaff978e1d 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -2,6 +2,7 @@ const std = @import("std"); const lanes = @import("lanes"); const mini = @import("inkling2"); +const cuda = @import("cuda"); const check = @import("check.zig"); const native = mini.native; @@ -25,17 +26,15 @@ fn target(loaded: *native.Loaded) *Backend { return &loaded.target.backend; } -fn download(loaded: *native.Loaded, out: []f32) !void { - const b = target(loaded); +fn download(b: *Backend, src: u64, out: []f32) !void { try b.s.synchronize(); - try b.m.logits.download(0, std.mem.sliceAsBytes(out)); + try cuda.memory.download(b.d, src, std.mem.sliceAsBytes(out)); } /// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. -fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.Reuse) !Trace { +fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.stream.Reuse) !Trace { const t = target(loaded); - const v = t.m.w.c.text.vocab; - const unpadded = t.m.w.c.text.unpadded_vocab; + const v = t.m.w.c.text.unpadded_vocab; var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-trace", .prompt = prompt, .max_new = @intCast(n), .sampling = sampling, .reuse = reuse }); defer s.deinit(gpu.gpa); const b = loaded.backend; @@ -45,13 +44,13 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes const logits = try gpu.gpa.alloc(f32, n * v); errdefer gpu.gpa.free(logits); try b.prefill(&s); - try download(loaded, logits[0..v]); + try download(t, t.slot[0].ptr, logits[0..v]); var handle: ?u64 = try b.first(&s, prompt.len); for (0..n) |i| { - ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..unpadded], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); + ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..v], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); if (i + 1 < n) { handle = try b.queue(&s, .{ .value = ids[i] }, prompt.len + i + 1); - try download(loaded, logits[(i + 1) * v ..][0..v]); + try download(t, t.m.s.logits, logits[(i + 1) * v ..][0..v]); } } return .{ .ids = ids, .logits = logits, .cached = s.cached, .failed = s.reuse_failed }; @@ -113,11 +112,11 @@ fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void } } -fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.Proposer) !void { +fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.proposer.Proposer) !void { var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); defer cfg.deinit(gpu.gpa); cfg.timed = false; - const clock: lanes.fake.FixedClock = .{}; + var clock: lanes.fake.FixedClock = .{}; var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); defer e.deinit(); if (proposer) |p| s.proposer = p; @@ -138,7 +137,7 @@ fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) ! var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); defer cfg.deinit(gpu.gpa); cfg.timed = false; - const clock: lanes.fake.FixedClock = .{}; + var clock: lanes.fake.FixedClock = .{}; var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); defer e.deinit(); if (!native.fits(loaded.ctx, @intCast(a.len), first.max_new)) return error.MiniUnexpectedFreeSlot; @@ -146,12 +145,12 @@ fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) ! if (native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniBusyAdmissionRefused; try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&second)); while (!first.finished) try e.step(); - try std.testing.expectEqual(lanes.Reason.length, first.reason); + try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSlotNotReleased; try e.addStream(&second); while (!second.finished) try e.step(); - try std.testing.expectEqual(lanes.Reason.length, second.reason); + try std.testing.expectEqual(lanes.stream.Reason.length, second.reason); if (!std.mem.eql(u32, second.emitted(), plain_b.ids)) return error.MiniAdmissionChangedSecond; } @@ -190,7 +189,7 @@ const Copier = struct { return c.out[0..count]; } - fn proposer(c: *Copier) lanes.Proposer { + fn proposer(c: *Copier) lanes.proposer.Proposer { return .{ .ptr = c, .vtable = &.{ .propose = propose, .last_match = struct { @@ -205,7 +204,8 @@ const Copier = struct { /// Rewind a rejected, partially accepted or fully accepted window, then compare continuation bits with serial decode. fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, plain: []const u32, accepted: usize) !void { - const v = target(loaded).m.w.c.text.vocab; + const t = target(loaded); + const v = t.m.w.c.text.unpadded_vocab; const next = accepted + 1; const ref = try gpu.gpa.alloc(f32, v); defer gpu.gpa.free(ref); @@ -214,7 +214,7 @@ fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?la const b = loaded.backend; try b.prefill(&serial); for (plain[0 .. next + 1], 0..) |token, i| _ = try b.queue(&serial, .{ .value = token }, prompt.len + i + 1); - try download(loaded, ref); + try download(t, t.m.s.logits, ref); b.release(&serial); var drafted = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-drafted", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); @@ -239,7 +239,7 @@ fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?la const handle = try b.queue(&drafted, .{ .value = plain[next] }, prompt.len + next + 1); const after = try gpu.gpa.alloc(f32, v); defer gpu.gpa.free(after); - try download(loaded, after); + try download(t, t.m.s.logits, after); if (!std.mem.eql(u8, std.mem.sliceAsBytes(ref), std.mem.sliceAsBytes(after))) return error.MiniRollbackChangedLogits; if (try b.read(handle) != plain[next + 1]) return error.MiniPostRejectionTokenChanged; } @@ -277,11 +277,11 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true }); defer loaded.deinit(loaded.ctx); try hostReference(gpu, &loaded, ids[0..4096]); - check.pass("Mini CUDA serving matches the host reference token for token"); + check.pass("Mini CUDA serving matches the host reference token for token", .{}); try freshAndResumed(gpu, &loaded, ids[0..2309]); - check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens"); + check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens", .{}); try admission(gpu, &loaded, ids[0..257], ids[17..1042]); - check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens"); + check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens", .{}); try copiedDrafts(gpu, &loaded, ids[0..64]); - check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly"); + check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly", .{}); } diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 9faab17b09b..972160f0062 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -165,7 +165,7 @@ fn compileInkling2Contracts() !void { var modelopt: @import("contract_inkling2_modelopt.zig").ModelOpt = undefined; _ = try modelopt.prepare(shape, .random, 0); try modelopt.run(); - _ = try modelopt.check(.shapes); + _ = modelopt.kernel(); _ = modelopt.count(); const want: []f64 = undefined; const mag: []f64 = undefined; From 7e30540a29f37a8d4876b01cd9903e3577a3ba0e Mon Sep 17 00:00:00 2001 From: ashhart Date: Sat, 21 Nov 2026 14:51:54 +0000 Subject: [PATCH 23/84] inkling2: link Metal host tests on macOS --- zig/build/inkling2_host.zig | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 6cb8bdf618f..5a85c5f6f65 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -13,7 +13,13 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin m.addImport("core", core); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); m.addImport("inkling2_metal", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize })); - m.addImport("metal", b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize })); + const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize }); + if (target.result.os.tag == .macos) { + metal.linkFramework("Metal", .{}); + metal.linkFramework("Foundation", .{}); + metal.linkSystemLibrary("objc", .{}); + } + m.addImport("metal", metal); m.addImport("kernel_sources", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = target, .optimize = optimize })); const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); inkling2_metal_ref.addImport("metal", m.import_table.get("metal").?); From 2a8cdd6d61d08447a7acbabd77e8f2aad93e4c49 Mon Sep 17 00:00:00 2001 From: ashhart Date: Sat, 21 Nov 2026 14:52:38 +0000 Subject: [PATCH 24/84] inkling2: fix nonfinite prompt expert launches --- zig/src/families/inkling2/modelopt.zig | 4 ++-- zig/tests/cuda/contract_inkling2_modelopt.zig | 16 +++------------- 2 files changed, 5 insertions(+), 15 deletions(-) diff --git a/zig/src/families/inkling2/modelopt.zig b/zig/src/families/inkling2/modelopt.zig index 322a81e8bf3..7ef444cab24 100644 --- a/zig/src/families/inkling2/modelopt.zig +++ b/zig/src/families/inkling2/modelopt.zig @@ -25,7 +25,7 @@ pub const Layer = struct { w2: Projection, }; -const Weight = extern struct { +pub const Weight = extern struct { codes: u64, scales: u64, amax: u64, @@ -115,7 +115,7 @@ fn i32d(v: usize) i32 { return @intCast(v); } -fn weight(p: Projection, l: Layer, row0: i32, row_step: i32) Weight { +pub fn weight(p: Projection, l: Layer, row0: i32, row_step: i32) Weight { return .{ .codes = p.codes, .scales = p.scales, diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig index 0bf04642881..5052173fd2a 100644 --- a/zig/tests/cuda/contract_inkling2_modelopt.zig +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -249,7 +249,7 @@ pub const ModelOpt = struct { pub fn prepare(self: *ModelOpt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { _ = seed; - if (self.phase == .prompt and shape.rows < 32 and fill != .stress) return false; + if (self.phase == .prompt and shape.rows < 32 and fill != .stress and fill != .nonfinite) return false; if (shape.n != 2304 or shape.k != 1152 or shape.rows == 0 or shape.rows > 2048) return false; self.drop(); self.shape = shape; @@ -334,7 +334,7 @@ pub const ModelOpt = struct { pub fn run(self: *ModelOpt) !void { const route_weights = if (self.fault == .wrong_combine) self.pick else self.weights; const caps = if (self.fault == .wrong_act) ink.experts.Caps{ .gate = 8, .up = 25 } else ink.experts.Caps{ .gate = 4, .up = 25 }; - if (self.stress and self.phase == .prompt and self.shape.rows < 32) return self.runPrompt(caps); + if (self.phase == .prompt and self.shape.rows < 32) return self.runPrompt(caps); try mo.run(self.k, self.rig.s, self.l, caps, self.dev_x, self.shape.n, self.pick, route_weights, self.shape.rows, slots, self.out, self.scratch); } @@ -414,17 +414,7 @@ pub const ModelOpt = struct { a.add(x); a.add(@as(i32, @intCast(stride))); a.add(@as(i32, @intCast(pair_slots))); - a.add(p.codes); - a.add(p.scales); - a.add(p.amax); - a.add(p.denominator); - a.add(@as(i64, experts)); - a.add(@as(i64, p.n)); - a.add(@as(i64, p.k)); - a.add(@as(i32, if (self.format == .nvfp4) 16 else 32)); - a.add(@as(i32, @backingInt(self.format))); - a.add(row0); - a.add(step); + a.add(mo.weight(p, self.l, row0, step)); a.add(@as(i32, @intCast(p.k / 32))); a.add(@as(i32, @intCast(outputs / 32))); for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); From dd60cf1b1192fc7913dbc3f3f311c52a2ebbb565 Mon Sep 17 00:00:00 2001 From: ashhart Date: Sat, 21 Nov 2026 15:21:49 +0000 Subject: [PATCH 25/84] inkling2: refresh Mini limits and quiet shape refusal --- zig/src/core/contract/inkling2_ops_records.zig | 2 +- zig/src/families/inkling2/metal/dspark_weights.zig | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/zig/src/core/contract/inkling2_ops_records.zig b/zig/src/core/contract/inkling2_ops_records.zig index e5ce0103f66..fbfd8cc5f45 100644 --- a/zig/src/core/contract/inkling2_ops_records.zig +++ b/zig/src/core/contract/inkling2_ops_records.zig @@ -4,7 +4,7 @@ const registry = @import("registry.zig"); /// nvcc 13.0's usage (nvcc -cubin per SM at the images' flags), the compiler of the release fatbins; 13.2 pending. pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2 ops tf_ink2_embed", .symbol = "tf_ink2_embed", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 21, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 22, .static = 128, .bound = 256 }, .{ .regs = 22, .static = 128, .bound = 256 } } }, - .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix", .symbol = "tf_ink2_mix", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix", .symbol = "tf_ink2_mix", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 72, .static = 45712, .bound = 512 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix_rows", .symbol = "tf_ink2_mix_rows", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_rowdot", .symbol = "tf_ink2_rowdot", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_topk", .symbol = "tf_ink2_topk", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 24, .static = 384, .bound = 512 }, .{ .regs = 23, .static = 384, .bound = 512 }, .{ .regs = 23, .static = 384, .bound = 512 }, .{ .regs = 36, .static = 384, .bound = 512 }, .{ .regs = 36, .static = 384, .bound = 512 } } }, diff --git a/zig/src/families/inkling2/metal/dspark_weights.zig b/zig/src/families/inkling2/metal/dspark_weights.zig index b9260e1b88f..00082911738 100644 --- a/zig/src/families/inkling2/metal/dspark_weights.zig +++ b/zig/src/families/inkling2/metal/dspark_weights.zig @@ -64,15 +64,13 @@ pub const Loaded = struct { } }; -fn require(t: ck.Tensor, dims: []const usize, name: []const u8) !ck.Tensor { +fn require(t: ck.Tensor, dims: []const usize, _: []const u8) !ck.Tensor { if (t.dtype != .bf16 or t.rank != dims.len) { - std.log.err("DSpark tensor {s} must be BF16 with rank {d}", .{ name, dims.len }); return error.DSparkTensorShape; } var count: usize = 1; for (dims, 0..) |d, i| { if (t.shape[i] != d) { - std.log.err("DSpark tensor {s} dimension {d} must be {d}, not {d}", .{ name, i, d, t.shape[i] }); return error.DSparkTensorShape; } count = std.math.mul(usize, count, d) catch return error.DSparkTensorShape; From 3e0e9bcb834616a4246b0e66320879e778538463 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:27:02 +0000 Subject: [PATCH 26/84] inkling2: complete native Metal admission and serving tests --- THIRD_PARTY_NOTICES.md | 9 +-- tools/zig/inkling2_fixtures.py | 10 +-- zig/build/metal_server.zig | 11 ++- zig/src/core/checkpoint_metal.zig | 4 +- zig/src/core/contract.zig | 4 + zig/src/core/root.zig | 1 + .../inkling2/fixtures/mini_config.json | 4 +- .../inkling2/fixtures/mini_model_header.txt | 2 +- .../inkling2/fixtures/mini_mtp_header.txt | 2 +- .../inkling2/metal/dspark_kernels_test.zig | 2 +- zig/src/families/inkling2/metal/glue_test.zig | 4 +- zig/src/families/inkling2/metal/host_test.zig | 3 +- zig/src/families/inkling2/metal/loop_test.zig | 2 +- zig/src/families/inkling2/metal/model.zig | 2 +- .../inkling2/metal/runtime_kernels_test.zig | 2 +- .../families/inkling2/metal/serving_test.zig | 79 +++++++++++++------ zig/src/native/inkling2.zig | 65 ++++++++++++++- zig/src/native/inkling2_capabilities_test.zig | 13 +++ 18 files changed, 169 insertions(+), 50 deletions(-) create mode 100644 zig/src/native/inkling2_capabilities_test.zig diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 0a8da983d22..bb22e7fb461 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -558,13 +558,10 @@ model and states no licence; no weights are included. `tools/zig/inkling2_fixtur `mini_config.json`, `mini_model_header.txt` and `mini_mtp_header.txt` in `zig/src/families/inkling2/fixtures/` come from the 2026-11-20 published snapshot of -[thinkingmachines/Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini), under the Apache License 2.0 -stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)). The config is the published `config.json` plus -its explicit `_fixture_provenance` annotation; the folded tables contain only metadata from the model and MTP safetensors +[thinkingmachines/Inkling-2-Mini at `ed40e7da625f594fc9c4990f5f66be24873c22d7`](https://huggingface.co/thinkingmachines/Inkling-2-Mini), under the Apache License 2.0 +stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)). The public model API supplied that full revision and last-modified time 2026-11-20T22:55:20Z. The fixture config differs from the supplied published `config.json` only by its explicit `_fixture_provenance` annotation; after excluding that annotation, every checkpoint config field matches. The folded tables contain only metadata from the model and MTP safetensors headers, no tensor data or weights. `tools/zig/inkling2_fixtures.py` rebuilds all three from the Mini release, or from its -extracted headers. None of the supplied config, generation config, quantization config, model card, tensor headers or -Mini specification records the release's full Hugging Face commit SHA. The fixtures therefore mark it unavailable rather -than deriving a revision from their digests. +extracted headers, with the same revision annotation. No revision was derived from fixture digests. The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, `loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and diff --git a/tools/zig/inkling2_fixtures.py b/tools/zig/inkling2_fixtures.py index e9dc31a617b..ac0465d7e4a 100644 --- a/tools/zig/inkling2_fixtures.py +++ b/tools/zig/inkling2_fixtures.py @@ -11,15 +11,16 @@ RELEASE = "thinkingmachines/Inkling-2-Small@2ad1157016e1aac77b6ff1b770e7c05229403134" TINY = "tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7" MINI_RELEASE = "thinkingmachines/Inkling-2-Mini" +MINI_REVISION = "ed40e7da625f594fc9c4990f5f66be24873c22d7" MINI_PROVENANCE = { "release": MINI_RELEASE, - "revision": None, - "revision_status": "full commit SHA absent from the supplied published metadata", + "revision": MINI_REVISION, + "revision_status": "full revision supplied separately; every checkpoint config field matches", "published": "2026-11-20", "license": "apache-2.0", } MINI_HEADER_PROVENANCE = ( - f"release={MINI_RELEASE} revision=unavailable-full-commit-SHA-absent-from-supplied-inputs " + f"release={MINI_RELEASE} revision={MINI_REVISION} " "published=2026-11-20 license=apache-2.0" ) PINS = {"transformers": "5.20.0", "tokenizers": "0.23.3", "jinja2": "3.1.6"} @@ -216,8 +217,7 @@ def main(): parser.add_argument("--tiny", type=Path, required=True, help=f"{TINY}: config.json, model.safetensors, mtp.safetensors") parser.add_argument( "--mini", type=Path, required=True, - help=f"{MINI_RELEASE}: config.json and model/MTP safetensors or extracted .header.json files; " - "the supplied snapshot has no full commit SHA", + help=f"{MINI_RELEASE}: config.json and model/MTP safetensors or extracted .header.json files; full revision supplied separately after config-field match", ) parser.add_argument("--out", type=Path, default=FIXTURES, help="the fixtures directory to write or compare") parser.add_argument("--check", action="store_true", help="write nothing; exit 1 if a file differs from the one in --out") diff --git a/zig/build/metal_server.zig b/zig/build/metal_server.zig index a7ecdee845e..b82cb3fe292 100644 --- a/zig/build/metal_server.zig +++ b/zig/build/metal_server.zig @@ -100,7 +100,16 @@ pub fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s const flint_draft_host = b.step("test-flint-draft-host", "Flint draft config, taps and first-token metadata without devices"); for ([_]*std.Build.Module{ engine, api.import_table.get("lanes").? }) |module| flint_draft_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"Flint DFlash2"} })).step); - b.step("test-native", "The Metal engines module's host-side tests").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines })).step); + const native_tests = b.step("test-native", "The Metal engines module's host-side tests"); + native_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engines })).step); + const capabilities = b.createModule(.{ .root_source_file = b.path("zig/src/native/inkling2_capabilities_test.zig"), .target = target, .optimize = .Debug, .link_libc = true }); + for (engines.import_table.keys(), engines.import_table.values()) |name, module| capabilities.addImport(name, module); + capabilities.addImport("native_metal", engines); + const capability_run = b.addRunArtifact(b.addTest(.{ .root_module = capabilities })); + const capability_step = b.step("test-inkling2-metal-capabilities", "Inkling native Metal checkpoint-format capabilities"); + capability_step.dependOn(&capability_run.step); + native_tests.dependOn(capability_step); + test_step.?.dependOn(&capability_run.step); const reuse = b.addExecutable(.{ .name = "tf-flashnext-reuse", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/flashnext_reuse.zig"), .target = target, diff --git a/zig/src/core/checkpoint_metal.zig b/zig/src/core/checkpoint_metal.zig index 39e081ba863..8cea8b3ccaf 100644 --- a/zig/src/core/checkpoint_metal.zig +++ b/zig/src/core/checkpoint_metal.zig @@ -2,8 +2,8 @@ const std = @import("std"); const platform = @import("sys"); const mtl = @import("metal"); -const st = @import("safetensors.zig"); -const file_cache = @import("checkpoint_file_cache.zig"); +const st = @import("core").safetensors; +const file_cache = @import("core").checkpoint_file_cache; pub const DType = st.DType; diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 2b352571903..4848f409ad1 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -11,6 +11,10 @@ pub const dense = @import("contract/dense.zig"); pub const bf16_round = @import("bf16_round"); pub const attention_range = @import("attention_range.zig"); pub const limits = @import("contract/limits.zig"); +pub const inkling2_glue_metal_records = @import("contract/inkling2_glue_metal_records.zig"); +pub const inkling2_dspark_metal_records = @import("contract/inkling2_dspark_metal_records.zig"); +pub const inkling2_loop_metal_records = @import("contract/inkling2_loop_metal_records.zig"); +pub const inkling2_runtime_metal_records = @import("contract/inkling2_runtime_metal_records.zig"); pub const lane_q8 = @import("contract/lane_q8_records.zig"); pub const q27_prompt = @import("contract/qwen27_prompt_records.zig"); pub const registry = @import("contract/registry.zig"); diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 83ceaa32e28..1d489df68ef 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -14,6 +14,7 @@ pub const digest_cache = @import("digest_cache.zig"); pub const checkpoint_identity = @import("checkpoint_identity.zig"); pub const checkpoint_read_ahead = @import("checkpoint_read_ahead.zig"); pub const checkpoint = @import("checkpoint.zig"); +pub const checkpoint_file_cache = @import("checkpoint_file_cache.zig"); pub const dfloat11_config = @import("dfloat11_config.zig"); pub const checkpoint_fixture = @import("checkpoint_fixture.zig"); pub const dfloat11_fixtures = @import("dfloat11_fixtures.zig"); diff --git a/zig/src/families/inkling2/fixtures/mini_config.json b/zig/src/families/inkling2/fixtures/mini_config.json index 53d31e37584..71dca9f656e 100644 --- a/zig/src/families/inkling2/fixtures/mini_config.json +++ b/zig/src/families/inkling2/fixtures/mini_config.json @@ -1,8 +1,8 @@ { "_fixture_provenance": { "release": "thinkingmachines/Inkling-2-Mini", - "revision": null, - "revision_status": "full commit SHA absent from the supplied published metadata", + "revision": "ed40e7da625f594fc9c4990f5f66be24873c22d7", + "revision_status": "full revision supplied separately; every checkpoint config field matches", "published": "2026-11-20", "license": "apache-2.0" }, diff --git a/zig/src/families/inkling2/fixtures/mini_model_header.txt b/zig/src/families/inkling2/fixtures/mini_model_header.txt index 84367e4d080..0ec22c72d2b 100644 --- a/zig/src/families/inkling2/fixtures/mini_model_header.txt +++ b/zig/src/families/inkling2/fixtures/mini_model_header.txt @@ -1,4 +1,4 @@ -inkling2-mini-model 1244 dfcec4225659aceabe432e4daadb4e6291f3718e2015d412f97f60200de32141 release=thinkingmachines/Inkling-2-Mini revision=unavailable-full-commit-SHA-absent-from-supplied-inputs published=2026-11-20 license=apache-2.0 +inkling2-mini-model 1244 dfcec4225659aceabe432e4daadb4e6291f3718e2015d412f97f60200de32141 release=thinkingmachines/Inkling-2-Mini revision=ed40e7da625f594fc9c4990f5f66be24873c22d7 published=2026-11-20 license=apache-2.0 model.llm.attn_res.attn_queries.{L} F32 2304 0-3,5-9,11-15,17-21 model.llm.attn_res.attn_queries.{L} F32 3x2304 4,10,16,22 model.llm.attn_res.mlp_queries.{L} F32 2304 0-23 diff --git a/zig/src/families/inkling2/fixtures/mini_mtp_header.txt b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt index 312daa6c44e..1f02401ebcb 100644 --- a/zig/src/families/inkling2/fixtures/mini_mtp_header.txt +++ b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt @@ -1,4 +1,4 @@ -inkling2-mini-mtp 54 f962cd87735ebbd1af0639f7513f99eed98b61d8a30b083fb33fc1bb1c3a70d1 release=thinkingmachines/Inkling-2-Mini revision=unavailable-full-commit-SHA-absent-from-supplied-inputs published=2026-11-20 license=apache-2.0 +inkling2-mini-mtp 54 f962cd87735ebbd1af0639f7513f99eed98b61d8a30b083fb33fc1bb1c3a70d1 release=thinkingmachines/Inkling-2-Mini revision=ed40e7da625f594fc9c4990f5f66be24873c22d7 published=2026-11-20 license=apache-2.0 fuse_weight BF16 4x4 layers.{L}.dflare_norm.weight BF16 2304 0-2 layers.{L}.input_layernorm.weight BF16 2304 0-2 diff --git a/zig/src/families/inkling2/metal/dspark_kernels_test.zig b/zig/src/families/inkling2/metal/dspark_kernels_test.zig index 0562997cadc..b72660d3aa2 100644 --- a/zig/src/families/inkling2/metal/dspark_kernels_test.zig +++ b/zig/src/families/inkling2/metal/dspark_kernels_test.zig @@ -1,7 +1,7 @@ //! Host-only FP64 witnesses for Mini DSpark rounding, pairing, reach and launch contracts. const std = @import("std"); const k = @import("dspark_kernels.zig"); -const records = @import("../../../core/contract/inkling2_dspark_metal_records.zig").records; +const records = @import("core").contract.inkling2_dspark_metal_records.records; const shader = @import("inkling2_metal").inkling2_dspark; const t = std.testing; diff --git a/zig/src/families/inkling2/metal/glue_test.zig b/zig/src/families/inkling2/metal/glue_test.zig index 815c606f0c7..f1480f33b33 100644 --- a/zig/src/families/inkling2/metal/glue_test.zig +++ b/zig/src/families/inkling2/metal/glue_test.zig @@ -1,9 +1,9 @@ //! Host-only proof of Mini's glue formulas, source inventory and shape admission. const std = @import("std"); const p = @import("inkling2_glue_plan"); -const records = @import("../../../core/contract/inkling2_glue_metal_records.zig").records; +const records = @import("core").contract.inkling2_glue_metal_records.records; const shader = @import("inkling2_metal").glue; -const c = @import("../../../core/contract/contract.zig"); +const c = @import("core").contract.spec; const t = std.testing; fn near(want: f64, got: f64) !void { diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index db8bce1b868..8598da235d9 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -1,4 +1,5 @@ //! Host-only Inkling 2 Mini Metal launch plans and scalar arithmetic references. +const serving = if (@import("builtin").os.tag.isDarwin()) @import("serving_test.zig") else struct {}; test { _ = @import("attention_test.zig"); @@ -13,5 +14,5 @@ test { _ = @import("dspark_state.zig"); _ = @import("dspark.zig"); _ = @import("backend.zig"); - _ = @import("serving_test.zig"); + _ = serving; } diff --git a/zig/src/families/inkling2/metal/loop_test.zig b/zig/src/families/inkling2/metal/loop_test.zig index 4fc655e211b..9634fc44573 100644 --- a/zig/src/families/inkling2/metal/loop_test.zig +++ b/zig/src/families/inkling2/metal/loop_test.zig @@ -1,7 +1,7 @@ //! Host-only proof of Mini's loop formulas, launch ABI, source inventory and rounding. const std = @import("std"); const p = @import("inkling2_loop_plan"); -const records = @import("../../../core/contract/inkling2_loop_metal_records.zig").records; +const records = @import("core").contract.inkling2_loop_metal_records.records; const shader = @import("inkling2_metal").loop; const t = std.testing; diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig index 078104e1f62..a60acf86d1e 100644 --- a/zig/src/families/inkling2/metal/model.zig +++ b/zig/src/families/inkling2/metal/model.zig @@ -5,7 +5,7 @@ const sources = @import("kernel_sources"); const cfg = @import("../config.zig"); const layer_plan = @import("../plan.zig"); const ck = @import("../../../core/checkpoint_metal.zig"); -const shards = @import("../../../core/checkpoint.zig"); +const shards = @import("core").checkpoint; const attention = @import("attention.zig"); const glue = @import("glue.zig"); const experts = @import("experts.zig"); diff --git a/zig/src/families/inkling2/metal/runtime_kernels_test.zig b/zig/src/families/inkling2/metal/runtime_kernels_test.zig index 0c3902ffaa6..ceb359181d8 100644 --- a/zig/src/families/inkling2/metal/runtime_kernels_test.zig +++ b/zig/src/families/inkling2/metal/runtime_kernels_test.zig @@ -2,7 +2,7 @@ const std = @import("std"); const p = @import("runtime_plan.zig"); const model = @import("model.zig"); -const records = @import("../../../core/contract/inkling2_runtime_metal_records.zig").records; +const records = @import("core").contract.inkling2_runtime_metal_records.records; const shader = @import("inkling2_metal").runtime; const t = std.testing; diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig index d24f8136269..d78d6df3abd 100644 --- a/zig/src/families/inkling2/metal/serving_test.zig +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -7,7 +7,7 @@ const native = @import("../../../native/inkling2.zig"); const Model = @import("model.zig").Model; const backend = @import("backend.zig"); const st = @import("state.zig"); -const native_metal = @import("../../../native/metal.zig"); +const dspark = @import("dspark.zig"); const gpa = std.testing.allocator; const io = std.testing.io; @@ -44,10 +44,26 @@ const TapSink = struct { } }; +fn featureRow(b: lanes.backend.Backend, s: *lanes.Stream, start: u64) ![st.feature_row_bytes]u8 { + const f = try b.features(s, &taps, start, 1); + try std.testing.expectEqual(lanes.backend.Features.Space.device, f.space); + try std.testing.expectEqual(lanes.backend.Features.Dtype.bf16, f.dtype); + try std.testing.expectEqual(@as(u32, 1), f.rows); + try std.testing.expectEqual(@as(u32, st.feature_row_bytes), f.row_bytes); + const buf: mtl.Buffer = .{ .id = @ptrFromInt(f.buffer) }; + const bytes = buf.slice(u8, @intCast(f.offset + f.row_bytes)); + var row: [st.feature_row_bytes]u8 = undefined; + @memcpy(&row, bytes[@intCast(f.offset)..][0..st.feature_row_bytes]); + return row; +} + const Reference = struct { tokens: [made]u32, first: lanes.LogprobRow, tap: [st.feature_row_bytes]u8, + full_tap: [st.feature_row_bytes]u8 = undefined, + partial_tap: [st.feature_row_bytes]u8 = undefined, + continuation_tap: [st.feature_row_bytes]u8 = undefined, }; fn serial(b: lanes.backend.Backend, ids: []const u32) !Reference { @@ -65,6 +81,12 @@ fn serial(b: lanes.backend.Backend, ids: []const u32) !Reference { for (1..made) |i| { next = try b.read(try b.queue(&s, .{ .value = next }, ids.len + i)); out.tokens[i] = next; + switch (i) { + 8 => out.full_tap = try featureRow(b, &s, ids.len + 7), + 15 => out.partial_tap = try featureRow(b, &s, ids.len + 14), + 16 => out.continuation_tap = try featureRow(b, &s, ids.len + 15), + else => {}, + } } return out; } @@ -171,20 +193,29 @@ fn expectTokens(want: *const Reference, got: *const Reply) !void { try expectFirstRow(want.first, got.rows.items[0]); } -fn transactions(dir: []const u8, ids: []const u32, want: *const Reference) !void { +fn transactions(dir: []const u8, drafter_dir: []const u8, ids: []const u32, want: *const Reference) !void { const model = try Model.load(gpa, io, dir); defer model.deinit(); const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = st.cacheBytes(context) }); defer target.deinit(); - const b = target.backend(); - try b.vtable.prepare_features.?(b.ptr, &taps); - var s = try lanes.Stream.init(gpa, .{ .id = "transactions", .prompt = ids, .max_new = made, .drafts = false, .logprobs = 3 }); + const draft_head = try dspark.Drafter.init(gpa, io, model.device, model, drafter_dir); + defer draft_head.deinit(); + try draft_head.setContext(context); + var wrapped = try lanes.drafted.Drafted.init(gpa, target.backend(), draft_head.drafter()); + defer wrapped.deinit(); + wrapped.first_rows = true; + const b = wrapped.backend(); + const target_b = target.backend(); + var s = try lanes.Stream.init(gpa, .{ .id = "transactions", .prompt = ids, .max_new = made, .drafts = true, .logprobs = 3 }); defer s.deinit(gpa); try b.prefill(&s); defer b.release(&s); + try expectFirstRow(want.first, try b.firstRow(&s)); + try std.testing.expectEqualSlices(u8, &want.tap, &(try featureRow(target_b, &s, ids.len - 1))); const full_drafts = want.tokens[1..8]; const full_positions = [_]u64{ ids.len + 1, ids.len + 2, ids.len + 3, ids.len + 4, ids.len + 5, ids.len + 6, ids.len + 7, ids.len + 8 }; + const full_path = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7 }; const full = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[0], .held = 0, .tokens = full_drafts, .parents = null, .positions = &full_positions }}; var sampled: [8]u32 = undefined; var echo: [7]u32 = undefined; @@ -192,7 +223,9 @@ fn transactions(dir: []const u8, ids: []const u32, want: *const Reference) !void try b.verify(&full, &full_out); try std.testing.expectEqualSlices(u32, want.tokens[1..9], &sampled); try std.testing.expectEqualSlices(u32, full_drafts, &echo); - try b.keep(&full, &.{&.{ 0, 1, 2, 3, 4, 5, 6, 7 }}); + try b.keep(&full, &.{&full_path}); + try std.testing.expectEqualSlices(u8, &want.full_tap, &(try featureRow(target_b, &s, ids.len + 7))); + try b.draft(&.{.{ .stream = &s, .follow = want.tokens[1..9], .rows = &full_path, .start = ids.len, .position = ids.len + 9, .depth = 7 }}); var partial_drafts = want.tokens[9..16].*; partial_drafts[6] = (want.tokens[15] + 1) % model.config.text.unpadded_vocab; @@ -203,8 +236,11 @@ fn transactions(dir: []const u8, ids: []const u32, want: *const Reference) !void try b.verify(&partial, &partial_out); try std.testing.expectEqualSlices(u32, want.tokens[9..17], &sampled); try b.keep(&partial, &.{&path}); + try std.testing.expectEqualSlices(u8, &want.partial_tap, &(try featureRow(target_b, &s, ids.len + 14))); + try b.draft(&.{.{ .stream = &s, .follow = want.tokens[9..16], .rows = &path, .start = ids.len + 8, .position = ids.len + 16, .depth = 7 }}); const next = try b.read(try b.queue(&s, .{ .value = want.tokens[15] }, ids.len + 16)); try std.testing.expectEqual(want.tokens[16], next); + try std.testing.expectEqualSlices(u8, &want.continuation_tap, &(try featureRow(target_b, &s, ids.len + 15))); } test "Mini Metal serving matches the host reference token for token" { @@ -223,10 +259,10 @@ test "Mini Metal serving matches the host reference token for token" { try std.testing.expectEqual(@as(?f64, 0.5), opened_once.engine.info().decode_share); const keepalive = opened_once.engine.keepaliveTarget() orelse return error.MissingMiniKeepalive; keepalive.tick(keepalive.ctx); - const first = try serve(opened_once, 1, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + var first = try serve(opened_once, 1, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); defer first.deinit(); try expectTokens(&refs.first, &first); - const restored = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + var restored = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); defer restored.deinit(); try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); try expectTokens(&refs.second.?, &restored); @@ -236,28 +272,25 @@ test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back e const dir = try checkpoint(); const drafter = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; const ids = prompt(64, 3); - const refs = try withReference(dir, &ids, null); - try transactions(dir, &ids, &refs.first); + var turn: [80]u32 = undefined; + @memcpy(turn[0..64], &ids); + @memcpy(turn[64..], &prompt(16, 2)); + const refs = try withReference(dir, &ids, &turn); + try transactions(dir, drafter, &ids, &refs.first); - const opened_once = try opened(dir, drafter, 0); + const opened_once = try opened(dir, drafter, 1); defer opened_once.close(opened_once.ctx); - const plain = try serve(opened_once, 10, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3 }); + var plain = try serve(opened_once, 10, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); defer plain.deinit(); try expectTokens(&refs.first, &plain); try std.testing.expectEqual(@as(u64, 0), plain.drafted); - const drafted = try serve(opened_once, 11, &.{ .prompt = &ids, .max_tokens = made, .drafts = true, .logprobs = 3 }); + var drafted = try serve(opened_once, 11, &.{ .prompt = &ids, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); defer drafted.deinit(); try expectTokens(&refs.first, &drafted); try std.testing.expect(drafted.drafted > 0); try std.testing.expect(drafted.accepted > 0); -} - -test "Metal capabilities: inkling2_loop serves the checkpoint's ModelOpt NVFP4 weights" { - var found = false; - for (native_metal.families) |family| if (std.mem.eql(u8, family.model_type, "inkling2_loop")) { - found = true; - try std.testing.expectEqual(@as(usize, 1), family.formats.len); - try std.testing.expectEqualStrings("modelopt-nvfp4", family.formats[0]); - }; - try std.testing.expect(found); + var restored = try serve(opened_once, 12, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer restored.deinit(); + try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); + try expectTokens(&refs.second.?, &restored); } diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index 9a09ef9f40b..dd0105c93ea 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -82,8 +82,10 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope } else null; errdefer if (drafter) |d| d.deinit(); var ram: u64 = 0; - var len: usize = @sizeOf(u64); - if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; + if (@import("builtin").os.tag.isDarwin()) { + var len: usize = @sizeOf(u64); + if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; + } const scratch: u64 = st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows); const resident = model.checkpoint.residentBytes() + scratch + if (drafter) |d| d.fixedBytes() + dspark.Drafter.scoreBytes(0) else 0; const budget = cacheBudget(ram, model.device.maxWorkingSet(), @import("sys").getenv("INKLING2_LOAD_LIMIT_GB"), resident) catch { @@ -206,6 +208,65 @@ test "Inkling native admission keeps DSpark opt-in and refuses learned modes" { try std.testing.expect(contextProblem(10, 10) == null); } +test "Inkling native open publishes the exact admission refusal" { + var problem: []const u8 = "not published"; + const o: api.Open = .{ .dir = "unused", .model_type = "inkling2_loop", .learn_conversations = true }; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: learned disk states are not implemented; serve without --learn and --learn-conversations", problem); +} + +test "Inkling native open releases DSpark when the later context admission refuses (TF_INKLING2_METAL_DIR, TF_INKLING2_DSPARK_DIR)" { + const dir = @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse return error.SkipZigTest; + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + var problem: []const u8 = "not published"; + var o: api.Open = .{ .dir = dir, .model_type = "inkling2_loop", .context = 0, .drafter = drafter_dir }; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: --context must be at least one token, and the selected context must fit the Metal state budget", problem); + o.context = std.math.maxInt(i64); + problem = "not published"; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: --context exceeds the largest window this Mac can afford beside the checkpoint and DSpark state", problem); + // Null skips errdefer; omitting explicit deinit leaks allocations caught by std.testing.allocator. +} + +test "Inkling native open unwinds DSpark when the later Host allocation fails (TF_INKLING2_METAL_DIR, TF_INKLING2_DSPARK_DIR)" { + const Fault = struct { + drafter_allocated: bool = false, + host_failed: bool = false, + + fn allocator(f: *@This()) std.mem.Allocator { + return .{ .ptr = f, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const f: *@This() = @ptrCast(@alignCast(ctx)); + if (f.drafter_allocated and len == @sizeOf(Host)) { + f.host_failed = true; + return null; + } + const memory = std.testing.allocator.rawAlloc(len, alignment, ra) orelse return null; + if (len == @sizeOf(dspark.Drafter)) f.drafter_allocated = true; + return memory; + } + fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { + return std.testing.allocator.rawResize(memory, alignment, len, ra); + } + fn remap(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { + return std.testing.allocator.rawRemap(memory, alignment, len, ra); + } + fn free(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void { + std.testing.allocator.rawFree(memory, alignment, ra); + } + }; + const dir = @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse return error.SkipZigTest; + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + var fault: Fault = .{}; + var problem: []const u8 = ""; + const o: api.Open = .{ .dir = dir, .model_type = "inkling2_loop", .context = 1, .lanes = 1, .drafter = drafter_dir }; + try std.testing.expectError(error.OutOfMemory, open(std.testing.allocator, fault.allocator(), std.testing.io, o, &problem)); + try std.testing.expect(fault.drafter_allocated and fault.host_failed); + // Removing errdefer leaks DSpark and its weights in std.testing.allocator. +} + test "Inkling native load limit clamps before integer conversion" { const gib: u64 = 1 << 30; try std.testing.expectEqual(8_000_000_000 - 5 * gib, try cacheBudget(16 * gib, 14 * gib, "8", 3 * gib)); diff --git a/zig/src/native/inkling2_capabilities_test.zig b/zig/src/native/inkling2_capabilities_test.zig new file mode 100644 index 00000000000..5dd1c0c1403 --- /dev/null +++ b/zig/src/native/inkling2_capabilities_test.zig @@ -0,0 +1,13 @@ +//! Inkling's checkpoint-format offer in the production native Metal registry. +const std = @import("std"); +const native_metal = @import("native_metal"); + +test "Metal capabilities: inkling2_loop serves the checkpoint's ModelOpt NVFP4 weights" { + var found = false; + for (native_metal.families) |family| if (std.mem.eql(u8, family.model_type, "inkling2_loop")) { + found = true; + try std.testing.expectEqual(@as(usize, 1), family.formats.len); + try std.testing.expectEqualStrings("modelopt-nvfp4", family.formats[0]); + }; + try std.testing.expect(found); +} From dc2ca8a1785df6ee5c8489ee7cd18e29cf7b4568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:09:47 +0100 Subject: [PATCH 27/84] inkling2: Mini prompt-cache states (C4d) and the experts' round_caps A/B switch Prompt-cache states: - A stream's state at a prompt mark holds each of the 48 visits' K and V: the full caches through the mark, and the sliding rings' last 1,023 positions. It also holds every visit's four conv states. - The states are saved and restored through the native store's snap_* hooks. - tf-cuda-test checks restored == fresh bit-equal. Its planted control restores another prompt's state and goes red. The round_caps A/B switch: - experts.Layer.round_caps rounds the gate and up sums to bf16 before Inkling's soft caps, in the EPI 4 epilogue (a negative up cap). It is off by default and the default bits are unchanged. - The float64 reference and the tests take INKLING2_ROUND_CAPS=1. - On the tiny checkpoint it does not close the one CUDA-vs-Metal top-1 difference outside Metal's tie list. --- zig/build/cuda_kernels.zig | 2 +- zig/kernels/cuda/experts.cuh | 9 +- zig/src/cuda/experts.zig | 1 + zig/src/cuda/experts_mx.zig | 9 +- zig/src/families/inkling2/inkling2.zig | 2 + zig/src/families/inkling2/mini_backend.zig | 46 ++++++++- zig/src/families/inkling2/mini_native.zig | 25 +++++ zig/src/families/inkling2/mini_ref.zig | 14 ++- zig/src/families/inkling2/mini_snap.zig | 112 +++++++++++++++++++++ zig/src/families/inkling2/mini_weights.zig | 5 + zig/tests/cuda/inkling2_mini_tests.zig | 38 ++++++- zig/tests/cuda/inkling2_mini_xcheck.zig | 4 +- 12 files changed, 255 insertions(+), 12 deletions(-) create mode 100644 zig/src/families/inkling2/mini_snap.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index ae45152b916..1b5a2351c63 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -164,7 +164,7 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_pattn", .src = "inkling2/prompt_attention", .flags = &.{"-O3"} }, // ours: Inkling 2's global-layer prompt attention .{ .name = "inkling2_ops", .src = "inkling2/ops", .flags = glue }, // ours: Inkling 2's residual mix, convs, router, SwiGLU .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows - .{ .name = "inkling2_loop", .src = "inkling2/loop", .flags = glue }, // ours: Inkling 2 Mini's loop messages and gates + .{ .name = "inkling2_loop", .src = "inkling2/loop", .flags = glue }, // Inkling 2 Mini: loop messages, gates .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family .{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5 .{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts diff --git a/zig/kernels/cuda/experts.cuh b/zig/kernels/cuda/experts.cuh index 30656262d6f..b31b4ed7eaa 100644 --- a/zig/kernels/cuda/experts.cuh +++ b/zig/kernels/cuda/experts.cuh @@ -88,8 +88,13 @@ __device__ __forceinline__ void epilogue(const float (&acc)[M][RT][NTW][4], int o0 = swiglu(a0, acc[M - 1][r][j][2 * h], limit); o1 = swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit); } else if constexpr (EPI == 4) { // limit and limit2: the gate's and the up's caps - o0 = softcap_swiglu(a0, acc[M - 1][r][j][2 * h], limit, limit2); - o1 = softcap_swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit, limit2); + if (limit2 < 0.f) { // an A/B switch (round_caps): gate and up rounded to bf16 before the caps + o0 = softcap_swiglu(bf(a0), bf(acc[M - 1][r][j][2 * h]), limit, -limit2); + o1 = softcap_swiglu(bf(a1), bf(acc[M - 1][r][j][2 * h + 1]), limit, -limit2); + } else { + o0 = softcap_swiglu(a0, acc[M - 1][r][j][2 * h], limit, limit2); + o1 = softcap_swiglu(a1, acc[M - 1][r][j][2 * h + 1], limit, limit2); + } } else { o0 = a0; o1 = a1; diff --git a/zig/src/cuda/experts.zig b/zig/src/cuda/experts.zig index e4b51cc85a0..0bd9a297469 100644 --- a/zig/src/cuda/experts.zig +++ b/zig/src/cuda/experts.zig @@ -35,6 +35,7 @@ pub const Layer = struct { relu2: bool = false, // nvfp4: up is one projection under relu^2 (Nemotron), not SwiGLU's gate and up; iq2xxs: always swiglu: bool = false, // affine4: up is gate and up interleaved per group ([E][NI/32][D/64][2][288]) under SwiGLU caps: [2]f32 = .{ 0, 0 }, // nvfp4, mxfp8: Inkling's soft-capped SwiGLU (gate cap, up cap); 0, 0 for none + round_caps: bool = false, // with caps: gate and up sums rounded to bf16 before the soft cap (an A/B switch) shared: i32 = -1, // affine3: the expert whose tables are 4-bit (a SwiGLU pair at shared_up, down at shared_down) shared_up: u64 = 0, shared_down: u64 = 0, diff --git a/zig/src/cuda/experts_mx.zig b/zig/src/cuda/experts_mx.zig index 9d8f069f740..eb25c5847fc 100644 --- a/zig/src/cuda/experts_mx.zig +++ b/zig/src/cuda/experts_mx.zig @@ -48,6 +48,11 @@ pub fn splitGateUp(rows: []const u8, row_bytes: usize, gate: []u8, up: []u8) voi } } +/// The caps as the kernels take them: a negative up cap asks for gate and up rounded to bf16 first (round_caps). +pub fn kernelCaps(l: Layer) [2]f32 { + return .{ l.caps[0], if (l.round_caps) -l.caps[1] else l.caps[1] }; +} + /// An expert call's arguments as the soft-capped and MXFP8 entries take them; `scale` null for MXFP8 (in its blocks). pub fn argsOf(in: Rows, gate: bool, w: u64, scale: ?u64, kg: usize, nb: usize, p: Plan, out: u64, n: usize, caps: [2]f32, skip: i32) launch_.Args { var a: launch_.Args = .{}; @@ -85,7 +90,7 @@ pub const Softcap = struct { /// Gate-up on a plan of at most `items` items (16 pairs decode, 64 prompt); capsBuilt checked the layer. pub fn run(c: Softcap, s: Stream, prompt: bool, in: Rows, l: Layer, p: Plan, out: u64, items: usize, skip: i32) !void { const nb = l.width / 32; - var a = argsOf(in, true, l.up, l.up_scale, l.dims / 32, nb, p, out, l.width, l.caps, skip); + var a = argsOf(in, true, l.up, l.up_scale, l.dims / 32, nb, p, out, l.width, kernelCaps(l), skip); const grid = if (prompt) items * ((nb + prompt_wn - 1) / prompt_wn) else @min((items * nb + 3) / 4, c.resident); if (grid < 1) return; const smem: u32 = if (prompt) experts.Nvfp4Experts.promptSmem(2, prompt_wn) else 0; @@ -139,7 +144,7 @@ pub const Mxfp8Experts = struct { if (prompt and nb % cw != 0) return error.UnexpectedShape; const grid = if (prompt) items * (nb / cw) else @min((items * nb + 3) / 4, e.resident[fi]); if (grid < 1) return; - var a = argsOf(in, gate, if (gate) l.up else l.down, null, k / 32, nb, p, out, n, l.caps, skip); + var a = argsOf(in, gate, if (gate) l.up else l.down, null, k / 32, nb, p, out, n, kernelCaps(l), skip); try launch_.launch(e.fns[fi], .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, s, &a); } diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 406229b020b..4eb8cedc801 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -10,6 +10,7 @@ pub const loop = @import("loop.zig"); pub const mini_weights = @import("mini_weights.zig"); pub const mini_model = @import("mini_model.zig"); pub const mini_backend = @import("mini_backend.zig"); +pub const mini_snap = @import("mini_snap.zig"); /// The float64 reference the CUDA forward's greedy tokens are checked against. pub const mini_ref = @import("mini_ref.zig"); /// The native CUDA registry's entry for inkling2_loop (native/cuda_families.zig). @@ -28,6 +29,7 @@ test { _ = @import("mini_visit.zig"); _ = mini_weights; _ = mini_backend; + _ = mini_snap; _ = mini_ref; _ = native; } diff --git a/zig/src/families/inkling2/mini_backend.zig b/zig/src/families/inkling2/mini_backend.zig index f1ab895e3e6..daf81aca079 100644 --- a/zig/src/families/inkling2/mini_backend.zig +++ b/zig/src/families/inkling2/mini_backend.zig @@ -5,6 +5,7 @@ const std = @import("std"); const cuda = @import("cuda"); const lanes = @import("lanes"); const mm = @import("mini_model.zig"); +const snap = @import("mini_snap.zig"); const be = lanes.backend; const Stream = lanes.Stream; @@ -207,23 +208,62 @@ pub const Mini = struct { l.sampled = true; } s.cached = 0; - l.fill = 0; - s.fill_at.store(0, .monotonic); + l.fill = x.resumeAt(s, l, p.len); + s.fill_at.store(@intCast(l.fill.?), .monotonic); return l; } + /// The kept state's position, restored into the slot (0: none, not this prompt's, or another plan's). + fn resumeAt(x: *Mini, s: *Stream, l: *const Lane, len: usize) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const snap.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= len) { + s.reuse_failed = true; + return 0; + } + snap.restore(x.m, x.s, l.slot, k) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = k.at; + return k.at; + } + + /// The prompt pass stands at `at` (a chunk start or a mark): copy the stream's state there. + pub fn saveState(x: *Mini, owner: ?*anyopaque, at: u32) !*snap.Saved { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + if ((l.fill orelse l.len) != at) return error.NotAtMark; // a state is copied only where the pass stands + return snap.save(x.gpa, x.m, x.s, l.slot, at); + } + + pub fn restoreState(x: *Mini, owner: ?*anyopaque, k: *const snap.Saved) !void { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + try snap.restore(x.m, x.s, l.slot, k); + l.len = k.at; + } + + pub fn dropState(x: *Mini, k: *snap.Saved) void { + snap.drop(x.gpa, x.s, k); + } + /// One chunk from `l.fill`; true once the prompt's last row is in. fn chunk(x: *Mini, s: *Stream, l: *Lane) !bool { const p = s.prompt(); const at = l.fill.?; if (s.isCancelled()) return error.Cancelled; - const end = @min(p.len, (at / prompt_rows + 1) * prompt_rows); + var end = @min(p.len, (at / prompt_rows + 1) * prompt_rows); + for (s.reuse.marks) |mk| if (mk > at and mk < end) { + end = mk; + }; const done = end == p.len; try x.m.forward(x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..end] }}, true, end - at - 1, @intFromBool(done)); if (done) try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.s.logits, x.vocab() * 4, x.s.handle), "cuMemcpyDtoDAsync"); s.fill_at.store(@intCast(end), .monotonic); l.fill = if (done) null else end; if (done) l.len = p.len; + if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); return done; } diff --git a/zig/src/families/inkling2/mini_native.zig b/zig/src/families/inkling2/mini_native.zig index 2ed404d1c1d..7e2b8bb04e4 100644 --- a/zig/src/families/inkling2/mini_native.zig +++ b/zig/src/families/inkling2/mini_native.zig @@ -6,6 +6,7 @@ const lanes = @import("lanes"); const wts = @import("mini_weights.zig"); const mm = @import("mini_model.zig"); const be = @import("mini_backend.zig"); +const snap = @import("mini_snap.zig"); pub const model_type = "inkling2_loop"; pub const formats: []const []const u8 = &.{"modelopt-nvfp4"}; @@ -15,6 +16,8 @@ pub const prompt_rows: u32 = be.prompt_rows; pub const takes_drafter = false; pub const drafter_refusal = "--drafter: Inkling 2 Mini on CUDA serves plain decode so far; its DSpark drafter is the next slice (C5)"; pub const explains_open = true; +/// A kept state is the caches and conv states through its position, nothing past it (no draft head reads on). +pub const snap_lookahead: u32 = 0; /// The server's reading of the room left after the weights; null if unreadable. pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; @@ -106,6 +109,28 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ }; } +fn mini(ptr: *anyopaque) *be.Mini { + return @ptrCast(@alignCast(ptr)); +} + +/// Bytes a state at `at` prompt tokens takes. +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + return snap.bytes(mini(ptr).m, at); +} + +/// The prompt pass stands at `at` (a chunk start or a mark): copy the stream's state there. +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try mini(ptr).saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return mini(ptr).restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + mini(ptr).dropState(@ptrCast(@alignCast(saved))); +} + /// Whether a request's caches could start now (the lane host's admission, on its engine thread). pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { const own: *const Owned = @ptrCast(@alignCast(p)); diff --git a/zig/src/families/inkling2/mini_ref.zig b/zig/src/families/inkling2/mini_ref.zig index 144e30dd5ac..8a9038fc4e8 100644 --- a/zig/src/families/inkling2/mini_ref.zig +++ b/zig/src/families/inkling2/mini_ref.zig @@ -53,6 +53,13 @@ fn sigmoid(x: f64) f64 { return 1.0 / (1.0 + @exp(-x)); } +/// x rounded to bf16 (via f32, nearest-even), back in f64. +fn bf16Round(x: f64) f64 { + const u: u32 = @bitCast(@as(f32, @floatCast(x))); + const r = (u + 0x7fff + ((u >> 16) & 1)) & 0xffff0000; + return @as(f32, @bitCast(r)); +} + fn mat2(a: std.mem.Allocator, n: usize, w: usize) ![][]f64 { const x = try a.alloc([]f64, n); for (x) |*row| row.* = try a.alloc(f64, w); @@ -128,6 +135,7 @@ pub const Ref = struct { c: config.Config, p: plan_.Plan, ck: *Checkpoint, + round_caps: bool = false, // gate and up rounded to bf16 before the soft caps (the experts' round_caps A/B) plant: bool = false, // a planted control: the cross-pass messages dropped (the check must then go red) fn get(r: *Ref, comptime fmt: []const u8, args: anytype) !Tensor { @@ -380,7 +388,11 @@ pub const Ref = struct { const sc13 = s13.bytes[e * (s13.bytes.len / t.experts) ..][0 .. s13.bytes.len / t.experts]; for (0..m) |j| { var gu: [2]f64 = .{ 0, 0 }; - for (0..2) |half| gu[half] = expertDot(nv, c13, sc13, h, 2 * j + half, x) * f13; // rows interleave gate, up + // w13's rows interleave gate and up + for (0..2) |half| gu[half] = expertDot(nv, c13, sc13, h, 2 * j + half, x) * f13; + if (r.round_caps) for (&gu) |*g| { + g.* = bf16Round(g.*); + }; act[j] = sigmoid(gu[0]) * t.gate_cap * std.math.tanh(gu[0] / t.gate_cap) * t.up_cap * std.math.tanh(gu[1] / t.up_cap); } const c2 = w2.bytes[e * (w2.bytes.len / t.experts) ..][0 .. w2.bytes.len / t.experts]; diff --git a/zig/src/families/inkling2/mini_snap.zig b/zig/src/families/inkling2/mini_snap.zig new file mode 100644 index 00000000000..35688a86a5a --- /dev/null +++ b/zig/src/families/inkling2/mini_snap.zig @@ -0,0 +1,112 @@ +//! A stream's state at a prompt position (the prompt cache's copy): the 48 visits' K and V, the full ones through +//! `at` and the sliding rings' last 1,023 positions, and every visit's four conv states. Nothing else carries over +//! between forwards: blocks, bank and messages are each forward's own. +const std = @import("std"); +const cuda = @import("cuda"); +const mm = @import("mini_model.zig"); + +/// A kept state: the copied rows and conv states in `buf`, in `each`'s order. +pub const Saved = struct { + at: u32, + visits: u32, // the plan's visit count it was made under (a state never crosses plans) + buf: cuda.DeviceBuffer, +}; + +/// Positions a sliding ring keeps at `at`: a later row reads keys from its position - window + 1 on. +pub fn tail(window: usize, at: usize) usize { + return @min(at, window - 1); +} + +fn rowBytes(m: *const mm.Model) usize { + return @as(usize, m.c.local.dim) * 2; +} + +fn convWidth(m: *const mm.Model, site: mm.Site) usize { + return if (site == .k or site == .v) @as(usize, m.c.local.kv) * m.c.local.dim else m.c.hidden; +} + +/// Each copy of `slot`'s state at `at`, in order: per visit K then V, each head's kept positions in runs of +/// consecutive ring rows; then the visit's four conv states ([3][C] fp32). +pub fn each(m: *const mm.Model, slot: usize, at: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { + const rb = rowBytes(m); + const kvh: usize = m.c.local.kv; + var off: usize = 0; + for (m.w.plan.visits.slice(), 0..) |step, v| { + const full = step.of(.full) != null; + const len: usize = if (full) m.full.ring else m.sliding.ring; + const from = if (full) 0 else at - tail(m.c.window, at); + for (0..2) |side| for (0..kvh) |h| { + const base = m.kv[side][v] + ((slot * kvh + h) * len) * rb; + var p = from; + while (p < at) { + const row = p % len; + const run = @min(at - p, len - row); + try f(ctx, base + row * rb, off, run * rb); + off += run * rb; + p += run; + } + }; + for (std.enums.values(mm.Site)) |site| { + const n = 3 * convWidth(m, site) * 4; + try f(ctx, m.conv[v][@intFromEnum(site)] + slot * n, off, n); + off += n; + } + } +} + +const Count = struct { + n: *usize, + fn add(c: Count, _: u64, _: usize, len: usize) anyerror!void { + c.n.* += len; + } +}; + +/// Bytes a state at `at` takes. +pub fn bytes(m: *const mm.Model, at: usize) u64 { + var n: usize = 0; + each(m, 0, at, Count{ .n = &n }, Count.add) catch unreachable; + return n; +} + +const Copy = struct { + m: *const mm.Model, + s: cuda.Stream, + buf: u64, + out: bool, // slot -> buf (save), else buf -> slot (restore) + fn copy(c: Copy, dev: u64, off: usize, len: usize) anyerror!void { + const src = if (c.out) dev else c.buf + off; + const dst = if (c.out) c.buf + off else dev; + try c.m.d.check(c.m.d.api.cuMemcpyDtoDAsync_v2(dst, src, len, c.s.handle), "cuMemcpyDtoDAsync"); + } +}; + +/// Copy `slot`'s state at `at` into new storage, queued on `s` behind the chunk that ends there. +pub fn save(gpa: std.mem.Allocator, m: *const mm.Model, s: cuda.Stream, slot: usize, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .visits = @intCast(m.w.plan.visits.len), .buf = try cuda.DeviceBuffer.alloc(m.d, @max(bytes(m, at), 256)) }; + errdefer k.buf.free(); + try each(m, slot, at, Copy{ .m = m, .s = s, .buf = k.buf.ptr, .out = true }, Copy.copy); + return k; +} + +/// Make `slot` hold `k`'s state, queued on `s` before the next chunk; a state of another plan is refused. +pub fn restore(m: *const mm.Model, s: cuda.Stream, slot: usize, k: *const Saved) !void { + if (k.visits != m.w.plan.visits.len) return error.Inkling2StateOfAnotherPlan; + if (k.at > m.context) return error.PastContext; + try each(m, slot, k.at, Copy{ .m = m, .s = s, .buf = k.buf.ptr, .out = false }, Copy.copy); +} + +/// Free a state once the stream's queued copies of it are done. +pub fn drop(gpa: std.mem.Allocator, s: cuda.Stream, k: *Saved) void { + s.synchronize() catch {}; + k.buf.free(); + gpa.destroy(k); +} + +test "a sliding ring keeps the window less one before the next row; short prompts all of theirs" { + try std.testing.expectEqual(@as(usize, 1023), tail(1024, 5000)); + try std.testing.expectEqual(@as(usize, 300), tail(1024, 300)); + try std.testing.expectEqual(@as(usize, 1023), tail(1024, 1023)); +} diff --git a/zig/src/families/inkling2/mini_weights.zig b/zig/src/families/inkling2/mini_weights.zig index 89fb777a64d..ecdd32f87e4 100644 --- a/zig/src/families/inkling2/mini_weights.zig +++ b/zig/src/families/inkling2/mini_weights.zig @@ -16,6 +16,11 @@ const Tensor = core.checkpoint.Tensor; /// NVFP4's outer scale denominator as Mini ships it (scales/RESULTS.md); another value is refused. pub const nvfp4_denominator = 2688; +/// The experts' round_caps A/B switch on every layer: gate and up rounded to bf16 before the soft caps. +pub fn roundCaps(w: *Weights, on: bool) void { + for (w.layers) |*l| l.experts.round_caps = on; +} + /// One packed buffer a layer, rows [q | gate | rel | sink padded to 64 | k | v]: views of it, every one at the /// parts' own K slices (one count for all six, else refused), so a fused product's rows carry the separate bits. pub const Fused = struct { diff --git a/zig/tests/cuda/inkling2_mini_tests.zig b/zig/tests/cuda/inkling2_mini_tests.zig index 71662a4a05b..43bb5fdfb34 100644 --- a/zig/tests/cuda/inkling2_mini_tests.zig +++ b/zig/tests/cuda/inkling2_mini_tests.zig @@ -20,6 +20,7 @@ pub const Rig = struct { r.gpu = gpu; r.w = try ink.mini_weights.load(gpu.gpa, gpu.io, gpu.d, model); errdefer r.w.deinit(); + ink.mini_weights.roundCaps(&r.w, roundCaps()); r.k = try mm.Kernels.load(gpu.ctx); errdefer r.k.deinit(); r.s = try cuda.Stream.init(gpu.d, false); @@ -65,6 +66,12 @@ pub const Rig = struct { } }; +/// INKLING2_ROUND_CAPS=1: the experts' gate and up rounded to bf16 before the soft caps (engine and reference). +pub fn roundCaps() bool { + const v = std.c.getenv("INKLING2_ROUND_CAPS") orelse return false; + return std.mem.eql(u8, std.mem.span(v), "1"); +} + pub fn argmax(x: []const f32) u32 { var best: usize = 0; for (x, 0..) |v, i| if (v > x[best]) { @@ -131,9 +138,38 @@ pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8, text: []const u8 } try check.expect(bad == 0, "inkling2 mini resumed == fresh: {d} chunkings differ", .{bad}); try graphs(&rig, ids, first, plain); + try snapshots(&rig, ids, first); try concurrent(&rig, ids, plain); } +/// A prompt-cache state saved mid-prompt in slot 0, restored into slot 1, the rest prefilled there: the last row's +/// logits bit-equal to the fresh pass. Planted: a state of another prompt restored instead must differ. +fn snapshots(rig: *Rig, ids: []const u32, first: []const f32) !void { + const gpa = rig.gpu.gpa; + const snap = ink.mini_snap; + const mid: u32 = @intCast(ids.len / 2); + gpa.free(try rig.prompt(0, ids[0..mid], 0, mm.prompt_rows)); + const k = try snap.save(gpa, &rig.m, rig.s, 0, mid); + defer snap.drop(gpa, rig.s, k); + // the planted control: slot 0 refilled with another prefix (the ids reversed) and its state restored + const other = try gpa.alloc(u32, mid); + defer gpa.free(other); + for (other, 0..) |*o, i| o.* = ids[mid - 1 - i]; + gpa.free(try rig.prompt(0, other, 0, mm.prompt_rows)); + const wrong = try snap.save(gpa, &rig.m, rig.s, 0, mid); + defer snap.drop(gpa, rig.s, wrong); + var same: [2]bool = undefined; + for ([_]*const snap.Saved{ wrong, k }, 0..) |state, i| { + try snap.restore(&rig.m, rig.s, 1, state); + const got = try rig.prompt(1, ids[mid..], mid, mm.prompt_rows); + defer gpa.free(got); + same[i] = std.mem.eql(u8, std.mem.sliceAsBytes(got), std.mem.sliceAsBytes(first)); + } + try check.expect(!same[0], "inkling2 mini planted control: another prompt's state restored gives the fresh logits", .{}); + try check.expect(same[1], "inkling2 mini snapshot: restored at {d} != fresh", .{mid}); + check.pass("inkling2 mini prompt-cache state at {d} of {d} ({d} bytes): restored == fresh bit-equal; planted (another prompt's state) red", .{ mid, ids.len, snap.bytes(&rig.m, mid) }); +} + /// The decode graphs against direct launches: the first step's logits bit-equal, then 32 greedy tokens equal. fn graphs(rig: *Rig, ids: []const u32, first: []const f32, plain: []const u32) !void { const gpa = rig.gpu.gpa; @@ -219,7 +255,7 @@ pub fn reference(gpu: Gpu, model: []const u8, count_text: []const u8, text: []co defer ck.close(); // INKLING2_REF_PLANT=1: the reference drops the cross-pass messages; the check must go red const plant = if (std.c.getenv("INKLING2_REF_PLANT")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; - var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck, .plant = plant }; + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck, .plant = plant, .round_caps = roundCaps() }; const picks = try gpa.alloc(ink.mini_ref.Pick, all.len); defer gpa.free(picks); const t0 = check.now(gpu.io); diff --git a/zig/tests/cuda/inkling2_mini_xcheck.zig b/zig/tests/cuda/inkling2_mini_xcheck.zig index 0d09b54c090..b582dda75d3 100644 --- a/zig/tests/cuda/inkling2_mini_xcheck.zig +++ b/zig/tests/cuda/inkling2_mini_xcheck.zig @@ -70,7 +70,7 @@ pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8) !void { defer rig.deinit(); var ck = try core.checkpoint.Checkpoint.openModel(gpa, gpu.io, model); defer ck.close(); - var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck }; + var r: ink.mini_ref.Ref = .{ .gpa = gpa, .c = rig.w.config, .p = rig.w.plan, .ck = &ck, .round_caps = tests.roundCaps() }; const v = rig.w.config.text.unpadded_vocab; var disagree: usize = 0; for (prompts) |pr| { @@ -106,7 +106,7 @@ pub fn run(gpu: Gpu, model: []const u8, count_text: []const u8) !void { defer buf.deinit(gpa); var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, &buf); const w = &aw.writer; - try w.print("{{\"prompt\":\"{s}\",\"forced\":{},\"ids\":", .{ pr.name, forced != null }); + try w.print("{{\"prompt\":\"{s}\",\"forced\":{},\"round_caps\":{},\"ids\":", .{ pr.name, forced != null, tests.roundCaps() }); try ids(w, pr.ids); try w.writeAll(",\"tokens\":"); try ids(w, all[n0..]); From cab35758fae989d89de76f874602fd88600e9830 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:59:28 +0800 Subject: [PATCH 28/84] Inkling 2 Mini on TOP: the run script finds the checkpoint first --- docs/recipes/inkling-2-mini-cuda/run-script.sh | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100755 docs/recipes/inkling-2-mini-cuda/run-script.sh diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh new file mode 100755 index 00000000000..129f994bb8f --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# Inkling 2 Mini (thinkingmachines/Inkling-2-Mini, revision ed40e7da62) whole on TOP's GB10: +# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/run-script.sh +# The job has no network: the checkpoint has to be in the pilot folder first, put there by the Desk: +# tar -C MODELS -c Inkling-2-Mini | ssh top-menu "put top models/Inkling-2-Mini" +set -eu +pilot=/assets/drama3-pilot +model=$pilot/models/Inkling-2-Mini +if [ ! -f "$model/config.json" ]; then + echo "missing $model/config.json; the pilot's models and any Inkling config:" >&2 + ls "$pilot/models" >&2 || true + find /assets -maxdepth 5 -name config.json -exec grep -l '"inkling2' {} + >&2 || true + exit 1 +fi +nvidia-smi --query-gpu=name,driver_version,memory.used --format=csv,noheader From d933489c58ab596713b51771b04a624028556649 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:39:43 +0800 Subject: [PATCH 29/84] Inkling 2 Mini: what differs on RTX Spark and what must change to build there --- docs/recipes/inkling-2-mini-cuda/README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 docs/recipes/inkling-2-mini-cuda/README.md diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md new file mode 100644 index 00000000000..4e68ed41e88 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -0,0 +1,20 @@ +# Inkling 2 Mini on TOP's GB10 + +`run-script.sh` runs thinkingmachines/Inkling-2-Mini (revision `ed40e7da62`) whole on TOP's Spark through the Desk's +GPU door. The job has no network, so the checkpoint must already sit in the pilot folder as +`models/Inkling-2-Mini`; the script refuses and lists what `/assets` holds when it does not. + +## RTX Spark (N1X): what differs and what must change + +I see the same chip and memory model as the GB10: sm_121 and one unified pool, so the `-Dsm=121` kernel images are +the same. What differs is the host. RTX Spark runs Windows on Arm, with WSL2 as the +Linux route. From #1010 (`5b1f10812`) and #2107: + +- Native Windows builds as `aarch64-windows` with VS 2022 Build Tools' ARM64 C++ tools (`vcvarsall arm64`) as nvcc's + host compiler and the CUDA 13.4 `windows-arm64` redistributables (winget has no arm64 installer). Admission reads the + WDDM pool through `cuMemGetInfo_v2`, and `nvidia-smi`'s NPU row is filtered out. +- Under WSL2 `/proc/meminfo` is WSL's RAM (about 30 GiB of 128 GB), not the GPU's 96 GB WDDM pool; with + `WSL_DISTRO_NAME` set, admission reads the CUDA pool instead (`TENSORFOLD_UNIFIED_HOST_COUNTS` overrides it). +- For Mini, I need three things before it builds and serves there: the Inkling CUDA kernels compiled by MSVC's + front end (only nvcc with gcc 14 has built them so far), one load of the 18.9 GiB single-shard checkpoint + through Windows' threaded reads, and the GB10's exactness checks repeated on the N1X. No N1X run of Mini exists yet. From 49a44d44ce33caae175d4654896e57f8d5ad4e8d Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:52:36 +0800 Subject: [PATCH 30/84] inkling2: size the retained engine plan to its layers Co-authored-by: jschmied <600316+jschmied@users.noreply.github.com> --- zig/src/families/inkling2/cuda_native.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig index 32bdecce4a8..10018b8df53 100644 --- a/zig/src/families/inkling2/cuda_native.zig +++ b/zig/src/families/inkling2/cuda_native.zig @@ -102,7 +102,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ var merged: core.safetensors.Header = .empty; for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); try @import("names.zig").precisions(merged, c.text.layers, &precisions); - const p = try plan_.build(&c.text, &precisions); + const p = try plan_.build(&c.text, precisions[0..c.text.layers]); var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); errdefer w.deinit(); if (ck.unused() != 0) return error.UnusedCheckpointTensor; From 7b83a968e7a2b7ff3522458eb52f60ffbeef7521 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:52:53 +0800 Subject: [PATCH 31/84] inkling2: upload each sliding attention norm once Co-authored-by: jschmied <600316+jschmied@users.noreply.github.com> --- zig/src/families/inkling2/loop_weights.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig index 3dbcba5e426..cd5cf841ee7 100644 --- a/zig/src/families/inkling2/loop_weights.zig +++ b/zig/src/families/inkling2/loop_weights.zig @@ -190,6 +190,7 @@ pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, .v_conv = undefined, .norms = undefined, }; + const sliding_norm: ?u64 = if (config.isGlobal(i)) null else try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}); inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { const conv = if (config.isGlobal(i)) try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) @@ -203,7 +204,7 @@ pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, const norm = if (config.isGlobal(i)) try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) else - try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}); + sliding_norm.?; layer.attn.norms[j + 1] = norm; } layer.attn.norms[0] = if (config.isGlobal(i)) From 2c43113f90bf269037ae3400634bb82e4ae952c7 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:53:04 +0800 Subject: [PATCH 32/84] inkling2: keep retained gate and sink projections raw Co-authored-by: jschmied <600316+jschmied@users.noreply.github.com> --- zig/src/families/inkling2/loop_engine.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig index f57d5f0040c..7b6d5201768 100644 --- a/zig/src/families/inkling2/loop_engine.zig +++ b/zig/src/families/inkling2/loop_engine.zig @@ -369,8 +369,8 @@ pub const Model = struct { const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, true); - try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, true); + try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, false); + try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, false); const geometry = m.layerGeometry(visit.layer); const cache = m.cacheOf(visit.of(.conv).?); From 58b0b228bde4f2da72d5c64295eac0308fb1cd85 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:06:10 +0800 Subject: [PATCH 33/84] inkling2: unify the merged host plan and module contracts --- zig/build/inkling2_host.zig | 6 ++++-- zig/build/metal_targets.zig | 4 ++++ zig/src/families/inkling2/config.zig | 10 +++++----- zig/src/families/inkling2/metal/state.zig | 4 ++-- zig/src/families/inkling2/mini_host_test.zig | 2 +- zig/src/tensorfold.zig | 2 ++ zig/tests/fixtures/gradient-serving.tsv | 6 +++--- 7 files changed, 21 insertions(+), 13 deletions(-) diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index cb01183ed00..850c7a6530d 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -29,8 +29,10 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin const lanes = b.createModule(.{ .root_source_file = b.path(dir ++ "lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); m.addImport("lanes", lanes); m.addImport("engine_api", b.createModule(.{ .root_source_file = b.path(dir ++ "engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} })); - m.addImport("visit_plan", b.createModule(.{ .root_source_file = b.path(dir ++ "visit_plan.zig"), .target = target, .optimize = optimize })); - m.addImport("modelopt", b.createModule(.{ .root_source_file = b.path(dir ++ "modelopt_config.zig"), .target = target, .optimize = optimize, .link_libc = true })); + const parts = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/core_parts.zig"), .target = target, .optimize = optimize, .link_libc = true }); + parts.addImport("core", core); + m.addImport("visit_plan", parts); + m.addImport("modelopt", parts); return m; } diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index c3405fa0d0c..7663103726c 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -489,6 +489,10 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim engine.addImport("inkling2_metal_ref", inkling2_metal_ref); engine.addImport("inkling2_glue_plan", inkling2_glue_plan); engine.addImport("inkling2_loop_plan", inkling2_loop_plan); + const inkling2_parts = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/core_parts.zig"), .target = target, .optimize = optimize, .link_libc = true }); + inkling2_parts.addImport("core", engine); + engine.addImport("visit_plan", inkling2_parts); + engine.addImport("modelopt", inkling2_parts); engine.addImport("engram_hash_core", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize })); return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; } diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index 8c3db4b437d..193aeae7eb9 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -307,17 +307,17 @@ fn parseLoop(o: std.json.ObjectMap, t: *const Text, why: *Why) !Loop { return error.Unsupported; }; const l: Loop = .{ - .start = try int(o, "core_start", why), - .end = try int(o, "core_end", why), + .start = try index(o, "core_start", why), + .end = try index(o, "core_end", why), .passes = try int(o, "num_passes", why), .rank = try int(o, "gate_rank", why), }; if (l.start == 0 or l.start >= l.end or l.end > t.layers) { - why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers", .{ l.start, l.end, t.layers }); + why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers; bounds outside the backbone's first and last blocks are not whole blocks of {d}", .{ l.start, l.end, t.layers, t.block }); return error.Layout; } if (l.start % t.block != 0 or l.end % t.block != 0 or l.start != t.block or l.end + t.block != t.layers) { - why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, leaving its first and last blocks outside the loop", .{t.block}); + why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, not whole blocks of {d} outside its first and last blocks", .{ t.block, t.block }); return error.Layout; } if (l.passes < 2 or l.rank > max_gate_rank) { @@ -429,7 +429,7 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, why: *Why) !Config { const small = std.mem.eql(u8, name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, kind, "inkling2"); const looped = std.mem.eql(u8, name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, kind, "inkling2_loop"); if (!small and !looped) { - why.set("not an Inkling 2 checkpoint: Inkling2ForConditionalGeneration (inkling2) or Inkling2LoopForConditionalGeneration (inkling2_loop)", .{}); + why.set("not an Inkling 2 checkpoint: model_type and architectures must match Inkling2ForConditionalGeneration (inkling2) or Inkling2LoopForConditionalGeneration (inkling2_loop)", .{}); return error.NotInkling2; } try fixed(o, "tie_word_embeddings", false, why); diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index c58533f310b..415f3fbc087 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -115,7 +115,7 @@ pub const Cache = struct { }; var at: usize = 0; for (0..visit_slots) |slot| { - const global = schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global; + const global = schedule.at(schedule.visits.steps[slot].layer).kind == .global; const ring_size = if (global) globalSlots(capacity) else sliding_ring; out.globals[slot] = global; out.rings[slot] = @intCast(ring_size); @@ -187,7 +187,7 @@ pub const Cache = struct { pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { std.debug.assert(rows <= max_rows); - var layer = if (schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); + var layer = if (schedule.at(schedule.visits.steps[slot].layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); layer.ring = @intCast(c.ring(slot)); return layer; } diff --git a/zig/src/families/inkling2/mini_host_test.zig b/zig/src/families/inkling2/mini_host_test.zig index d86c3aad2ed..d8ffcf1b147 100644 --- a/zig/src/families/inkling2/mini_host_test.zig +++ b/zig/src/families/inkling2/mini_host_test.zig @@ -4,7 +4,7 @@ const std = @import("std"); const config = @import("config.zig"); const names = @import("names.zig"); const plan = @import("plan.zig"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const unfold = @import("names_test.zig").unfold; const t = std.testing; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 0564262ab38..03b9b24a51c 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -43,6 +43,8 @@ pub const affine_mm = @import("core/affine_mm.zig"); pub const moe_route = @import("core/moe_route.zig"); /// The checkpoint formats (MLX affine and its fp64 reader for the device checks, exact widen). pub const quant = @import("core/quant/quant.zig"); +pub const modelopt = @import("core/modelopt.zig"); +pub const visit_plan = @import("core/visit_plan.zig"); pub const exl3_format = @import("core/exl3_format.zig"); pub const exl3_projection = @import("core/exl3_projection.zig"); pub const exlr8 = @import("core/exlr8.zig"); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 7c4d88eaacb..5177fd7a454 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -6,7 +6,7 @@ zig/kernels/cuda/embed_rows.cu c3cad38db6576728a15e048a45f2c1a571233fc3fedc83d04 zig/kernels/cuda/exlr8.cu 0eb19c8965aeb8188efd2b15a5844da860d9bf75364b12b62dd3a2589a89178c raw zig/kernels/cuda/exlr8_dense.cu 7616e7a3bb35a2bb64b53a1ca84ce8be98442a36394dad945b844219f72ec671 raw zig/kernels/cuda/experts.cu 2a9b3989f3baaef5eadb56abfb8520700449bd910f2b00345703c22dbf758b8c raw -zig/kernels/cuda/experts.cuh 1cc91e62a72beef4a11c538bbf411dfd8f037c1310c4de4f6721e542504dc660.raw Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged; #4441 C4d: experts' round_caps A/B switch +zig/kernels/cuda/experts.cuh 1cc91e62a72beef4a11c538bbf411dfd8f037c1310c4de4f6721e542504dc660 raw Inkling 2 Mini C3: additive soft-capped and MXFP8 entries, SASS of every existing function unchanged; #4441 C4d: experts' round_caps A/B switch zig/kernels/cuda/experts_pack.cu 578e9a607f678f0547aaeb312d18252ea0608bad7fe71bb2d5241d28adf31bac raw zig/kernels/cuda/experts_prefill.cu 5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc raw zig/kernels/cuda/experts_rows.cu 714b76ad72ff45715c5ebf6b57365f0f41789ad301871f07168a016412df13a7 raw @@ -89,11 +89,11 @@ zig/src/cuda/cublaslt.zig d87f865fc03cf94bdcbe83504f74a6e569d70c10ca792b675122e9 zig/src/cuda/driver.zig f20856bd06afe9365ab9ca1bc39800ccb260ade2704197c033e1344a0c8dd742 raw commits e9bf05ffd, b923e554c, b2c75a98a; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/embed_rows.zig 3fa5e28ab46b4daef2c820b3ad3f7d331bc77f55ea340a7a3cac64b21584c5f4 raw #3471: Gemma 4 holds its tied embedding once; token rows read the head's 4-bit tiles; replies unchanged zig/src/cuda/exlr8.zig 1e2164096ae949a8a9a4903df82c7c0c184a6f5e1ba5ba4423038a42b0633fc6 raw -zig/src/cuda/experts.zig 3c02d147eff2053efb805faff7c9434df2eaf50883a5f85f2a3215e803763731.raw main 3768bc0168 (#2843: grouped EXL3 experts launched and sized at the caller's tile and pair count; no kernel source change), #1630 (a bf16 format: its Grouped member, decode and prompt arms and prompt tile; other formats unchanged); Inkling 2 Mini C3: additive MXFP8 format and soft-capped dispatch (experts_mx.zig); existing calls unchanged; #4441 C4d: experts' round_caps A/B switch +zig/src/cuda/experts.zig 3c02d147eff2053efb805faff7c9434df2eaf50883a5f85f2a3215e803763731 raw main 3768bc0168 (#2843: grouped EXL3 experts launched and sized at the caller's tile and pair count; no kernel source change), #1630 (a bf16 format: its Grouped member, decode and prompt arms and prompt tile; other formats unchanged); Inkling 2 Mini C3: additive MXFP8 format and soft-capped dispatch (experts_mx.zig); existing calls unchanged; #4441 C4d: experts' round_caps A/B switch zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 3be92a6a0d47152a5d8eea1be0d42964607bab8541c12ff8bf435a5a91652801.raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #4441 C4d: inkling2_loop image registered +zig/src/cuda/kernels.zig 3be92a6a0d47152a5d8eea1be0d42964607bab8541c12ff8bf435a5a91652801 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #4441 C4d: inkling2_loop image registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw From 1a56f10e57d61188058f3dbf6243065d5bd00c7a Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:07:40 +0800 Subject: [PATCH 34/84] inkling2: complete native inventory and prompt-cache registration --- zig/metal_runtime_inventory.zig | 2 +- zig/src/core/profile.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/metal_runtime_inventory.zig b/zig/metal_runtime_inventory.zig index bb45f0fe19c..376206c94e6 100644 --- a/zig/metal_runtime_inventory.zig +++ b/zig/metal_runtime_inventory.zig @@ -1,6 +1,6 @@ //! Source assembly shares one module owner with the engine's family and core files. pub const metal_runtime_sources = @import("runtime_sources/root.zig"); -const engine = @import("src/tensorfold.zig"); +const engine = @import("core"); pub const gpu_profile = engine.gpu_profile; pub const sys = @import("sys"); pub const rope_freq = engine.rope_freq; diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 39570f0ac41..430b0ab5413 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -140,7 +140,7 @@ const nemotron: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni" }; const slide_cuda: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "qwen3_5" }; const flash: []const []const u8 = &.{"qwen4_exp"}; /// The CUDA families whose host prompt cache the generic CUDA host builds (cuda_keep_others_test.zig checks the list). -pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark" }; +pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark", "inkling2_loop" }; pub const entries = [_]Entry{ .{ .id = .TF_CACHE_EVICT, .families = cuda_cache, .backend = "multiple", .scopes = &.{ .{ .backend = "cuda", .families = cuda_cache }, .{ .backend = "metal", .families = &.{ "nemotron_h", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "glm5_next", "glm_moe_dsa", "minimax_m3_vl", "gemma4", "gemma4_unified", "spark2_5", "llama", "lfm2_moe", "lfm3", "lfm3_vl", "step5_vl", "kimi_k3", "kimi_k31" } }, .{ .backend = "xpu", .families = &.{ "nemotron_h", "lfm3", "qwen3_5", "gemma4" } } }, .class = .experimental, .syntax = .present, .report_values = &.{"decayed_resume"}, .effect = "Opt into bounded resume credit for RAM snapshot eviction", .evidence = "#3241; synthetic host rows gate; default main unchanged" }, From 87a27b6c91985569005c95a7b1c93c2c578c11be Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:09:25 +0800 Subject: [PATCH 35/84] inkling2: port native checkpoint loading to current core exports --- zig/qwen27_core.zig | 1 + zig/src/families/inkling2/metal/model.zig | 2 +- zig/src/tensorfold.zig | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index 916ceeaa248..89302dbfe62 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -2,6 +2,7 @@ pub const checkpoint = @import("src/core/checkpoint.zig"); pub const gguf = @import("src/core/gguf.zig"); pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); +pub const checkpoint_file_cache = @import("src/core/checkpoint_file_cache.zig"); pub const safetensors = @import("src/core/safetensors.zig"); pub const Checkpoint = checkpoint.Checkpoint; pub const npy = @import("src/core/npy.zig"); diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig index efec8b28816..bed9a8af710 100644 --- a/zig/src/families/inkling2/metal/model.zig +++ b/zig/src/families/inkling2/metal/model.zig @@ -5,7 +5,7 @@ const sources = @import("kernel_sources"); const cfg = @import("../config.zig"); const layer_plan = @import("../plan.zig"); const ck = @import("../../../core/checkpoint_metal.zig"); -const shards = @import("core").checkpoint; +const shards = @import("core").checkpoint_host; const attention = @import("attention.zig"); const glue = @import("glue.zig"); const experts = @import("experts.zig"); diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 03b9b24a51c..a451ff6d8ae 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -10,6 +10,7 @@ pub const wav = @import("core/wav.zig"); pub const gguf = @import("core/gguf.zig"); pub const Checkpoint = checkpoint_host.Checkpoint; pub const checkpoint_host = @import("core/checkpoint.zig"); +pub const checkpoint_file_cache = @import("core/checkpoint_file_cache.zig"); pub const digest_cache = @import("core/digest_cache.zig"); pub const checkpoint_metal = checkpoint; pub const qwen27 = @import("families/qwen27/qwen27.zig"); From 7ff7dfe2f3c06bb9a1dfd9f589e23a845865dde2 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:19:15 +0800 Subject: [PATCH 36/84] Inkling 2 Mini on TOP: serving checks, float64 reference and 1/4-stream receipt in one job --- .../188-inkling-2-mini-runs-whole-on-our-spark-g.md | 7 +++++++ docs/recipes/inkling-2-mini-cuda/README.md | 6 ++++++ 2 files changed, 13 insertions(+) create mode 100644 changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md new file mode 100644 index 00000000000..45df25d327e --- /dev/null +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -0,0 +1,7 @@ +# Inkling 2 Mini on CUDA: upstream #4387 with jschmied's #4364, #4365 and #4441, and a whole-model run on TOP + +- Merges Ash's #4387 and jschmied's C1 (#4364), C3 (#4365) and H2 + C4 (#4441) with their commits; #4387's engine + serves `inkling2_loop`, with jschmied's three fixes (layer-sized plan, one sliding-norm upload, raw gate and sink). +- `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: #4387's serving + checks, the float64 reference and its planted control, then first-token time, prompt speed, decode speed and + memory at 1 and 4 streams. The recipe's README notes what RTX Spark (Windows and WSL2) needs. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 4e68ed41e88..0346d1f9c7e 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -4,6 +4,12 @@ GPU door. The job has no network, so the checkpoint must already sit in the pilot folder as `models/Inkling-2-Mini`; the script refuses and lists what `/assets` holds when it does not. +The server is #4387's engine (`inkling2.native`, model type `inkling2_loop`) with jschmied's three load and +attention fixes from his #4387 comments; #4441's engine (`inkling2.mini_native`) rides along for its float64 +reference. The script fails on any of: `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test +inkling2-mini-ref` (32 greedy tokens equal to the float64 host reference), that reference's planted control staying +green, or a failed stream in `tools/bench_concurrent.py` at 1 and 4 streams. + ## RTX Spark (N1X): what differs and what must change I see the same chip and memory model as the GB10: sm_121 and one unified pool, so the `-Dsm=121` kernel images are From 5994b00f6b15d6ef9a1fa7f893975e24be510ea6 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:46:50 +0800 Subject: [PATCH 37/84] lanes: compare opt-in lone keeps against main's default count, not a pinned zero --- zig/src/core/lanes/rollback_test.zig | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/zig/src/core/lanes/rollback_test.zig b/zig/src/core/lanes/rollback_test.zig index f4763e224d1..c482a89fb19 100644 --- a/zig/src/core/lanes/rollback_test.zig +++ b/zig/src/core/lanes/rollback_test.zig @@ -157,8 +157,9 @@ test "rollback: heads landing no draft, some or all commit the one-token decode, }; } -test "rollback: fully accepted lone keep is opt-in and preserves main's default call count" { - for ([_]bool{ false, true }) |enabled| { +test "rollback: fully accepted lone keep is opt-in and adds keeps over main's default" { + var calls: [2]usize = undefined; + for ([_]bool{ false, true }, &calls) |enabled, *n| { const r = try Rig.create(every, 0); defer r.destroy(); r.engine.backend.keep_full_lone = enabled; @@ -166,12 +167,9 @@ test "rollback: fully accepted lone keep is opt-in and preserves main's default try r.engine.addStream(s); _ = try r.finish(); try expectFresh(.{ .prompt = &p1, .max_new = 24 }, s); - if (enabled) { - try expect(r.target.keep_calls > 0); - } else { - try std.testing.expectEqual(@as(usize, 0), r.target.keep_calls); - } + n.* = r.target.keep_calls; } + try expect(calls[1] > calls[0]); } /// Steps of the uncancelled run of `reqs`, which bound where a cancel can land. From 3d5584c476809186c339be37663aed58b95ae12a Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:46:50 +0800 Subject: [PATCH 38/84] contract: Inkling 2's sm_121-only launches wait in cuda_pending for their other SMs' receipts --- zig/src/core/contract/inkling2_cuda_records.zig | 1 + zig/src/core/contract/inkling2_experts_records.zig | 3 +++ zig/src/core/contract/registry_joins.zig | 3 ++- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index b24f4ea1efe..27835f558bc 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -4,5 +4,6 @@ const ops = @import("inkling2_ops_records.zig"); const experts = @import("inkling2_experts_records.zig"); pub const cuda = attn.cuda ++ ops.cuda ++ experts.cuda; +pub const pending = experts.pending; pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ experts.cuda_132; pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ experts.cuda_133; diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 7e4277db00f..01452e97e89 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -10,6 +10,9 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_embed", .symbol = "tf_ink2v_embed", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, +}; +/// Measured on sm_121 alone (GB10, #4387): the other SMs' receipts are missing, so these refuse there (cuda_pending). +pub const pending = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index f53498e770c..6a82665f641 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -60,7 +60,8 @@ pub const cuda_pending = @import("qwen_whole_records.zig").records ++ @import("qwen4_records.zig").cuda ++ @import("registry_media.zig").cuda_pending ++ @import("registry_media.zig").cuda_tma_pending ++ - @import("h3_image_cuda_records.zig").records; + @import("h3_image_cuda_records.zig").records ++ + @import("inkling2_cuda_records.zig").pending; pub const metal_before = @import("fsr_records.zig").metal ++ @import("scale_index_records.zig").metal ++ @import("lfm3_records.zig").metal; From 4b8ed029341ec1004732cddc67ae2ccc7d5fd24a Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:47:18 +0800 Subject: [PATCH 39/84] gitleaks: #4365's stored-experts comment is prose, not a key --- .gitleaksignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitleaksignore b/.gitleaksignore index 0bccecc491b..f86b1e2bb41 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -2,3 +2,4 @@ 5be42d15e99da7a7197fbf1e618b62ab31a25ade:tools/zig/nemotron_parse_reference.py:generic-api-key:33 5be42d15e99da7a7197fbf1e618b62ab31a25ade:tools/zig/nemotron_parse_reference.py:generic-api-key:34 5be42d15e99da7a7197fbf1e618b62ab31a25ade:tools/zig/nemotron_parse_reference.py:generic-api-key:35 +913847b4d4a06c1cb380ba63c2156b0f621be34b:zig/tests/cuda/stored_experts_check.zig:generic-api-key:73 From 2e5361c8071611dc5ad87a1c206715004a96e5cd Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:39:51 +0800 Subject: [PATCH 40/84] Inkling 2 Mini on TOP: build, check and serve in the run script; the Desk's checkpoint path --- docs/recipes/inkling-2-mini-cuda/README.md | 4 +- .../recipes/inkling-2-mini-cuda/run-script.sh | 69 +++++++++++++++++-- 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 0346d1f9c7e..77cf85d5f5c 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -1,8 +1,8 @@ # Inkling 2 Mini on TOP's GB10 `run-script.sh` runs thinkingmachines/Inkling-2-Mini (revision `ed40e7da62`) whole on TOP's Spark through the Desk's -GPU door. The job has no network, so the checkpoint must already sit in the pilot folder as -`models/Inkling-2-Mini`; the script refuses and lists what `/assets` holds when it does not. +GPU door. The job has no network, so the checkpoint must already sit in the pilot folder as `Inkling-2-Mini` (or +`models/Inkling-2-Mini`); the script refuses and lists the Inkling configs under `/assets` when it does not. The server is #4387's engine (`inkling2.native`, model type `inkling2_loop`) with jschmied's three load and attention fixes from his #4387 comments; #4441's engine (`inkling2.mini_native`) rides along for its float64 diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh index 129f994bb8f..95f9b1acc0a 100755 --- a/docs/recipes/inkling-2-mini-cuda/run-script.sh +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -1,15 +1,72 @@ #!/bin/sh # Inkling 2 Mini (thinkingmachines/Inkling-2-Mini, revision ed40e7da62) whole on TOP's GB10: # swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/run-script.sh -# The job has no network: the checkpoint has to be in the pilot folder first, put there by the Desk: -# tar -C MODELS -c Inkling-2-Mini | ssh top-menu "put top models/Inkling-2-Mini" +# The job has no network: the Desk put the checkpoint in the pilot folder as Inkling-2-Mini, and the toolchain +# archives of ../minimax-h3-cuda/toolchain-stage.sh beside it. Logs and the 1/4-stream receipt land in /work/out/inkling2. set -eu pilot=/assets/drama3-pilot -model=$pilot/models/Inkling-2-Mini -if [ ! -f "$model/config.json" ]; then - echo "missing $model/config.json; the pilot's models and any Inkling config:" >&2 - ls "$pilot/models" >&2 || true +staged=$pilot/cuda-build-toolchain +zig=zig-aarch64-linux-0.17.0 +gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu +out=/work/out/inkling2 +model= +for dir in "$pilot/Inkling-2-Mini" "$pilot/models/Inkling-2-Mini"; do + [ -f "$dir/config.json" ] && model=$dir && break +done +if [ -z "$model" ]; then + echo "no Inkling-2-Mini/config.json in $pilot or $pilot/models; Inkling configs under /assets:" >&2 find /assets -maxdepth 5 -name config.json -exec grep -l '"inkling2' {} + >&2 || true exit 1 fi +[ -d "$staged" ] || { echo "missing $staged: run ../minimax-h3-cuda/toolchain-stage.sh" >&2; exit 1; } +(cd "$staged" && sha256sum -c --quiet) <"$out/ids.txt" +"$bin/tf-cuda-test" inkling2-serving "$model" "$out/ids.txt" +text="The three laws of thermodynamics, explained for a curious student:" +"$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" +INKLING2_REF_PLANT=1 "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" +mem() { echo "$1: $(free -m | awk '/^Mem:/ {print "host used " $3 " MiB, available " $7 " MiB"}'); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } +mem "before the server" +/work/sm121/native/bin/tensorfold-native serve "$model" --backend cuda --host 127.0.0.1 --port 8188 \ + --name inkling-2-mini --parallel 4 --context 8192 --no-update-check >"$out/server.log" 2>&1 & +server=$! +trap 'kill $server 2>/dev/null || :' EXIT +python3 - <<'EOF' +import time, urllib.request +for _ in range(900): + try: + urllib.request.urlopen("http://127.0.0.1:8188/v1/models", timeout=5) + raise SystemExit(0) + except OSError: + time.sleep(1) +raise SystemExit("server did not answer /v1/models in 15 min") +EOF +mem "server loaded" +for level in 1 4; do + python3 tools/bench_concurrent.py http://127.0.0.1:8188 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ + --temperatures 0 --label "gb10-$level" --output "$out/streams-$level.json" + mem "after $level streams" +done +python3 - "$out" <<'EOF' +import json, sys +for level in (1, 4): + cells = json.load(open(f"{sys.argv[1]}/streams-{level}.json"))["cells"] + if any(c.get("failed") for c in cells): + raise SystemExit(f"{level} streams: a request failed") +EOF From 9226939be15d6279958a133e03a6b0281e1e30e3 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:14:39 +0800 Subject: [PATCH 41/84] contract: Mini's ops mix declares its width once after the #4364 merge --- zig/tests/cuda/contract_inkling2_ops_mix.zig | 1 - 1 file changed, 1 deletion(-) diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index 260228a24d2..ba0498e5e15 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -114,7 +114,6 @@ pub const Mix = struct { if (shape.rows == 0 or shape.n != C or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; self.free(a); self.shape = shape; - const C = self.shape.n; const rows = self.shape.rows; const nb = shape.k - 1; const q = nq(self.form); From b7c72ce671a042bb49bbe335640cbd554c71aa37 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:53:28 +0800 Subject: [PATCH 42/84] inkling2: Mini snapshots copy each key head's ring rows (the CUDA caches are head-major) --- .../188-inkling-2-mini-runs-whole-on-our-spark-g.md | 2 ++ zig/src/families/inkling2/loop_engine.zig | 9 +++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index 45df25d327e..df42e174a68 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -5,3 +5,5 @@ - `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: #4387's serving checks, the float64 reference and its planted control, then first-token time, prompt speed, decode speed and memory at 1 and 4 streams. The recipe's README notes what RTX Spark (Windows and WSL2) needs. +- Mini prompt snapshots save and restore each key head's ring rows: the CUDA caches are head-major, and the + row-major copy left restored prompts' logits off from a fresh prefill. diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig index 7b6d5201768..8c7cc1c382d 100644 --- a/zig/src/families/inkling2/loop_engine.zig +++ b/zig/src/families/inkling2/loop_engine.zig @@ -504,24 +504,25 @@ pub const Model = struct { const visit = m.w.p.visits.steps[v]; const layer = m.w.p.at(visit.layer); const geometry = m.layerGeometry(visit.layer); - const rb = @as(usize, layer.heads.kv) * layer.heads.dim * 2; + const rb = @as(usize, layer.heads.dim) * 2; + const head_bytes = @as(usize, geometry.ring) * rb; // caches are [kv head][ring slot][dim] (attention.cu prep) const global = layer.kind == .global; const count = if (global) at else @min(at, m.w.c.text.window - 1); const first = at - count; const cache = m.cacheOf(visit.of(.conv).?); - for ([2]u64{ cache.k, cache.v }) |base| { + for ([2]u64{ cache.k, cache.v }) |base| for (0..layer.heads.kv) |h| { var pos = first; while (pos < at) { const row = pos % geometry.ring; const n = @min(at - pos, geometry.ring - row); - const dev = base + row * rb; + const dev = base + h * head_bytes + row * rb; const src = if (out) dev else saved.buf.ptr + off; const dst = if (out) saved.buf.ptr + off else dev; try m.copy(s, dst, src, n * rb); off += n * rb; pos += n; } - } + }; } const conv = m.cache.ptr + m.layout.at(0).conv_offset; const bytes = m.layout.bytes - m.layout.at(0).conv_offset; From e0b919ce2c41c1d0de1e8979e24681f89cf773b7 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:22:17 +0800 Subject: [PATCH 43/84] inkling2 serving test: name the resumed case, cut and first differing logit on a mismatch --- zig/tests/cuda/inkling2_serving_tests.zig | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index ccaff978e1d..d6545967cd2 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -58,7 +58,11 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes fn sameTrace(a: *const Trace, b: *const Trace) !void { if (!std.mem.eql(u32, a.ids, b.ids)) return error.MiniServingTokenMismatch; - if (!std.mem.eql(u8, std.mem.sliceAsBytes(a.logits), std.mem.sliceAsBytes(b.logits))) return error.MiniServingLogitMismatch; + if (std.mem.indexOfDiff(u32, @ptrCast(a.logits), @ptrCast(b.logits))) |i| { + const v = a.logits.len / a.ids.len; + std.debug.print("RESULT mini-serving logits differ step={d} id={d} {e} vs {e}\n", .{ i / v, i % v, a.logits[i], b.logits[i] }); + return error.MiniServingLogitMismatch; + } } fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { @@ -108,7 +112,10 @@ fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void var fresh = try trace(gpu, loaded, prompt, sampling, 8, false, .{}); defer fresh.deinit(gpu.gpa); const cuts: []const u32 = if (case == 0) &.{ 17, 2048 } else &.{ 2049, @intCast(prompt.len - 1) }; - for (cuts) |cut| try resumedAt(gpu, loaded, prompt, cut, sampling, &fresh); + for (cuts) |cut| resumedAt(gpu, loaded, prompt, cut, sampling, &fresh) catch |err| { + std.debug.print("RESULT mini-serving resumed case={d} cut={d} mismatch={s}\n", .{ case, cut, @errorName(err) }); + return err; + }; } } From 2dc74c17417c2d56a11dbd7b986213538b9cbb84 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:45:46 +0800 Subject: [PATCH 44/84] inkling2: use one global attention path across prompt cuts --- zig/src/families/inkling2/kernels.zig | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/zig/src/families/inkling2/kernels.zig b/zig/src/families/inkling2/kernels.zig index cfdf45eb374..1d11e636a92 100644 --- a/zig/src/families/inkling2/kernels.zig +++ b/zig/src/families/inkling2/kernels.zig @@ -194,6 +194,13 @@ pub fn attend(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, stride: u32, a.add(scale); a.add(int(0)); try go(k.attn, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = tileChunks(r.heads / r.kv_heads, l) }, 128, &a); + } else if (r.streams == 1) { // one stream's rows: 128 pairs a block share each K/V tile, the fold's bits + var p: cuda.Args = .{}; + for ([_]u64{ q, kv.k, kv.v, tab, r.segs, part_o, part_ml }) |v| p.add(v); + for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| p.add(int(v)); + p.add(scale); + const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + try goShared(k.attn_prompt, s, .{ .x = blocks, .y = r.kv_heads, .z = stride }, prompt_threads, prompt_shared, &p); } else if (split(r, stride, slots)) { // every sub-chunk of `stride` chunks (past the rows return at once), so graphs replay by stride per = subs; @@ -202,13 +209,6 @@ pub fn attend(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, stride: u32, a.add(scale); a.add(int(1)); try go(k.attn, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = slots_rh }, 128, &a); - } else if (r.streams == 1) { // one stream's rows: 128 pairs a block share each K/V tile, the fold's bits - var p: cuda.Args = .{}; - for ([_]u64{ q, kv.k, kv.v, tab, r.segs, part_o, part_ml }) |v| p.add(v); - for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| p.add(int(v)); - p.add(scale); - const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; - try goShared(k.attn_prompt, s, .{ .x = blocks, .y = r.kv_heads, .z = stride }, prompt_threads, prompt_shared, &p); } else { // a block a chunk, its sub-chunks folded in order for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| a.add(int(v)); a.add(scale); From 8cf739ea593872a8f4d15ebecc012471bc65c46a Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:02:08 +0800 Subject: [PATCH 45/84] inkling2: store loop messages in role-major planes for serving --- zig/kernels/cuda/inkling2/loop_math.cu | 7 +++---- zig/src/families/inkling2/kernels.zig | 14 +++++++------- zig/src/families/inkling2/loop_math_cuda.zig | 14 ++------------ zig/tests/cuda/contract_inkling2_loop_math.zig | 4 ++-- 4 files changed, 14 insertions(+), 25 deletions(-) diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu index 5d1e5d04891..ccd4fd33360 100644 --- a/zig/kernels/cuda/inkling2/loop_math.cu +++ b/zig/kernels/cuda/inkling2/loop_math.cu @@ -120,7 +120,7 @@ namespace ink2l { // One block handles one token and role, sharing each bank's normalization across all 12 core queries. __device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, const float* __restrict__ qm, const float* __restrict__ qkv, - float* __restrict__ out, int core_layers, int c, float eps) { + float* __restrict__ out, int rows, int core_layers, int c, float eps) { __shared__ float sh[2 * 32]; __shared__ float inv[2], w[2]; const size_t row = blockIdx.x; @@ -154,7 +154,7 @@ __device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __r if (threadIdx.x == 0) softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); __syncthreads(); - float* dst = out + ((static_cast(row * core_layers + j) * 4 + role) * static_cast(c)); + float* dst = out + ((static_cast(j * 4 + role) * rows + row) * static_cast(c)); for (int i = threadIdx.x; i < c; i += blockDim.x) { const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); @@ -230,8 +230,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, int rows, int core_layers, int c, float eps) { - (void)rows; // grid x is rows * core_layers; row derives from pair/core_layers, explicitly visit-local. - ink2l::messages(bank0, bank1, qm, qkv, out, core_layers, c, eps); + ink2l::messages(bank0, bank1, qm, qkv, out, rows, core_layers, c, eps); } extern "C" __global__ void __launch_bounds__(256) diff --git a/zig/src/families/inkling2/kernels.zig b/zig/src/families/inkling2/kernels.zig index 1d11e636a92..cfdf45eb374 100644 --- a/zig/src/families/inkling2/kernels.zig +++ b/zig/src/families/inkling2/kernels.zig @@ -194,13 +194,6 @@ pub fn attend(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, stride: u32, a.add(scale); a.add(int(0)); try go(k.attn, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = tileChunks(r.heads / r.kv_heads, l) }, 128, &a); - } else if (r.streams == 1) { // one stream's rows: 128 pairs a block share each K/V tile, the fold's bits - var p: cuda.Args = .{}; - for ([_]u64{ q, kv.k, kv.v, tab, r.segs, part_o, part_ml }) |v| p.add(v); - for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| p.add(int(v)); - p.add(scale); - const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; - try goShared(k.attn_prompt, s, .{ .x = blocks, .y = r.kv_heads, .z = stride }, prompt_threads, prompt_shared, &p); } else if (split(r, stride, slots)) { // every sub-chunk of `stride` chunks (past the rows return at once), so graphs replay by stride per = subs; @@ -209,6 +202,13 @@ pub fn attend(k: *const Kernels, s: cuda.Stream, r: Rows, l: Layer, stride: u32, a.add(scale); a.add(int(1)); try go(k.attn, s, .{ .x = r.n_tiles, .y = r.kv_heads, .z = slots_rh }, 128, &a); + } else if (r.streams == 1) { // one stream's rows: 128 pairs a block share each K/V tile, the fold's bits + var p: cuda.Args = .{}; + for ([_]u64{ q, kv.k, kv.v, tab, r.segs, part_o, part_ml }) |v| p.add(v); + for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| p.add(int(v)); + p.add(scale); + const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + try goShared(k.attn_prompt, s, .{ .x = blocks, .y = r.kv_heads, .z = stride }, prompt_threads, prompt_shared, &p); } else { // a block a chunk, its sub-chunks folded in order for ([_]u32{ r.heads, r.kv_heads, l.ring, l.chunk, 0, stride }) |v| a.add(int(v)); a.add(scale); diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig index 9a0d4cc4b63..869e9f91ae3 100644 --- a/zig/src/families/inkling2/loop_math_cuda.zig +++ b/zig/src/families/inkling2/loop_math_cuda.zig @@ -65,7 +65,7 @@ pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); } -/// Messages: BF16 banks, even/odd qm/kv FP32 queries/output; row-local q/k/v/mlp, no scratch/position/mask/cache. +/// Messages: BF16 banks, even/odd qm/kv FP32 queries; output [core][role][row][c] (role-major planes). pub fn messages( k: *const Kernels, s: cuda.Stream, @@ -143,16 +143,6 @@ pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); } -test "loop math argument ABI and message role offsets" { +test "loop math argument ABI" { try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); - const c = 2304; - const j = 7; - const row = 3; - const core_layers = 12; - const base = ((row * core_layers + j) * 4) * c; - for ([_]usize{ 0, 1, 2, 3 }, 0..) |role, i| { - const at = base + role * c; - const queries = @as(usize, 2 * j + @as(usize, @intFromBool(i == 2 or i == 3))) * c; - try std.testing.expect(at >= base and queries < 24 * c); - } } diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig index 37fe14871a2..bef2f7d69ef 100644 --- a/zig/tests/cuda/contract_inkling2_loop_math.zig +++ b/zig/tests/cuda/contract_inkling2_loop_math.zig @@ -264,7 +264,7 @@ pub const Messages = struct { const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); value = value.add(logits[b].mul(beta)); } - const at = ((row * layers + j) * 4 + role) * cols + i; + const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; out[at] = value; } }; @@ -301,7 +301,7 @@ pub const Messages = struct { const w1 = e1 / den; for (0..cols) |i| { const want = w0 * beta0[i] + w1 * beta1[i]; - const at = ((row * layers + j) * 4 + role) * cols + i; + const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; const value = ref.readF32(got, at); if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); } From 08888990225eb5730657da5d4f3310c64ec66d3d Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:56:05 +0800 Subject: [PATCH 46/84] docs: note Mini role-major loop message fix --- changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md | 1 + 1 file changed, 1 insertion(+) diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index df42e174a68..babfb205706 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -7,3 +7,4 @@ memory at 1 and 4 streams. The recipe's README notes what RTX Spark (Windows and WSL2) needs. - Mini prompt snapshots save and restore each key head's ring rows: the CUDA caches are head-major, and the row-major copy left restored prompts' logits off from a fresh prefill. +- Mini loop messages now store `[core][role][row][c]` planes, matching each controller's role offset across multi-row prompt chunks; the CUDA reference checks the same served layout. From 588299b2ea36c909f29b9e37f2e872bd12dcca4f Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:55:55 +0800 Subject: [PATCH 47/84] inkling2 serving: compare sampled draws on device BF16 basis --- .../188-inkling-2-mini-runs-whole-on-our-spark-g.md | 1 + zig/tests/cuda/inkling2_serving_tests.zig | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index babfb205706..df9dfd98cb7 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -8,3 +8,4 @@ - Mini prompt snapshots save and restore each key head's ring rows: the CUDA caches are head-major, and the row-major copy left restored prompts' logits off from a fresh prefill. - Mini loop messages now store `[core][role][row][c]` planes, matching each controller's role offset across multi-row prompt chunks; the CUDA reference checks the same served layout. +- The sampled CUDA serving reference widens the same BF16 logits the device sampler consumes, while retaining exact comparisons of the original FP32 logits. diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index d6545967cd2..3be290178ea 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lanes = @import("lanes"); const mini = @import("inkling2"); const cuda = @import("cuda"); +const core = @import("core"); const check = @import("check.zig"); const native = mini.native; @@ -43,11 +44,20 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes errdefer gpu.gpa.free(ids); const logits = try gpu.gpa.alloc(f32, n * v); errdefer gpu.gpa.free(logits); + const draw_row: ?[]f32 = if (host and cuda.sample.ruleFor(sampling) != null) try gpu.gpa.alloc(f32, v) else null; + defer if (draw_row) |rounded| gpu.gpa.free(rounded); try b.prefill(&s); try download(t, t.slot[0].ptr, logits[0..v]); var handle: ?u64 = try b.first(&s, prompt.len); for (0..n) |i| { - ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..v], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); + ids[i] = if (host) blk: { + const row = logits[i * v ..][0..v]; + if (draw_row) |rounded| { + for (rounded, row) |*dst, value| dst.* = core.bf16_round.round32(value); + break :blk try lanes.gpu_full.draw(gpu.gpa, rounded, sampling, @intCast(prompt.len + i), null); + } + break :blk try lanes.gpu_full.draw(gpu.gpa, row, null, @intCast(prompt.len + i), null); + } else try b.read(handle.?); if (i + 1 < n) { handle = try b.queue(&s, .{ .value = ids[i] }, prompt.len + i + 1); try download(t, t.m.s.logits, logits[(i + 1) * v ..][0..v]); From 822e8e178b19bcebc880adc736b7e803ba391bd7 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:23:28 +0800 Subject: [PATCH 48/84] inkling2: one sequence state and CUDA stream a --parallel lane; shared rounds queue every lane before waiting --- zig/src/families/inkling2/cuda_native.zig | 39 ++-- zig/src/families/inkling2/loop_backend.zig | 243 +++++++++++++-------- zig/src/families/inkling2/loop_engine.zig | 7 + zig/tests/cuda/inkling2_serving_tests.zig | 49 +++-- 4 files changed, 194 insertions(+), 144 deletions(-) diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig index 10018b8df53..cf6e33d5b01 100644 --- a/zig/src/families/inkling2/cuda_native.zig +++ b/zig/src/families/inkling2/cuda_native.zig @@ -22,6 +22,7 @@ pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; pub const Options = struct { context: usize, drafts: bool, + lanes: u32 = 1, segments: usize = 1, slide: bool = false, vision: ?VisionOptions = null, @@ -38,18 +39,17 @@ pub const Owned = struct { gpa: std.mem.Allocator, admission: loop.Admission, kernels: engine.Kernels, - stream: cuda.Stream, weights: @import("loop_weights.zig").Weights, - model: engine.Model, backend: backend.Backend, }; +/// `free_streams`: every lane's sequence state is allocated at open, so admission adds none. pub const Loaded = struct { backend: lanes.backend.Backend, facts: lanes.Model, rows: u32, stream_bytes: usize, - free_streams: u32 = 1, + free_streams: u32, ctx: *anyopaque, deinit: *const fn (*anyopaque) void, target: *Owned, @@ -61,10 +61,7 @@ fn own(ptr: *anyopaque) *Owned { fn release(p: *anyopaque) void { const o = own(p); - o.stream.synchronize() catch {}; o.backend.deinit(); - o.stream.deinit(); - o.model.deinit(); o.kernels.deinit(); o.weights.deinit(); const gpa = o.gpa; @@ -103,30 +100,22 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); try @import("names.zig").precisions(merged, c.text.layers, &precisions); const p = try plan_.build(&c.text, precisions[0..c.text.layers]); - var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); - errdefer w.deinit(); - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - ck.release(); - var k = try engine.Kernels.load(ctx); - errdefer k.deinit(); - var stream = try cuda.Stream.init(ctx.d, true); - errdefer stream.deinit(); - var m = try engine.Model.init(gpa, ctx.d, stream, &w, o.context); - errdefer m.deinit(); - var be = try backend.Backend.init(gpa, ctx.d, &m, &k, stream); - errdefer be.deinit(); const out = try gpa.create(Owned); errdefer gpa.destroy(out); - out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; - // The value copies above own pointers to their old stack homes; retarget the live model/backend now. - out.model.w = &out.weights; - out.backend.m = &out.model; - out.backend.k = &out.kernels; - return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = out.model.layout.bytes, .ctx = out, .deinit = release, .target = out }; + out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = undefined, .weights = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p), .backend = undefined }; + errdefer out.weights.deinit(); + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + ck.release(); + out.kernels = try engine.Kernels.load(ctx); + errdefer out.kernels.deinit(); + const room: ?u64 = if (o.room) |r| r.read(r.ctx) else null; + out.backend = try backend.Backend.init(gpa, ctx.d, &out.weights, &out.kernels, o.context, o.lanes, room); + const be = &out.backend; + return .{ .backend = be.backend(), .facts = be.facts(), .rows = window_rows, .stream_bytes = be.lanes[0].m.layout.bytes, .free_streams = @intCast(be.lanes.len), .ctx = out, .deinit = release, .target = out }; } pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { - return own(ptr).model.snapshotBytes(at); + return own(ptr).backend.lanes[0].m.snapshotBytes(at); } pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig index 1053526de10..b25e7f257dd 100644 --- a/zig/src/families/inkling2/loop_backend.zig +++ b/zig/src/families/inkling2/loop_backend.zig @@ -1,8 +1,9 @@ -//! Inkling 2 Mini lane execution and snapshot adapter. +//! Inkling 2 Mini lane execution and snapshot adapter: one complete sequence state and CUDA stream a lane. const std = @import("std"); const cuda = @import("cuda"); const lanes = @import("lanes"); const engine = @import("loop_engine.zig"); +const weights_ = @import("loop_weights.zig"); const ops = @import("ops.zig"); const Model = engine.Model; @@ -11,52 +12,86 @@ const prompt_rows = engine.prompt_rows; const window_rows = engine.window_rows; const token_ring = 1024; -const Lane = struct { +/// A sequence's own cache, scratch and stream; shared rounds queue every lane's forward before any waits. +pub const Lane = struct { + m: Model, + s: cuda.Stream, + logits16: cuda.DeviceBuffer, + meta: cuda.DeviceBuffer, + last: cuda.DeviceBuffer, + rule: cuda.DeviceBuffer, + owner: ?*lanes.Stream = null, + at: usize = 0, // the tokens buffer row this lane's verify draws start at len: usize = 0, fill: ?usize = null, base: usize = 0, rows: std.ArrayList(u32) = .empty, - last: u64, - rule: u64, sampled: bool = false, + + fn init(l: *Lane, gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const weights_.Weights, context: usize) !void { + const v = w.c.text.unpadded_vocab; + var s = try cuda.Stream.init(d, true); + errdefer s.deinit(); + var m = try Model.init(gpa, d, s, w, context); + errdefer m.deinit(); + var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); + errdefer logits16.free(); + var meta = try cuda.DeviceBuffer.alloc(d, 16); + errdefer meta.free(); + var last = try cuda.DeviceBuffer.alloc(d, v * 4); + errdefer last.free(); + l.* = .{ .m = m, .s = s, .logits16 = logits16, .meta = meta, .last = last, .rule = try cuda.DeviceBuffer.alloc(d, @sizeOf(cuda.sample.Rule)) }; + } + + fn deinit(l: *Lane, gpa: std.mem.Allocator) void { + l.s.synchronize() catch {}; + l.rows.deinit(gpa); + l.rule.free(); + l.last.free(); + l.meta.free(); + l.logits16.free(); + l.m.deinit(); + l.s.deinit(); + } + + /// Device bytes the lane holds. + fn heldBytes(l: *const Lane) u64 { + return l.m.heldBytes() + l.logits16.len + l.meta.len + l.last.len + l.rule.len; + } }; pub const Backend = struct { gpa: std.mem.Allocator, d: *const cuda.Driver, - m: *Model, k: *const Kernels, - s: cuda.Stream, - lane: ?Lane = null, - stream: ?*lanes.Stream = null, - tokens: cuda.DeviceBuffer, - logits16: cuda.DeviceBuffer, - meta: cuda.DeviceBuffer, - slot: [2]cuda.DeviceBuffer, + lanes: []Lane, + tokens: cuda.DeviceBuffer, // the token ring, then each lane's verify rows next: u64 = 0, const be = lanes.backend; - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *Model, k: *const Kernels, s: cuda.Stream) !Backend { - const v = m.w.c.text.unpadded_vocab; - var tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + window_rows) * 4); - errdefer tokens.free(); - var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); - errdefer logits16.free(); - var meta = try cuda.DeviceBuffer.alloc(d, 16); - errdefer meta.free(); - var last = try cuda.DeviceBuffer.alloc(d, v * 4); - errdefer last.free(); - var rule = try cuda.DeviceBuffer.alloc(d, @sizeOf(cuda.sample.Rule)); - errdefer rule.free(); - return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .tokens = tokens, .logits16 = logits16, .meta = meta, .slot = .{ last, rule } }; + /// Up to `count` lanes over shared weights and kernels, as many as `room` (device bytes left) holds, at least one. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const weights_.Weights, k: *const Kernels, context: usize, count: usize, room: ?u64) !Backend { + var one: Lane = undefined; + try one.init(gpa, d, w, context); + var made: usize = 1; + const fit = if (room) |r| r / one.heldBytes() else count; + const all = gpa.alloc(Lane, std.math.clamp(fit, 1, @max(count, 1))) catch |err| { + one.deinit(gpa); + return err; + }; + all[0] = one; + errdefer gpa.free(all); + errdefer for (all[0..made]) |*l| l.deinit(gpa); + while (made < all.len) : (made += 1) try all[made].init(gpa, d, w, context); + for (all, 0..) |*l, i| l.at = token_ring + i * window_rows; + const tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + all.len * window_rows) * 4); + return .{ .gpa = gpa, .d = d, .k = k, .lanes = all, .tokens = tokens }; } pub fn deinit(b: *Backend) void { - if (b.lane) |*l| l.rows.deinit(b.gpa); - for (&b.slot) |*x| x.free(); - b.meta.free(); - b.logits16.free(); + for (b.lanes) |*l| l.deinit(b.gpa); + b.gpa.free(b.lanes); b.tokens.free(); b.* = undefined; } @@ -65,35 +100,41 @@ pub const Backend = struct { return .{ .ptr = b, .vtable = &vtable }; } - pub fn facts(_: *const Backend) lanes.Model { - return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = 1, .streams_exact = true }; + pub fn facts(b: *const Backend) lanes.Model { + return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = @intCast(b.lanes.len), .streams_exact = true }; } pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { - return b.stream == null and prompt <= b.m.context and max_new <= b.m.context - prompt; + const m = &b.lanes[0].m; + return b.free() != null and prompt <= m.context and max_new <= m.context - prompt; + } + + fn free(b: *const Backend) ?usize { + for (b.lanes, 0..) |l, i| if (l.owner == null) return i; + return null; } fn self(ptr: *anyopaque) *Backend { return @ptrCast(@alignCast(ptr)); } - fn upload(b: *Backend, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(b.d, dst, bytes, b.s); + fn upload(b: *Backend, s: cuda.Stream, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(b.d, dst, bytes, s); } fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { - if (b.stream != s) return error.UnknownStream; - return if (b.lane) |*l| l else error.UnknownStream; + for (b.lanes) |*l| if (l.owner == s) return l; + return error.UnknownStream; } - fn resumeSaved(b: *Backend, s: *lanes.Stream) usize { + fn resumeSaved(l: *Lane, s: *lanes.Stream) usize { const saved = s.reuse.saved orelse return 0; const k: *const Model.Saved = @ptrCast(@alignCast(saved)); if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { s.reuse_failed = true; return 0; } - b.m.restore(b.s, k) catch { + l.m.restore(l.s, k) catch { s.reuse_failed = true; return 0; }; @@ -104,21 +145,18 @@ pub const Backend = struct { fn opening(b: *Backend, s: *lanes.Stream) !*Lane { const prompt = s.prompt(); if (prompt.len == 0) return error.EmptyPrompt; - if (prompt.len > b.m.context or s.max_new > b.m.context - prompt.len) return error.PastContext; - if (b.stream != null and b.stream != s) return error.NoFreeSlot; - if (b.stream == null) { - b.lane = .{ .last = b.slot[0].ptr, .rule = b.slot[1].ptr }; - b.stream = s; - } - const l = try b.laneOf(s); + const context = b.lanes[0].m.context; + if (prompt.len > context or s.max_new > context - prompt.len) return error.PastContext; + const l = b.laneOf(s) catch &b.lanes[b.free() orelse return error.NoFreeSlot]; + l.owner = s; l.sampled = false; if (cuda.sample.ruleFor(s.sampling)) |r| { - try b.upload(l.rule, std.mem.asBytes(&r)); + try b.upload(l.s, l.rule.ptr, std.mem.asBytes(&r)); l.sampled = true; } l.len = 0; - try b.m.reset(b.s); - const at = b.resumeSaved(s); + try l.m.reset(l.s); + const at = resumeSaved(l, s); l.len = at; l.fill = at; s.fill_at.store(@intCast(at), .monotonic); @@ -134,8 +172,8 @@ pub const Backend = struct { if (mark > at and mark < end) end = mark; } const done = end == prompt.len; - try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); - if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); + try l.m.forward(b.k, l.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); + if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last.ptr, l.m.s.logits, l.m.w.c.text.unpadded_vocab * 4, l.s.handle), "cuMemcpyDtoDAsync"); l.len = end; l.fill = if (done) null else end; s.fill_at.store(@intCast(end), .monotonic); @@ -150,20 +188,21 @@ pub const Backend = struct { return @intCast(h % token_ring); } - fn drawRows(b: *Backend, l: *const Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { - const v = b.m.w.c.text.unpadded_vocab; - if (!l.sampled) return ops.top1(&b.k.glue, b.s, logits, rows, v, v, 0, b.m.s.t + at * 4, b.tokens.ptr + at * 4); - try ops.tobf(&b.k.glue, b.s, logits, rows, v, v, b.logits16.ptr, v, 0, v); + fn drawRows(b: *Backend, l: *Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { + const v = l.m.w.c.text.unpadded_vocab; + if (!l.sampled) return ops.top1(&b.k.glue, l.s, logits, rows, v, v, 0, l.m.s.t + at * 4, b.tokens.ptr + at * 4); + try ops.tobf(&b.k.glue, l.s, logits, rows, v, v, l.logits16.ptr, v, 0, v); const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; - try b.upload(b.meta.ptr, std.mem.asBytes(&metadata)); - try b.k.draws.draw(b.s, b.logits16.ptr, v, l.rule, b.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); + try b.upload(l.s, l.meta.ptr, std.mem.asBytes(&metadata)); + try b.k.draws.draw(l.s, l.logits16.ptr, v, l.rule.ptr, l.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); } + /// A ring token was drawn on its owner's stream; the ring does not record which, so every lane lands first. fn read(ptr: *anyopaque, h: u64) anyerror!u32 { const b = self(ptr); if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; var out: [1]u32 = undefined; - try b.s.synchronize(); + for (b.lanes) |l| if (l.owner != null) try l.s.synchronize(); try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); return out[0]; } @@ -191,8 +230,8 @@ pub const Backend = struct { fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { const b = self(ptr); - const going = b.stream == s and b.lane != null and b.lane.?.fill != null; - const l = if (going) try b.laneOf(s) else try b.opening(s); + const going = b.laneOf(s) catch null; + const l = if (going != null and going.?.fill != null) going.? else try b.opening(s); errdefer release(ptr, s); return b.chunk(s, l); } @@ -202,7 +241,7 @@ pub const Backend = struct { const l = try b.laneOf(s); if (position != l.len or l.fill != null) return error.PositionMismatch; const h = b.next; - try b.drawRows(l, l.last, 1, position, b.handle()); + try b.drawRows(l, l.last.ptr, 1, position, b.handle()); return h; } @@ -222,76 +261,86 @@ pub const Backend = struct { const l = try b.laneOf(s); const token = try b.feed(value); if (position != l.len + 1) return error.PositionMismatch; - try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); + try l.m.forward(b.k, l.s, &.{token}, l.len, 0, 1, false); l.len += 1; const h = b.next; - try b.drawRows(l, b.m.s.logits, 1, position, b.handle()); + try b.drawRows(l, l.m.s.logits, 1, position, b.handle()); return h; } + /// Every window's forward and draw is queued on its own lane before the first wait. fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { const b = self(ptr); - if (windows.len != 1 or out.len != 1) return error.OneStreamOnly; - const w = windows[0]; - if (w.held != 0) return error.NoHeldDrafts; - if (w.parents != null) return error.ChainsOnly; - if (w.masks.len != 0) return error.StructuresUnsupported; - const l = try b.laneOf(w.stream); - const n = w.rows(); - if (n == 0 or n > window_rows) return error.WindowTooWide; - l.base = l.len; - l.rows.clearRetainingCapacity(); - try l.rows.append(b.gpa, w.pending); - try l.rows.appendSlice(b.gpa, w.tokens); - for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; - try b.m.forward(b.k, b.s, l.rows.items, l.base, 0, n, true); - try b.drawRows(l, b.m.s.logits, n, w.positions[0], token_ring); - var got: [window_rows]u32 = undefined; - try b.s.synchronize(); - try b.tokens.download(token_ring * 4, std.mem.sliceAsBytes(got[0..n])); - @memcpy(out[0].sampled[0..n], got[0..n]); - @memcpy(out[0].drafts[0 .. n - 1], l.rows.items[1..n]); - l.len = l.base + n; + if (windows.len != out.len) return error.WindowCount; + for (windows) |w| { + if (w.held != 0) return error.NoHeldDrafts; + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = try b.laneOf(w.stream); + const n = w.rows(); + if (n == 0 or n > window_rows) return error.WindowTooWide; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(b.gpa, w.pending); + try l.rows.appendSlice(b.gpa, w.tokens); + for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; + try l.m.forward(b.k, l.s, l.rows.items, l.base, 0, n, true); + try b.drawRows(l, l.m.s.logits, n, w.positions[0], l.at); + } + for (windows, out) |w, o| { + const l = try b.laneOf(w.stream); + const n = w.rows(); + try l.s.synchronize(); + try b.tokens.download(l.at * 4, std.mem.sliceAsBytes(o.sampled[0..n])); + @memcpy(o.drafts[0 .. n - 1], l.rows.items[1..n]); + l.len = l.base + n; + } } fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { const b = self(ptr); - if (windows.len != 1 or paths.len != 1) return error.OneStreamOnly; - const l = try b.laneOf(windows[0].stream); - const path = paths[0]; - if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; - for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; - try b.m.rewind(b.k, b.s, path.len); - l.len = l.base + path.len; + if (windows.len != paths.len) return error.WindowCount; + for (windows, paths) |w, path| { + const l = try b.laneOf(w.stream); + if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; + for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; + try l.m.rewind(b.k, l.s, path.len); + l.len = l.base + path.len; + } } fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; } + /// A snapshot lands before it returns: another lane may restore it on its own stream. pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); const l = try b.laneOf(s); if ((l.fill orelse l.len) != at) return error.NotAtMark; - return b.m.save(b.s, at); + const saved = try l.m.save(l.s, at); + errdefer l.m.drop(l.s, saved); + try l.s.synchronize(); + return saved; } pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); const l = try b.laneOf(s); - try b.m.restore(b.s, saved); + try l.m.restore(l.s, saved); l.len = saved.at; } + /// Any lane may still be reading the snapshot: all of them land before its bytes go. pub fn dropState(b: *Backend, saved: *Model.Saved) void { - b.m.drop(b.s, saved); + for (b.lanes) |l| l.s.synchronize() catch {}; + b.lanes[0].m.drop(b.lanes[0].s, saved); } fn release(ptr: *anyopaque, s: *lanes.Stream) void { const b = self(ptr); - if (b.stream != s) return; - if (b.lane) |*l| l.rows.deinit(b.gpa); - b.lane = null; - b.stream = null; + const l = b.laneOf(s) catch return; + l.rows.clearRetainingCapacity(); + l.owner = null; } }; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig index 8c7cc1c382d..e019f3807a3 100644 --- a/zig/src/families/inkling2/loop_engine.zig +++ b/zig/src/families/inkling2/loop_engine.zig @@ -253,6 +253,13 @@ pub const Model = struct { m.buffers.deinit(m.gpa); } + /// Device bytes one sequence holds: its cache and its forward scratch. + pub fn heldBytes(m: *const Model) u64 { + var n: u64 = m.cache.len; + for (m.buffers.items) |b| n += b.len; + return n; + } + pub fn deinit(m: *Model) void { m.deinitBuffers(); m.cache.free(); diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index 3be290178ea..1d0141b7b22 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -7,7 +7,7 @@ const core = @import("core"); const check = @import("check.zig"); const native = mini.native; -const Backend = @TypeOf(@as(native.Owned, undefined).backend); +const Lane = @typeInfo(@FieldType(@FieldType(native.Owned, "backend"), "lanes")).pointer.child; const Gpu = check.Gpu; const sampled: lanes.Sampling = .{ .seed = 37, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; @@ -23,13 +23,14 @@ const Trace = struct { } }; -fn target(loaded: *native.Loaded) *Backend { - return &loaded.target.backend; +/// Lane 0: a lone stream always takes the first free lane. +fn target(loaded: *native.Loaded) *Lane { + return &loaded.target.backend.lanes[0]; } -fn download(b: *Backend, src: u64, out: []f32) !void { - try b.s.synchronize(); - try cuda.memory.download(b.d, src, std.mem.sliceAsBytes(out)); +fn download(l: *Lane, src: u64, out: []f32) !void { + try l.s.synchronize(); + try cuda.memory.download(l.s.d, src, std.mem.sliceAsBytes(out)); } /// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. @@ -47,7 +48,7 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes const draw_row: ?[]f32 = if (host and cuda.sample.ruleFor(sampling) != null) try gpu.gpa.alloc(f32, v) else null; defer if (draw_row) |rounded| gpu.gpa.free(rounded); try b.prefill(&s); - try download(t, t.slot[0].ptr, logits[0..v]); + try download(t, t.last.ptr, logits[0..v]); var handle: ?u64 = try b.first(&s, prompt.len); for (0..n) |i| { ids[i] = if (host) blk: { @@ -90,16 +91,16 @@ fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { /// Save one complete state at `cut`, restore it through the genuine prompt-reuse hook and rerun the suffix. fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling, fresh: *const Trace) !void { - const Saved = @TypeOf(loaded.target.model).Saved; + const Saved = @TypeOf(target(loaded).m).Saved; const Keeper = struct { - b: *Backend, + b: *native.Owned, saved: ?*Saved = null, fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { const k: *@This() = @ptrCast(@alignCast(ptr)); - k.saved = k.b.saveState(s, mark) catch null; + k.saved = k.b.backend.saveState(s, mark) catch null; } }; - const t = target(loaded); + const t = loaded.target; const saved = snapshot: { var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-snapshot", .prompt = prompt, .max_new = 1, .reuse = .{ .marks = &.{cut} } }); defer s.deinit(gpu.gpa); @@ -110,7 +111,7 @@ fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sa try b.prefill(&s); break :snapshot keeper.saved orelse return error.MiniSnapshotNotSaved; }; - defer t.dropState(saved); + defer t.backend.dropState(saved); var resumed = try trace(gpu, loaded, prompt, sampling, fresh.ids.len, false, .{ .saved = saved, .at = cut }); defer resumed.deinit(gpu.gpa); if (resumed.cached != cut or resumed.failed) return error.MiniSnapshotNotRestored; @@ -142,6 +143,7 @@ fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.pr if (s.reason != .length) return error.MiniServingDidNotFinish; } +/// Both lanes decode at once in shared rounds; a third request finds no free lane until one ends. fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) !void { var plain_a = try trace(gpu, loaded, a, null, 10, false, .{}); defer plain_a.deinit(gpu.gpa); @@ -151,24 +153,27 @@ fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) ! defer first.deinit(gpu.gpa); var second = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-second", .prompt = b, .max_new = 10, .sampling = sampled }); defer second.deinit(gpu.gpa); + var third = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-third", .prompt = a, .max_new = 10 }); + defer third.deinit(gpu.gpa); var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); defer cfg.deinit(gpu.gpa); cfg.timed = false; var clock: lanes.fake.FixedClock = .{}; var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); defer e.deinit(); - if (!native.fits(loaded.ctx, @intCast(a.len), first.max_new)) return error.MiniUnexpectedFreeSlot; try e.addStream(&first); - if (native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniBusyAdmissionRefused; - try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&second)); - while (!first.finished) try e.step(); - try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); - if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; - if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSlotNotReleased; + if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSecondLaneRefused; try e.addStream(&second); - while (!second.finished) try e.step(); + if (native.fits(loaded.ctx, @intCast(a.len), third.max_new)) return error.MiniBusyAdmissionRefused; + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&third)); + const rounds = e.shared_rounds; + while (!first.finished or !second.finished) try e.step(); + if (e.shared_rounds == rounds) return error.MiniLanesNeverShared; + try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); try std.testing.expectEqual(lanes.stream.Reason.length, second.reason); + if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; if (!std.mem.eql(u32, second.emitted(), plain_b.ids)) return error.MiniAdmissionChangedSecond; + if (!native.fits(loaded.ctx, @intCast(a.len), third.max_new)) return error.MiniSlotNotReleased; } /// Priced copies deliberately alternate whole matches, first-row rejection and a prefix match. @@ -291,14 +296,14 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { defer gpu.gpa.free(ids); if (ids.len < 4096) return error.MiniServingPromptTooShort; const context = ids.len + 64; - var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true }); + var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true, .lanes = 2 }); defer loaded.deinit(loaded.ctx); try hostReference(gpu, &loaded, ids[0..4096]); check.pass("Mini CUDA serving matches the host reference token for token", .{}); try freshAndResumed(gpu, &loaded, ids[0..2309]); check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens", .{}); try admission(gpu, &loaded, ids[0..257], ids[17..1042]); - check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens", .{}); + check.pass("Mini CUDA two lanes decode together in shared rounds without changing tokens; a third waits", .{}); try copiedDrafts(gpu, &loaded, ids[0..64]); check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly", .{}); } From 2301ab379e4d57f40fc574ca4287a14d62db76ae Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:23:28 +0800 Subject: [PATCH 49/84] Inkling 2 Mini on TOP: host memory from /proc/meminfo, 4-stream gate and GB10 bandwidth limit in the receipt --- ...nkling-2-mini-runs-whole-on-our-spark-g.md | 3 ++ docs/recipes/inkling-2-mini-cuda/README.md | 7 +++- .../recipes/inkling-2-mini-cuda/run-script.sh | 39 +++++++++++++++++-- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index df9dfd98cb7..fd957e0b1e0 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -9,3 +9,6 @@ row-major copy left restored prompts' logits off from a fresh prefill. - Mini loop messages now store `[core][role][row][c]` planes, matching each controller's role offset across multi-row prompt chunks; the CUDA reference checks the same served layout. - The sampled CUDA serving reference widens the same BF16 logits the device sampler consumes, while retaining exact comparisons of the original FP32 logits. +- Mini CUDA serves `--parallel N` streams at once: each lane owns its sequence state and CUDA stream over shared + weights, and a shared round queues every lane's forward before it waits. Before, the server admitted N requests + to one lane and failed the others with `NoFreeSlot`. The TOP receipt adds the bandwidth limit and a 4-stream gate. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 77cf85d5f5c..18fb59fc4da 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -8,7 +8,12 @@ The server is #4387's engine (`inkling2.native`, model type `inkling2_loop`) wit attention fixes from his #4387 comments; #4441's engine (`inkling2.mini_native`) rides along for its float64 reference. The script fails on any of: `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test inkling2-mini-ref` (32 greedy tokens equal to the float64 host reference), that reference's planted control staying -green, or a failed stream in `tools/bench_concurrent.py` at 1 and 4 streams. +green, a failed stream in `tools/bench_concurrent.py` at 1 and 4 streams, or 4 streams giving under 1.5 times one +stream's total tok/s. The receipt also sets one stream's decode against GB10's bandwidth limit: the weight bytes a +token reads (from the checkpoint's headers) over 273 GB/s. + +Each `--parallel` stream gets its own lane: a complete sequence state (cache and forward scratch, about 1.5 GiB at an +8K window) and CUDA stream over the shared weights. A shared round queues every lane's forward before it waits on any. ## RTX Spark (N1X): what differs and what must change diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh index 95f9b1acc0a..65c630e1743 100755 --- a/docs/recipes/inkling-2-mini-cuda/run-script.sh +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -41,7 +41,7 @@ python3 -c 'import random; r = random.Random(4387); print(" ".join(str(r.randran text="The three laws of thermodynamics, explained for a curious student:" "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" INKLING2_REF_PLANT=1 "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" -mem() { echo "$1: $(free -m | awk '/^Mem:/ {print "host used " $3 " MiB, available " $7 " MiB"}'); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } +mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } mem "before the server" /work/sm121/native/bin/tensorfold-native serve "$model" --backend cuda --host 127.0.0.1 --port 8188 \ --name inkling-2-mini --parallel 4 --context 8192 --no-update-check >"$out/server.log" 2>&1 & @@ -63,10 +63,41 @@ for level in 1 4; do --temperatures 0 --label "gb10-$level" --output "$out/streams-$level.json" mem "after $level streams" done -python3 - "$out" <<'EOF' -import json, sys +python3 - "$out" "$model" <<'EOF' +import glob, json, re, struct, sys +out, model = sys.argv[1:] +agg = {} for level in (1, 4): - cells = json.load(open(f"{sys.argv[1]}/streams-{level}.json"))["cells"] + cells = json.load(open(f"{out}/streams-{level}.json"))["cells"] if any(c.get("failed") for c in cells): raise SystemExit(f"{level} streams: a request failed") + agg[level] = max(c["aggregate_tps"] for c in cells) + for c in cells: + r = c["request"] + print(f"RESULT inkling2 mini gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") +# weight bytes one decoded token reads: the core layers (loop_config) run num_passes times, each visit reads +# num_experts_per_tok of n_routed_experts experts, the unembedding is read whole and the embedding one row +text = json.load(open(f"{model}/config.json")) +text = text.get("text_config", text) +loop = text["loop_config"] +per_token = 0.0 +for path in glob.glob(f"{model}/*.safetensors"): + with open(path, "rb") as f: + header = json.loads(f.read(struct.unpack(" Date: Mon, 23 Nov 2026 07:15:40 +0800 Subject: [PATCH 50/84] docs: Inkling 2 Mini GB10 receipt at 1 and 4 streams with the bandwidth limit --- docs/recipes/inkling-2-mini-cuda/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 18fb59fc4da..33c990ed2ef 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -15,6 +15,24 @@ token reads (from the checkpoint's headers) over 273 GB/s. Each `--parallel` stream gets its own lane: a complete sequence state (cache and forward scratch, about 1.5 GiB at an 8K window) and CUDA stream over the shared weights. A shared round queues every lane's forward before it waits on any. +## Receipt: TOP's GB10, one capped run + +Job `top-0759755a0515` at `2301ab379`, `--context 8192`, greedy, 256 tokens, 3 reps, medians. This is one run with +these settings, not a benchmark. + +| Streams | First token (code / chat) | Prompt (code) | Decode a stream | Total decode | Failed | +|---|---|---|---|---|---| +| 1 | 0.36 s / 0.18 s | 41.9 tok/s | 5.7 tok/s | 5.7 tok/s | 0 | +| 4 | 0.90 s / 0.45 s | 17.3 tok/s | 2.3 tok/s | 9.4 tok/s (1.65x) | 0 | + +Memory (`/proc/meminfo`, host used): 10.7 GiB before the server, 35.3 GiB with Mini loaded with 4 lanes, and the same +after both levels. GPU (`nvidia-smi`): 23.9 GiB held by the server. + +Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the +whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 5.7 tok/s is 12% of it. The gap is not bandwidth: +the 175 ms a token is consistent with roughly 1,350 small launches and one-row matrix kernels per token, unbatched +across lanes [INFERENCE, not profiled]. CUDA graphs per lane and batched expert rows across lanes are what is missing. + ## RTX Spark (N1X): what differs and what must change I see the same chip and memory model as the GB10: sm_121 and one unified pool, so the `-Dsm=121` kernel images are From 987ab2981fa1fca63a698160ff7bb9df16f0c24d Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:50:45 +0800 Subject: [PATCH 51/84] inkling2 metal: budget a target state per stream; read the first logprob row after the first token --- zig/kernels/cuda/inkling2/loop_math.cu | 284 --------- zig/src/families/inkling2/cuda_native.zig | 160 ----- zig/src/families/inkling2/loop_backend.zig | 346 ----------- zig/src/families/inkling2/loop_cache.zig | 155 ----- zig/src/families/inkling2/loop_engine.zig | 578 ------------------ zig/src/families/inkling2/loop_math_cuda.zig | 148 ----- zig/src/families/inkling2/loop_model.zig | 464 -------------- zig/src/families/inkling2/loop_model_test.zig | 214 ------- zig/src/families/inkling2/loop_weights.zig | 227 ------- .../families/inkling2/metal/serving_test.zig | 3 +- zig/src/native/inkling2.zig | 9 +- .../cuda/contract_inkling2_loop_math.zig | 479 --------------- .../contract_inkling2_loop_math_extra.zig | 426 ------------- 13 files changed, 8 insertions(+), 3485 deletions(-) delete mode 100644 zig/kernels/cuda/inkling2/loop_math.cu delete mode 100644 zig/src/families/inkling2/cuda_native.zig delete mode 100644 zig/src/families/inkling2/loop_backend.zig delete mode 100644 zig/src/families/inkling2/loop_cache.zig delete mode 100644 zig/src/families/inkling2/loop_engine.zig delete mode 100644 zig/src/families/inkling2/loop_math_cuda.zig delete mode 100644 zig/src/families/inkling2/loop_model.zig delete mode 100644 zig/src/families/inkling2/loop_model_test.zig delete mode 100644 zig/src/families/inkling2/loop_weights.zig delete mode 100644 zig/tests/cuda/contract_inkling2_loop_math.zig delete mode 100644 zig/tests/cuda/contract_inkling2_loop_math_extra.zig diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu deleted file mode 100644 index ccd4fd33360..00000000000 --- a/zig/kernels/cuda/inkling2/loop_math.cu +++ /dev/null @@ -1,284 +0,0 @@ -// Inkling 2 Mini: raw block residuals, two-bank messages, rank-64 gates and three-input QKV projection. -#include -#include - -namespace ink2l { - -constexpr int kRank = 64; -constexpr int kMaxBlocks = 8; -constexpr int kMaxQueries = 3; - -__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } -__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } -__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } - -__device__ __forceinline__ float warpSum(float v) { - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} - -// Every call has the same reduction tree: lanes' strided chains, each warp's butterfly, then warp 0 over partials. -template -__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; - for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); - __syncthreads(); - if (lane == 0) - for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; - __syncthreads(); - for (int i = 0; i < N; ++i) { - const float t = lane < nw ? sh[i * 32 + lane] : 0.0f; - v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); - } -} - -// A14(a): Mini's queried residual and message dot products scale after the dot, by binary32(1 / 48). -__device__ __forceinline__ float queryScale(int c) { - return c == 2304 ? 1.0f / 48.0f : rsqrtf(static_cast(c)); -} - -__device__ __forceinline__ void softmax2(float l0, float l1, float* w) { - const float m = fmaxf(l0, l1); - const float e0 = expf(l0 - m), e1 = expf(l1 - m); - const float d = __fadd_rn(e0, e1); - w[0] = __fdiv_rn(e0, d); - w[1] = __fdiv_rn(e1, d); -} - -struct ArArgs { - const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C], one completed state a pointer - const void* partial; // the final source, BF16 or FP32 according to partial_bf16 - const float* query; // fp32 [nq, C] - float* out; // fp32 [nq, rows, C], deliberately neither normalized nor rounded - int n_blocks, partial_bf16, nq, rows, C; - float eps; -}; - -// The AR half of Small's residual mix, without its fused RMSNorm. Needed before Mini's controller, not just after it. -__device__ void ar(const ArArgs a) { - __shared__ float sh[32 * (1 + kMaxQueries)]; - __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; - __shared__ float rr[kMaxBlocks + 1]; - const size_t row = blockIdx.x; - const int n = a.n_blocks + 1; - auto entry = [&](int j, int c) -> float { - if (j < a.n_blocks) return bf(a.blocks[j][row * a.C + c]); - return a.partial_bf16 ? bf(static_cast(a.partial)[row * a.C + c]) - : static_cast(a.partial)[row * a.C + c]; - }; - for (int j = 0; j < n; ++j) { - float ss[1] = {0.0f}; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - const float x = entry(j, c); - ss[0] = __fmaf_rn(x, x, ss[0]); - } - blockSums<1>(ss, sh); - if (threadIdx.x == 0) rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(a.C)), a.eps)); - } - __syncthreads(); - for (int j = 0; j < n; ++j) { - float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - const float normalized = __fmul_rn(entry(j, c), rr[j]); - for (int q = 0; q < a.nq; ++q) - dots[q] = __fmaf_rn(a.query[static_cast(q) * a.C + c], normalized, dots[q]); - } - blockSums(dots, sh); - if (threadIdx.x == 0) - for (int q = 0; q < a.nq; ++q) wts[q][j] = __fmul_rn(dots[q], queryScale(a.C)); - } - __syncthreads(); - if (threadIdx.x < a.nq) { - float* l = wts[threadIdx.x]; - float m = -INFINITY, d = 0.0f; - for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); - for (int j = 0; j < n; ++j) d = __fadd_rn(d, expf(l[j] - m)); - for (int j = 0; j < n; ++j) l[j] = __fdiv_rn(expf(l[j] - m), d); - } - __syncthreads(); - for (int q = 0; q < a.nq; ++q) { - float* out = a.out + (static_cast(q) * a.rows + row) * a.C; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - float h = 0.0f; - for (int j = 0; j < n; ++j) { - const float z = __fmul_rn(entry(j, c), rr[j]); - h = __fmaf_rn(wts[q][j], z, h); - } - out[c] = h; - } - } -} - -} // namespace ink2l - -extern "C" __global__ void __launch_bounds__(512) tf_ink2_loop_ar(const ink2l::ArArgs a) { - ink2l::ar(a); -} - -namespace ink2l { - -// One block handles one token and role, sharing each bank's normalization across all 12 core queries. -__device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, - const float* __restrict__ qm, const float* __restrict__ qkv, - float* __restrict__ out, int rows, int core_layers, int c, float eps) { - __shared__ float sh[2 * 32]; - __shared__ float inv[2], w[2]; - const size_t row = blockIdx.x; - const int role = blockIdx.y; // q, k, v, mlp - const uint16_t* banks[2] = {bank0 + row * c, bank1 + row * c}; - const float* role_queries = role == 0 || role == 3 ? qm : qkv; - const int odd = role == 3 || role == 2; - float ss[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float x0 = bf(banks[0][i]), x1 = bf(banks[1][i]); - ss[0] = __fmaf_rn(x0, x0, ss[0]); - ss[1] = __fmaf_rn(x1, x1, ss[1]); - } - blockSums<2>(ss, sh); - if (threadIdx.x == 0) { - inv[0] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); - inv[1] = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); - } - __syncthreads(); - for (int j = 0; j < core_layers; ++j) { - const float* query = role_queries + static_cast(2 * j + odd) * c; - float dots[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float q = query[i]; - const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); - const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); - dots[0] = __fmaf_rn(q, b0, dots[0]); - dots[1] = __fmaf_rn(q, b1, dots[1]); - } - blockSums<2>(dots, sh); - if (threadIdx.x == 0) - softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); - __syncthreads(); - float* dst = out + ((static_cast(j * 4 + role) * rows + row) * static_cast(c)); - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); - const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); - const float m0 = __fmul_rn(w[0], b0), m1 = __fmul_rn(w[1], b1); - dst[i] = __fadd_rn(m0, m1); - } - } -} - -// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). -__device__ void gate(const float* __restrict__ h, const float* __restrict__ m, - const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, - const uint16_t* __restrict__ gain, float* __restrict__ out, - int c, float eps) { - __shared__ float sh[2 * 32]; - __shared__ float inv_h, inv_m; - __shared__ uint16_t zeta[kRank]; - const size_t row = blockIdx.x; - const float* hr = h + row * c; - const float* mr = m + row * c; - float ss[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); - ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); - } - blockSums<2>(ss, sh); - if (threadIdx.x == 0) { - inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); - inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); - } - __syncthreads(); - // Pair ranks to reuse each normalized input, but keep every dot's 256-thread chains and two-level reduction tree. - for (int r = 0; r < kRank; r += 2) { - float acc[2] = {0.0f, 0.0f}; - const uint16_t* d0 = down + static_cast(r) * (2 * c); - const uint16_t* d1 = d0 + 2 * c; - for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { - const bool message = i >= c; - const float x = message ? mr[i - c] : hr[i]; - const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); - acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); - acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); - } - blockSums<2>(acc, sh); - if (threadIdx.x == 0) { - zeta[r] = tobf(acc[0]); - zeta[r + 1] = tobf(acc[1]); - } - } - __syncthreads(); - float* dst = out + row * c; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const uint16_t* f = forget + static_cast(i) * kRank; - const uint16_t* g = gain + static_cast(i) * kRank; - float sf = 0.0f, sg = 0.0f; - for (int r = 0; r < kRank; ++r) { - const float z = bf(zeta[r]); - sf = __fmaf_rn(bf(f[r]), z, sf); - sg = __fmaf_rn(bf(g[r]), z, sg); - } - const float fg = tanhf(sf), gg = tanhf(sg); - // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. - const float keep = __fsub_rn(1.0f, fg); - const float old = __fmul_rn(keep, hr[i]); - const float added = __fmul_rn(gg, mr[i]); - dst[i] = __fadd_rn(old, added); - } -} - -} // namespace ink2l - -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, - const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, - int rows, int core_layers, int c, float eps) { - ink2l::messages(bank0, bank1, qm, qkv, out, rows, core_layers, c, eps); -} - -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, - const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, - int rows, int c, float eps) { - (void)rows; - ink2l::gate(h, m, down, forget, gain, out, c, eps); -} - -// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, - const uint16_t* __restrict__ uv, const uint16_t* __restrict__ wq, - const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wv, - uint16_t* __restrict__ raw_q, uint16_t* __restrict__ raw_k, - uint16_t* __restrict__ raw_v, int rows, int c, int q_width, int kv_width) { - constexpr int kRows = 16, kOutputs = 16, kSlice = 32; - __shared__ uint16_t sx[kRows * kSlice], sw[kOutputs * kSlice]; - const int role = blockIdx.z; // q=0, k=1, v=2 - const int width = role == 0 ? q_width : kv_width; - const int row0 = static_cast(blockIdx.x) * kRows; - const int j0 = static_cast(blockIdx.y) * kOutputs; - if (j0 >= width) return; - const uint16_t* x = role == 0 ? uq : role == 1 ? uk : uv; - const uint16_t* w = role == 0 ? wq : role == 1 ? wk : wv; - const int tr = threadIdx.x / kOutputs, tj = threadIdx.x % kOutputs; - const int row = row0 + tr, j = j0 + tj; - float sum = 0.0f; - // A block reuses each normalized tile for 16 outputs and each weight tile for 16 prompt rows. - for (int k0 = 0; k0 < c; k0 += kSlice) { - for (int e = threadIdx.x; e < kRows * kSlice; e += blockDim.x) { - const int r = e / kSlice, k = k0 + e % kSlice; - sx[e] = row0 + r < rows && k < c ? x[static_cast(row0 + r) * c + k] : 0; - sw[e] = j0 + r < width && k < c ? w[static_cast(j0 + r) * c + k] : 0; - } - __syncthreads(); - for (int k = 0; k < kSlice && k0 + k < c; ++k) - sum = __fmaf_rn(ink2l::bf(sx[tr * kSlice + k]), ink2l::bf(sw[tj * kSlice + k]), sum); - __syncthreads(); - } - uint16_t* out = role == 0 ? raw_q : role == 1 ? raw_k : raw_v; - if (row < rows && j < width) out[static_cast(row) * width + j] = ink2l::tobf(sum); -} - -// Global dynamic taps: dot in FP32, store as BF16, and widen to FP32 before the convolution. -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_round_bf16(const float* __restrict__ in, float* __restrict__ out, long long n) { - const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; - if (i < n) out[i] = ink2l::bf(ink2l::tobf(in[i])); -} diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig deleted file mode 100644 index cf6e33d5b01..00000000000 --- a/zig/src/families/inkling2/cuda_native.zig +++ /dev/null @@ -1,160 +0,0 @@ -//! Inkling 2 Mini's complete one-rank, text-only CUDA engine and checkpoint/snapshot admission. -const std = @import("std"); -const cuda = @import("cuda"); -const lanes = @import("lanes"); -const core = @import("core"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -const loop = @import("loop_cache.zig"); -const engine = @import("loop_engine.zig"); -const backend = @import("loop_backend.zig"); - -pub const model_type = "inkling2_loop"; -pub const formats: []const []const u8 = &.{"modelopt-mixed"}; -pub const default_context: i64 = 1_048_576; -pub const max_segments: u32 = 1; -pub const prompt_rows: u32 = engine.prompt_rows; -pub const window_rows: u32 = engine.window_rows; -pub const explains_open = true; - -pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; -pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; -pub const Options = struct { - context: usize, - drafts: bool, - lanes: u32 = 1, - segments: usize = 1, - slide: bool = false, - vision: ?VisionOptions = null, - precision: ?enum { full } = null, - room: ?Room = null, - drafter: ?[]const u8 = null, - tp: usize = 1, - rank: usize = 0, - master: ?[]const u8 = null, - master_port: u16 = 29551, -}; - -pub const Owned = struct { - gpa: std.mem.Allocator, - admission: loop.Admission, - kernels: engine.Kernels, - weights: @import("loop_weights.zig").Weights, - backend: backend.Backend, -}; - -/// `free_streams`: every lane's sequence state is allocated at open, so admission adds none. -pub const Loaded = struct { - backend: lanes.backend.Backend, - facts: lanes.Model, - rows: u32, - stream_bytes: usize, - free_streams: u32, - ctx: *anyopaque, - deinit: *const fn (*anyopaque) void, - target: *Owned, -}; - -fn own(ptr: *anyopaque) *Owned { - return @ptrCast(@alignCast(ptr)); -} - -fn release(p: *anyopaque) void { - const o = own(p); - o.backend.deinit(); - o.kernels.deinit(); - o.weights.deinit(); - const gpa = o.gpa; - gpa.destroy(o); -} - -pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { - const o: *const Owned = @ptrCast(@alignCast(p)); - return o.admission.fits(prompt, max_tokens) and o.backend.admits(prompt, max_tokens); -} - -pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { - if (kernels != null) return error.Inkling2CapturedKernels; - if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; - if (o.vision != null) return error.Inkling2LoopTextOnly; - if (o.drafter != null) return error.Inkling2DSparkPending; - const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); - defer gpa.free(path); - const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); - defer gpa.free(bytes); - var why: config.Why = .{}; - const c = config.parse(gpa, bytes, &why) catch |err| { - std.log.err("Inkling 2 Mini config refused: {s}", .{why.text()}); - return err; - }; - try loop.validateLoad(&c, 1, false); - if (o.context == 0 or o.context > c.text.max_context or o.context > std.math.maxInt(u32)) return error.BadLoopCache; - var ck = try core.Checkpoint.openModel(gpa, io, dir); - defer ck.close(); - try ck.skip("model.visual."); // The checkpoint carries Small's tower; text-only Mini never loads or executes it. - var precisions: [config.max_layers]plan_.Precision = undefined; - @memset(&precisions, .nvfp4); - var header_arena = std.heap.ArenaAllocator.init(gpa); - defer header_arena.deinit(); - var merged: core.safetensors.Header = .empty; - for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); - try @import("names.zig").precisions(merged, c.text.layers, &precisions); - const p = try plan_.build(&c.text, precisions[0..c.text.layers]); - const out = try gpa.create(Owned); - errdefer gpa.destroy(out); - out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = undefined, .weights = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p), .backend = undefined }; - errdefer out.weights.deinit(); - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - ck.release(); - out.kernels = try engine.Kernels.load(ctx); - errdefer out.kernels.deinit(); - const room: ?u64 = if (o.room) |r| r.read(r.ctx) else null; - out.backend = try backend.Backend.init(gpa, ctx.d, &out.weights, &out.kernels, o.context, o.lanes, room); - const be = &out.backend; - return .{ .backend = be.backend(), .facts = be.facts(), .rows = window_rows, .stream_bytes = be.lanes[0].m.layout.bytes, .free_streams = @intCast(be.lanes.len), .ctx = out, .deinit = release, .target = out }; -} - -pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { - return own(ptr).backend.lanes[0].m.snapshotBytes(at); -} - -pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { - return @ptrCast(try own(ptr).backend.saveState(owner, at)); -} - -pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { - return own(ptr).backend.restoreState(owner, @ptrCast(@alignCast(saved))); -} - -pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { - own(ptr).backend.dropState(@ptrCast(@alignCast(saved))); -} - -pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { - return switch (err) { - error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", - error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", - error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", - error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", - error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", - else => null, - }; -} - -test "Mini native registration and refusal wording are explicit" { - try std.testing.expectEqualStrings("inkling2_loop", model_type); - try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); - for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels }) |err| { - try std.testing.expect(explain(null, err) != null); - } -} - -test "the complete prompt snapshot hooks match the store vtable" { - const pc: struct { - bytes: *const fn (*anyopaque, u32) u64, - save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, - restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, - drop: *const fn (*anyopaque, *anyopaque) void, - } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; - try std.testing.expect(@intFromPtr(pc.save) != 0); -} diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig deleted file mode 100644 index b25e7f257dd..00000000000 --- a/zig/src/families/inkling2/loop_backend.zig +++ /dev/null @@ -1,346 +0,0 @@ -//! Inkling 2 Mini lane execution and snapshot adapter: one complete sequence state and CUDA stream a lane. -const std = @import("std"); -const cuda = @import("cuda"); -const lanes = @import("lanes"); -const engine = @import("loop_engine.zig"); -const weights_ = @import("loop_weights.zig"); -const ops = @import("ops.zig"); - -const Model = engine.Model; -const Kernels = engine.Kernels; -const prompt_rows = engine.prompt_rows; -const window_rows = engine.window_rows; -const token_ring = 1024; - -/// A sequence's own cache, scratch and stream; shared rounds queue every lane's forward before any waits. -pub const Lane = struct { - m: Model, - s: cuda.Stream, - logits16: cuda.DeviceBuffer, - meta: cuda.DeviceBuffer, - last: cuda.DeviceBuffer, - rule: cuda.DeviceBuffer, - owner: ?*lanes.Stream = null, - at: usize = 0, // the tokens buffer row this lane's verify draws start at - len: usize = 0, - fill: ?usize = null, - base: usize = 0, - rows: std.ArrayList(u32) = .empty, - sampled: bool = false, - - fn init(l: *Lane, gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const weights_.Weights, context: usize) !void { - const v = w.c.text.unpadded_vocab; - var s = try cuda.Stream.init(d, true); - errdefer s.deinit(); - var m = try Model.init(gpa, d, s, w, context); - errdefer m.deinit(); - var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); - errdefer logits16.free(); - var meta = try cuda.DeviceBuffer.alloc(d, 16); - errdefer meta.free(); - var last = try cuda.DeviceBuffer.alloc(d, v * 4); - errdefer last.free(); - l.* = .{ .m = m, .s = s, .logits16 = logits16, .meta = meta, .last = last, .rule = try cuda.DeviceBuffer.alloc(d, @sizeOf(cuda.sample.Rule)) }; - } - - fn deinit(l: *Lane, gpa: std.mem.Allocator) void { - l.s.synchronize() catch {}; - l.rows.deinit(gpa); - l.rule.free(); - l.last.free(); - l.meta.free(); - l.logits16.free(); - l.m.deinit(); - l.s.deinit(); - } - - /// Device bytes the lane holds. - fn heldBytes(l: *const Lane) u64 { - return l.m.heldBytes() + l.logits16.len + l.meta.len + l.last.len + l.rule.len; - } -}; - -pub const Backend = struct { - gpa: std.mem.Allocator, - d: *const cuda.Driver, - k: *const Kernels, - lanes: []Lane, - tokens: cuda.DeviceBuffer, // the token ring, then each lane's verify rows - next: u64 = 0, - - const be = lanes.backend; - - /// Up to `count` lanes over shared weights and kernels, as many as `room` (device bytes left) holds, at least one. - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const weights_.Weights, k: *const Kernels, context: usize, count: usize, room: ?u64) !Backend { - var one: Lane = undefined; - try one.init(gpa, d, w, context); - var made: usize = 1; - const fit = if (room) |r| r / one.heldBytes() else count; - const all = gpa.alloc(Lane, std.math.clamp(fit, 1, @max(count, 1))) catch |err| { - one.deinit(gpa); - return err; - }; - all[0] = one; - errdefer gpa.free(all); - errdefer for (all[0..made]) |*l| l.deinit(gpa); - while (made < all.len) : (made += 1) try all[made].init(gpa, d, w, context); - for (all, 0..) |*l, i| l.at = token_ring + i * window_rows; - const tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + all.len * window_rows) * 4); - return .{ .gpa = gpa, .d = d, .k = k, .lanes = all, .tokens = tokens }; - } - - pub fn deinit(b: *Backend) void { - for (b.lanes) |*l| l.deinit(b.gpa); - b.gpa.free(b.lanes); - b.tokens.free(); - b.* = undefined; - } - - pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &vtable }; - } - - pub fn facts(b: *const Backend) lanes.Model { - return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = @intCast(b.lanes.len), .streams_exact = true }; - } - - pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { - const m = &b.lanes[0].m; - return b.free() != null and prompt <= m.context and max_new <= m.context - prompt; - } - - fn free(b: *const Backend) ?usize { - for (b.lanes, 0..) |l, i| if (l.owner == null) return i; - return null; - } - - fn self(ptr: *anyopaque) *Backend { - return @ptrCast(@alignCast(ptr)); - } - - fn upload(b: *Backend, s: cuda.Stream, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(b.d, dst, bytes, s); - } - - fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { - for (b.lanes) |*l| if (l.owner == s) return l; - return error.UnknownStream; - } - - fn resumeSaved(l: *Lane, s: *lanes.Stream) usize { - const saved = s.reuse.saved orelse return 0; - const k: *const Model.Saved = @ptrCast(@alignCast(saved)); - if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { - s.reuse_failed = true; - return 0; - } - l.m.restore(l.s, k) catch { - s.reuse_failed = true; - return 0; - }; - s.cached = k.at; - return k.at; - } - - fn opening(b: *Backend, s: *lanes.Stream) !*Lane { - const prompt = s.prompt(); - if (prompt.len == 0) return error.EmptyPrompt; - const context = b.lanes[0].m.context; - if (prompt.len > context or s.max_new > context - prompt.len) return error.PastContext; - const l = b.laneOf(s) catch &b.lanes[b.free() orelse return error.NoFreeSlot]; - l.owner = s; - l.sampled = false; - if (cuda.sample.ruleFor(s.sampling)) |r| { - try b.upload(l.s, l.rule.ptr, std.mem.asBytes(&r)); - l.sampled = true; - } - l.len = 0; - try l.m.reset(l.s); - const at = resumeSaved(l, s); - l.len = at; - l.fill = at; - s.fill_at.store(@intCast(at), .monotonic); - return l; - } - - fn chunk(b: *Backend, s: *lanes.Stream, l: *Lane) !bool { - const prompt = s.prompt(); - const at = l.fill.?; - if (s.isCancelled()) return error.Cancelled; - var end = @min(prompt.len, (at / prompt_rows + 1) * prompt_rows); - for (s.reuse.marks) |mark| { - if (mark > at and mark < end) end = mark; - } - const done = end == prompt.len; - try l.m.forward(b.k, l.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); - if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last.ptr, l.m.s.logits, l.m.w.c.text.unpadded_vocab * 4, l.s.handle), "cuMemcpyDtoDAsync"); - l.len = end; - l.fill = if (done) null else end; - s.fill_at.store(@intCast(end), .monotonic); - if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) - hook.at(hook.ptr, s, @intCast(end)); - return done; - } - - fn handle(b: *Backend) usize { - const h = b.next; - b.next += 1; - return @intCast(h % token_ring); - } - - fn drawRows(b: *Backend, l: *Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { - const v = l.m.w.c.text.unpadded_vocab; - if (!l.sampled) return ops.top1(&b.k.glue, l.s, logits, rows, v, v, 0, l.m.s.t + at * 4, b.tokens.ptr + at * 4); - try ops.tobf(&b.k.glue, l.s, logits, rows, v, v, l.logits16.ptr, v, 0, v); - const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; - try b.upload(l.s, l.meta.ptr, std.mem.asBytes(&metadata)); - try b.k.draws.draw(l.s, l.logits16.ptr, v, l.rule.ptr, l.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); - } - - /// A ring token was drawn on its owner's stream; the ring does not record which, so every lane lands first. - fn read(ptr: *anyopaque, h: u64) anyerror!u32 { - const b = self(ptr); - if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; - var out: [1]u32 = undefined; - for (b.lanes) |l| if (l.owner != null) try l.s.synchronize(); - try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); - return out[0]; - } - - const vtable: be.Backend.VTable = .{ - .prefill = prefill, - .prefill_step = prefillStep, - .first = first, - .first_masked = firstMasked, - .queue = queue, - .read = read, - .verify = verify, - .keep = keep, - .draft = draft, - .release = release, - .reports_fill = true, - }; - - fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { - const b = self(ptr); - const l = try b.opening(s); - errdefer release(ptr, s); - while (!try b.chunk(s, l)) {} - } - - fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { - const b = self(ptr); - const going = b.laneOf(s) catch null; - const l = if (going != null and going.?.fill != null) going.? else try b.opening(s); - errdefer release(ptr, s); - return b.chunk(s, l); - } - - fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { - const b = self(ptr); - const l = try b.laneOf(s); - if (position != l.len or l.fill != null) return error.PositionMismatch; - const h = b.next; - try b.drawRows(l, l.last.ptr, 1, position, b.handle()); - return h; - } - - fn firstMasked(_: *anyopaque, _: *lanes.Stream, _: u64, _: []const u32) anyerror!u64 { - return error.StructuresUnsupported; - } - - fn feed(b: *Backend, value: be.Feed) !u32 { - return switch (value) { - .value => |v| v, - .handle => |h| read(b, h), - }; - } - - fn queue(ptr: *anyopaque, s: *lanes.Stream, value: be.Feed, position: u64) anyerror!u64 { - const b = self(ptr); - const l = try b.laneOf(s); - const token = try b.feed(value); - if (position != l.len + 1) return error.PositionMismatch; - try l.m.forward(b.k, l.s, &.{token}, l.len, 0, 1, false); - l.len += 1; - const h = b.next; - try b.drawRows(l, l.m.s.logits, 1, position, b.handle()); - return h; - } - - /// Every window's forward and draw is queued on its own lane before the first wait. - fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { - const b = self(ptr); - if (windows.len != out.len) return error.WindowCount; - for (windows) |w| { - if (w.held != 0) return error.NoHeldDrafts; - if (w.parents != null) return error.ChainsOnly; - if (w.masks.len != 0) return error.StructuresUnsupported; - const l = try b.laneOf(w.stream); - const n = w.rows(); - if (n == 0 or n > window_rows) return error.WindowTooWide; - l.base = l.len; - l.rows.clearRetainingCapacity(); - try l.rows.append(b.gpa, w.pending); - try l.rows.appendSlice(b.gpa, w.tokens); - for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; - try l.m.forward(b.k, l.s, l.rows.items, l.base, 0, n, true); - try b.drawRows(l, l.m.s.logits, n, w.positions[0], l.at); - } - for (windows, out) |w, o| { - const l = try b.laneOf(w.stream); - const n = w.rows(); - try l.s.synchronize(); - try b.tokens.download(l.at * 4, std.mem.sliceAsBytes(o.sampled[0..n])); - @memcpy(o.drafts[0 .. n - 1], l.rows.items[1..n]); - l.len = l.base + n; - } - } - - fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { - const b = self(ptr); - if (windows.len != paths.len) return error.WindowCount; - for (windows, paths) |w, path| { - const l = try b.laneOf(w.stream); - if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; - for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; - try l.m.rewind(b.k, l.s, path.len); - l.len = l.base + path.len; - } - } - - fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { - for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; - } - - /// A snapshot lands before it returns: another lane may restore it on its own stream. - pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const l = try b.laneOf(s); - if ((l.fill orelse l.len) != at) return error.NotAtMark; - const saved = try l.m.save(l.s, at); - errdefer l.m.drop(l.s, saved); - try l.s.synchronize(); - return saved; - } - - pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const l = try b.laneOf(s); - try l.m.restore(l.s, saved); - l.len = saved.at; - } - - /// Any lane may still be reading the snapshot: all of them land before its bytes go. - pub fn dropState(b: *Backend, saved: *Model.Saved) void { - for (b.lanes) |l| l.s.synchronize() catch {}; - b.lanes[0].m.drop(b.lanes[0].s, saved); - } - - fn release(ptr: *anyopaque, s: *lanes.Stream) void { - const b = self(ptr); - const l = b.laneOf(s) catch return; - l.rows.clearRetainingCapacity(); - l.owner = null; - } -}; diff --git a/zig/src/families/inkling2/loop_cache.zig b/zig/src/families/inkling2/loop_cache.zig deleted file mode 100644 index 3a52bda9af7..00000000000 --- a/zig/src/families/inkling2/loop_cache.zig +++ /dev/null @@ -1,155 +0,0 @@ -//! Inkling 2 Mini's loop host layout: 48 private visit caches, whole-state snapshots and one-rank admission. -const std = @import("std"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); - -pub fn validateLoad(c: *const config.Config, rank: usize, images: bool) !void { - if (rank != 1) return error.Inkling2LoopOneRankOnly; - if (images) return error.Inkling2LoopTextOnly; - const lp = c.text.loop orelse return error.Inkling2LoopRequired; - if (lp.rank != 64) return error.UnsupportedLoopGateRank; -} - -pub const SnapshotSlot = struct { - kv_offset: u64, - kv_bytes: u64, - conv_offset: u64, - conv_bytes: u64, -}; - -/// A stream or a saved prompt owns the same complete layout: no visit shares KV or convolution state with another. -pub const CacheLayout = struct { - slots: [config.max_visits]SnapshotSlot, - n: u32, - bytes: u64, - - pub fn init(c: *const config.Text, p: *const plan_.Plan, context: u32) !CacheLayout { - if (context == 0 or context > c.max_context or p.visits.len != c.visits()) return error.BadLoopCache; - var out: CacheLayout = undefined; - out.n = p.visits.len; - out.bytes = 0; - const conv_values = 3 * (2 * @as(u64, c.local.kv * c.local.dim) + 2 * @as(u64, c.hidden)); - for (p.visits.slice()) |visit| { - const i = visit.slot[@backingInt(plan_.Slot.conv)].?; - const layer = p.layers[visit.layer]; - const rows: u32 = @intCast(@min(2048, context)); - const tokens = if (layer.kind == .global) - std.mem.alignForward(u32, context, 64) - else - std.mem.alignForward(u32, c.window + rows - 1, 64); - const kv = try std.math.mul(u64, tokens, 2 * @as(u64, layer.heads.kv * layer.heads.dim * 2)); - // The recurrence rounds each site then widens its complete state to FP32 before the FMAs. - const conv = try std.math.mul(u64, conv_values, 4); - out.slots[i] = .{ .kv_offset = out.bytes, .kv_bytes = kv, .conv_offset = 0, .conv_bytes = conv }; - out.bytes = try std.math.add(u64, out.bytes, kv); - } - var conv_offset = out.bytes; - for (out.slots[0..out.n]) |*slot| { - slot.conv_offset = conv_offset; - conv_offset = try std.math.add(u64, conv_offset, slot.conv_bytes); - } - out.bytes = conv_offset; - return out; - } - - pub fn at(l: *const CacheLayout, visit: u32) SnapshotSlot { - return l.slots[visit]; - } -}; - -/// The serial lane adapter's admission rule. One request occupies one complete 48-visit stream. -pub const Admission = struct { - context: u32, - - pub fn fits(a: Admission, prompt: u32, max_tokens: u32) bool { - return prompt <= a.context and max_tokens <= a.context - prompt; - } -}; - -/// A prompt-cache save or restore copies every byte of this layout, including all four convolution recurrences. -pub fn snapshotBytes(l: *const CacheLayout) u64 { - return l.bytes; -} - -pub const Snapshot = struct { - bytes: []u8, - - pub fn save(gpa: std.mem.Allocator, state: []const u8, l: *const CacheLayout) !Snapshot { - if (state.len != l.bytes) return error.BadLoopSnapshot; - return .{ .bytes = try gpa.dupe(u8, state) }; - } - - pub fn restore(s: *const Snapshot, state: []u8, l: *const CacheLayout) !void { - if (s.bytes.len != l.bytes or state.len != l.bytes) return error.BadLoopSnapshot; - @memcpy(state, s.bytes); - } - - pub fn deinit(s: *Snapshot, gpa: std.mem.Allocator) void { - gpa.free(s.bytes); - s.* = undefined; - } -}; - -test "a saved prompt restores every visit byte and owns its copy" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - var prec: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &prec); - const layout = try CacheLayout.init(&c.text, &p, 1); - const state = try std.testing.allocator.alloc(u8, @intCast(layout.bytes)); - defer std.testing.allocator.free(state); - for (state, 0..) |*v, i| v.* = @truncate(i * 29 + 7); - var saved = try Snapshot.save(std.testing.allocator, state, &layout); - defer saved.deinit(std.testing.allocator); - @memset(state, 0xa5); - try saved.restore(state, &layout); - try std.testing.expectEqualSlices(u8, saved.bytes, state); - try std.testing.expectError(error.BadLoopSnapshot, Snapshot.save(std.testing.allocator, state[0 .. state.len - 1], &layout)); -} - -test "Mini has 48 independent KV and convolution slots and a whole-state snapshot" { - const config_test = @import("config_test.zig"); - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var why: config.Why = .{}; - const c = try config.parse(a, config_test.mini, &why); - var prec: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &prec); - const layout = try CacheLayout.init(&c.text, &p, 1_048_576); - try std.testing.expectEqual(@as(u32, 48), layout.n); - try std.testing.expectEqual(@as(u64, 3072 * 2 * 8 * 128 * 2), layout.at(0).kv_bytes); - try std.testing.expectEqual(@as(u64, 1_048_576 * 2 * 8 * 128 * 2), layout.at(5).kv_bytes); - try std.testing.expectEqual(@as(u64, 34_866_888_704), layout.bytes); - try std.testing.expectEqual(layout.bytes, snapshotBytes(&layout)); - try std.testing.expect((Admission{ .context = 8192 }).fits(8000, 192)); - try std.testing.expectEqual(@as(u64, 79_872), layout.at(0).conv_bytes); -} - -test "Mini loop load is one-rank text-only with rank-64 gated controllers" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - try validateLoad(&c, 1, false); - try std.testing.expectError(error.Inkling2LoopOneRankOnly, validateLoad(&c, 2, false)); - try std.testing.expectError(error.Inkling2LoopTextOnly, validateLoad(&c, 1, true)); -} - -test "pass two resets and only completed passes with a successor capture message banks" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - var prec: [24]plan_.Precision = @splat(.nvfp4); - const p = try plan_.build(&c.text, &prec); - const lp = c.text.loop.?; - var banks: u32 = 0; - for (p.visits.slice(), 0..) |visit, i| { - if (visit.pass == 1 and visit.layer == lp.start) try std.testing.expect(p.messages(@intCast(i))); - if (visit.pass < lp.passes - 1 and visit.leave) banks += 1; - } - try std.testing.expectEqual(lp.passes - 1, banks); -} diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig deleted file mode 100644 index e019f3807a3..00000000000 --- a/zig/src/families/inkling2/loop_engine.zig +++ /dev/null @@ -1,578 +0,0 @@ -//! One-rank, text-only Inkling 2 Mini: the complete 48-visit CUDA forward. -const std = @import("std"); -const cuda = @import("cuda"); -const config = @import("config.zig"); -const loop = @import("loop_cache.zig"); -const weights_ = @import("loop_weights.zig"); -const ops = @import("ops.zig"); -const attention = @import("kernels.zig"); -const modelopt = @import("modelopt.zig"); -const loop_math = @import("loop_math_cuda.zig"); - -pub const prompt_rows: usize = 2048; -pub const window_rows: usize = 16; - -pub const Kernels = struct { - glue: ops.Kernels, - attn: attention.Kernels, - moe: modelopt.Kernels, - loop: loop_math.Kernels, - sample_mod: cuda.Module, - draws: cuda.sample.Draws, - - pub fn load(ctx: *const cuda.Context) !Kernels { - const d = ctx.d; - var glue = try ops.Kernels.load(d); - errdefer glue.unload(); - var attn = try attention.Kernels.load(d); - errdefer attn.unload(); - const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); - var moe = try modelopt.Kernels.load(d, sms); - errdefer moe.unload(); - var lm = try loop_math.Kernels.load(d); - errdefer lm.unload(); - var sample_mod = try cuda.Module.load(d, cuda.kernels.sample); - errdefer sample_mod.unload(); - return .{ - .glue = glue, - .attn = attn, - .moe = moe, - .loop = lm, - .sample_mod = sample_mod, - .draws = try cuda.sample.Draws.resolve(sample_mod), - }; - } - - pub fn deinit(k: *Kernels) void { - k.sample_mod.unload(); - k.loop.unload(); - k.moe.unload(); - k.attn.unload(); - k.glue.unload(); - k.* = undefined; - } -}; - -const Scratch = struct { - ids: u64, - pos: u64, - seg_of: u64, - segs: u64, - tiles: u64, - blocks: [ops.max_blocks]u64 = @splat(0), - partial_a: u64, - partial_b: u64, - prelude: u64, - bank0: u64, - bank1: u64, - raw: u64, // three FP32 AR/gate rows per token - messages: u64, // four FP32 message rows per token - normalized: u64, // three BF16 rows per token - t: u64, - q_raw: u64, - rel_raw: u64, - sink: u64, - gate: u64, - k_raw: u64, - v_raw: u64, - k_conv: u64, - v_conv: u64, - k_dynamic: u64, - v_dynamic: u64, - q_prepared: u64, - rel_prepared: u64, - rel_table: u64, - part_o: u64, - part_ml: u64, - attn_heads: u64, - attn_out: u64, - route_scores: u64, - route_pick: u64, - route_weights: u64, - moe_out: u64, - moe_scratch: u64, - hidden: u64, - logits: u64, - backup: u64, - hist: u64, - rewind_sites: u64, -}; - -pub const Model = struct { - gpa: std.mem.Allocator, - d: *const cuda.Driver, - w: *const weights_.Weights, - context: usize, - layout: loop.CacheLayout, - cache: cuda.DeviceBuffer, - s: Scratch = undefined, - buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, - - fn alloc(m: *Model, bytes: usize) !u64 { - var b = try cuda.DeviceBuffer.alloc(m.d, @max(bytes, 256)); - errdefer b.free(); - try m.buffers.append(m.gpa, b); - return b.ptr; - } - - fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(m.d, dst, bytes, s); - } - - fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { - try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); - } - - fn zeros(m: *const Model, s: cuda.Stream, ptr: u64, bytes: usize) !void { - try m.d.check(m.d.api.cuMemsetD8Async(ptr, 0, bytes, s.handle), "cuMemsetD8Async"); - } - - fn layerGeometry(m: *const Model, layer: u32) attention.Layer { - return if (config.isGlobal(layer)) - attention.Layer.global(@intCast(m.context)) - else - attention.Layer.sliding(m.w.c.text.window, @intCast(@min(prompt_rows, m.context))); - } - - fn cacheOf(m: *const Model, visit: u32) attention.Cache { - const slot = m.layout.at(visit); - const base = m.cache.ptr + slot.kv_offset; - return .{ .k = base, .v = base + slot.kv_bytes / 2 }; - } - - fn convOf(m: *const Model, visit: u32, site: usize) u64 { - const c = m.w.c.text; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const h: usize = c.hidden; - const widths = [4]usize{ kv, kv, h, h }; - var at = m.cache.ptr + m.layout.at(visit).conv_offset; - for (0..site) |i| at += 3 * widths[i] * 4; - return at; - } - - fn histOf(m: *const Model, visit: u32, site: usize) u64 { - const c = m.w.c.text; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const h: usize = c.hidden; - const widths = [4]usize{ kv, kv, h, h }; - var at = m.s.hist + visit * window_rows * (2 * kv + 2 * h) * 4; - for (0..site) |i| at += window_rows * widths[i] * 4; - return at; - } - - fn backupOf(m: *const Model, visit: u32, site: usize) usize { - return m.convOf(visit, site) - (m.cache.ptr + m.layout.at(0).conv_offset); - } - - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const weights_.Weights, context: usize) !Model { - const layout = try loop.CacheLayout.init(&w.c.text, &w.p, @intCast(context)); - var m: Model = .{ - .gpa = gpa, - .d = d, - .w = w, - .context = context, - .layout = layout, - .cache = try cuda.DeviceBuffer.alloc(d, layout.bytes), - }; - errdefer m.cache.free(); - errdefer m.deinitBuffers(); - const c = w.c.text; - const h: usize = c.hidden; - const q: usize = @as(usize, c.global.q) * c.global.dim; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const rows = prompt_rows; - const rel_rows = rows * c.global.q * attention.extent; - const local = attention.Layer.sliding(c.window, @intCast(@min(prompt_rows, context))); - const global = attention.Layer.global(@intCast(context)); - const local_slots = attention.slotsFor(local, context); - const global_slots = attention.slotsFor(global, context); - const part_slots = @max(rows * c.local.q * local_slots, rows * c.global.q * global_slots); - const hist_values = @as(usize, w.p.visits.len) * (2 * kv + 2 * h) * window_rows; - m.s = .{ - .ids = try m.alloc(rows * 4), - .pos = try m.alloc(rows * 4), - .seg_of = try m.alloc(rows * 4), - .segs = try m.alloc(@sizeOf(attention.Seg)), - .tiles = try m.alloc(128 * @sizeOf(attention.Tile)), - .partial_a = try m.alloc(rows * h * 2), - .partial_b = try m.alloc(rows * h * 2), - .prelude = try m.alloc(rows * h * 2), - .bank0 = try m.alloc(rows * h * 2), - .bank1 = try m.alloc(rows * h * 2), - .raw = try m.alloc(3 * rows * h * 4), - .messages = try m.alloc(4 * rows * h * 4), - .normalized = try m.alloc(3 * rows * h * 2), - .t = try m.alloc(rows * h * 4), - .q_raw = try m.alloc(rows * q * 2), - .rel_raw = try m.alloc(rows * c.global.q * c.d_rel * 2), - .sink = try m.alloc(rows * c.global.q * 2), - .gate = try m.alloc(rows * q * 2), - .k_raw = try m.alloc(rows * kv * 2), - .v_raw = try m.alloc(rows * kv * 2), - .k_conv = try m.alloc(rows * kv * 2), - .v_conv = try m.alloc(rows * kv * 2), - .k_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), - .v_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), - .q_prepared = try m.alloc(rows * q * 2), - .rel_prepared = try m.alloc(rows * c.global.q * c.d_rel * 2), - .rel_table = try m.alloc(rel_rows * 2), - .part_o = try m.alloc(part_slots * attention.head_dim * 4), - .part_ml = try m.alloc(part_slots * 8), - .attn_heads = try m.alloc(rows * q * 2), - .attn_out = try m.alloc(rows * h * 2), - .route_scores = try m.alloc(rows * c.experts * 4), - .route_pick = try m.alloc(rows * c.experts * 4), - .route_weights = try m.alloc(rows * c.experts * 4), - .moe_out = try m.alloc(rows * h * 2), - .moe_scratch = try m.alloc(try modelopt.scratchBytes(rows, c.topk, h, c.expert_inter)), - .hidden = try m.alloc(rows * h * 2), - .logits = try m.alloc(window_rows * c.unpadded_vocab * 4), - .backup = try m.alloc(layout.bytes - layout.at(0).conv_offset), - .hist = try m.alloc(hist_values * 4), - .rewind_sites = try m.alloc(w.p.visits.len * 4 * @sizeOf(ops.RewindSite)), - }; - for (0..ops.max_blocks) |i| m.s.blocks[i] = try m.alloc(rows * h * 2); - var sites: [config.max_visits * 4]ops.RewindSite = undefined; - for (0..w.p.visits.len) |v| for (0..4) |site| { - const kv_site = site < 2; - sites[v * 4 + site] = .{ - .state = m.convOf(@intCast(v), site), - .hist = @intCast(m.histOf(@intCast(v), site) - m.s.hist), - .backup = @intCast(m.backupOf(@intCast(v), site)), - .c = @intCast(if (kv_site) kv else h), - }; - }; - try m.upload(s, m.s.rewind_sites, std.mem.sliceAsBytes(sites[0 .. w.p.visits.len * 4])); - try m.zeros(s, m.cache.ptr + m.layout.at(0).conv_offset, layout.bytes - m.layout.at(0).conv_offset); - try s.synchronize(); - return m; - } - - fn deinitBuffers(m: *Model) void { - for (m.buffers.items) |*b| b.free(); - m.buffers.deinit(m.gpa); - } - - /// Device bytes one sequence holds: its cache and its forward scratch. - pub fn heldBytes(m: *const Model) u64 { - var n: u64 = m.cache.len; - for (m.buffers.items) |b| n += b.len; - return n; - } - - pub fn deinit(m: *Model) void { - m.deinitBuffers(); - m.cache.free(); - m.* = undefined; - } - - pub fn reset(m: *const Model, s: cuda.Stream) !void { - try m.zeros(s, m.cache.ptr + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); - } - - pub fn rewind(m: *const Model, k: *const Kernels, s: cuda.Stream, kept: usize) !void { - if (kept > window_rows) return error.WindowTooWide; - try ops.rewind(&k.glue, s, m.s.rewind_sites, m.w.p.visits.len * 4, m.w.c.text.hidden, m.s.backup, m.s.hist, 0, 0, kept); - } - - fn arBlocks(m: *const Model, blocks: []const u64, partial: u64, query: u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) loop_math.ArArgs { - var a: loop_math.ArArgs = .{ - .partial = partial, - .query = query, - .out = out, - .n_blocks = @intCast(blocks.len), - .partial_bf16 = @intFromBool(partial_bf16), - .nq = @intCast(nq), - .rows = @intCast(rows), - .c = @intCast(m.w.c.text.hidden), - .eps = m.w.c.text.eps, - }; - for (blocks, 0..) |b, i| a.blocks[i] = b; - return a; - } - - fn mixArgs(m: *const Model, blocks: []const u64, partial: u64, query: u64, norms: [3]u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) ops.MixArgs { - var a: ops.MixArgs = .{ - .partial = partial, - .query = query, - .out = out, - .n_blocks = @intCast(blocks.len), - .partial_bf16 = @intFromBool(partial_bf16), - .nq = @intCast(nq), - .rows = @intCast(rows), - .c = @intCast(m.w.c.text.hidden), - .eps = m.w.c.text.eps, - }; - for (blocks, 0..) |b, i| a.blocks[i] = b; - a.norm = norms; - return a; - } - - /// One prompt chunk or one decode window. `record` retains every convolution input for exact prefix rollback. - pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, tokens: []const u32, p0: usize, head0: usize, heads: usize, record: bool) !void { - const c = m.w.c.text; - const rows = tokens.len; - const h: usize = c.hidden; - if (rows == 0 or rows > prompt_rows or p0 + rows > m.context or (!record and heads > window_rows) or head0 + heads > rows) - return error.BadLoopRows; - if (record and rows > window_rows) return error.WindowTooWide; - var ids: [prompt_rows]i32 = undefined; - var pos: [prompt_rows]i32 = undefined; - var seg_of: [prompt_rows]i32 = @splat(0); - for (tokens, 0..) |token, i| { - ids[i] = @intCast(token); - pos[i] = @intCast(p0 + i); - } - try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ids[0..rows])); - try m.upload(s, m.s.pos, std.mem.sliceAsBytes(pos[0..rows])); - try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(seg_of[0..rows])); - const seg: attention.Seg = .{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p0), .off = 0 }; - try m.upload(s, m.s.segs, std.mem.asBytes(&seg)); - if (record) try m.copy(s, m.s.backup, m.cache.ptr + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); - - try ops.embed(&k.glue, s, m.s.ids, rows, m.w.embed, m.w.embed_norm, m.s.partial_a, h, c.eps); - var partial = m.s.partial_a; - var next = m.s.partial_b; - var n_blocks: usize = 0; - const lp = c.loop.?; - - for (m.w.p.visits.steps[0..m.w.p.visits.len]) |visit| { - const layer = m.w.p.at(visit.layer); - const lw = &m.w.layers[visit.layer]; - if (visit.pass >= 1 and visit.layer == lp.start) { - try m.copy(s, partial, m.s.prelude, rows * h * 2); - n_blocks = 1; // block zero is the embedding; later passes never inherit completed blocks - } - const messages = visit.pass > 0; - if (messages) { - const core_j = visit.layer - lp.start; - try loop_math.messages(&k.loop, s, m.s.bank0, m.s.bank1, m.w.cross_qm + 2 * core_j * h * 4, m.w.cross_kv + 2 * core_j * h * 4, m.s.messages, rows, 1, h, c.eps); - } - const nq: usize = if (layer.kind == .global) 3 else 1; - const query = m.w.attn_queries[visit.layer]; - const blocks = m.s.blocks[0..n_blocks]; - const raw_stride = rows * h * 4; - const norm_stride = rows * h * 2; - if (messages) { - if (nq == 3) { - try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw, 3, true, rows)); - } else { - // A sliding layer stores one query; each gated role gets its own AR result from that query. - for (0..3) |role| try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw + role * raw_stride, 1, true, rows)); - } - for (0..3) |role| { - const ctl = lw.controllers[role]; - try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); - const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; - try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); - } - } else { - try ops.mix(&k.glue, s, m.mixArgs(blocks, partial, query, lw.attn.norms, m.s.normalized, nq, true, rows)); - } - const u_q = m.s.normalized; - const u_k = if (layer.kind == .global or messages) m.s.normalized + norm_stride else u_q; - const u_v = if (layer.kind == .global or messages) m.s.normalized + 2 * norm_stride else u_q; - const q_width: usize = @as(usize, layer.heads.q) * layer.heads.dim; - const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; - try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); - try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, false); - - const geometry = m.layerGeometry(visit.layer); - const cache = m.cacheOf(visit.of(.conv).?); - const dynamic = layer.kind == .global; - for (0..2) |kind| { - const input = if (kind == 0) u_k else u_v; - const dyn_out = if (kind == 0) m.s.k_dynamic else m.s.v_dynamic; - if (dynamic) { - try ops.rowdot(&k.glue, s, input, if (kind == 0) lw.attn.k_dynamic else lw.attn.v_dynamic, dyn_out, rows, layer.heads.kv * config.conv_taps, h, false, false); - try loop_math.roundBf16(&k.loop, s, dyn_out, dyn_out, rows * layer.heads.kv * config.conv_taps); - } - try ops.conv(&k.glue, s, .{ - .x = if (kind == 0) m.s.k_raw else m.s.v_raw, - .state = m.convOf(visit.of(.conv).?, kind), - .w = if (kind == 0) lw.attn.k_conv else lw.attn.v_conv, - .dyn = if (dynamic) dyn_out else 0, - .out = if (kind == 0) m.s.k_conv else m.s.v_conv, - .hist = if (record) m.histOf(visit.of(.conv).?, kind) else 0, - .x_bf16 = 1, - .heads = @intCast(layer.heads.kv), - .c = @intCast(kv_width), - .rows = @intCast(rows), - .mode = 0, - }, 1); - } - var tiles: [128]attention.Tile = undefined; - const n_tiles = try attention.tiles(&.{seg}, layer.heads.q / layer.heads.kv, &tiles); - try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); - const stride = attention.slotsFor(geometry, m.context); - const part_capacity = prompt_rows * layer.heads.q * stride; - const r: attention.Rows = .{ - .rows = @intCast(rows), - .heads = layer.heads.q, - .kv_heads = layer.heads.kv, - .pos = m.s.pos, - .seg_of = m.s.seg_of, - .segs = m.s.segs, - .tiles = m.s.tiles, - .n_tiles = @intCast(n_tiles), - .last_pos = @intCast(p0 + rows - 1), - }; - const prep: attention.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = @floatFromInt(c.log_floor), .alpha = c.log_alpha, .eps = c.eps }; - try attention.prep(&k.attn, s, r, geometry, prep, .{ m.s.q_raw, m.s.k_conv, m.s.v_conv, m.s.rel_raw }, .{ lw.attn.q_scale, lw.attn.rel_scale }, m.s.q_prepared, m.s.rel_prepared, cache); - try attention.relTable(&k.attn, s, r, m.s.rel_prepared, lw.attn.rel_proj, m.s.rel_table); - try attention.attend(&k.attn, s, r, geometry, stride, part_capacity, m.s.q_prepared, cache, m.s.rel_table, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.attn_heads); - try ops.rowdot(&k.glue, s, m.s.attn_heads, lw.attn.wo, m.s.attn_out, rows, h, q_width, true, false); - - if (layer.boundary) { - try m.copy(s, m.s.blocks[n_blocks], partial, rows * h * 2); - n_blocks += 1; - } - try ops.conv(&k.glue, s, .{ - .x = m.s.attn_out, - .state = m.convOf(visit.of(.conv).?, 2), - .w = lw.attn_conv, - .base = if (layer.boundary) 0 else partial, - .resid = m.s.t, - .hist = if (record) m.histOf(visit.of(.conv).?, 2) else 0, - .x_bf16 = 1, - .c = @intCast(h), - .rows = @intCast(rows), - .mode = 1, - }, 1); - - const mlp_query = m.w.mlp_queries[visit.layer]; - const mlp_blocks = m.s.blocks[0..n_blocks]; - if (messages) { - try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); - const ctl = lw.controllers[3]; - try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); - try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); - } else { - try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); - } - try ops.rowdot(&k.glue, s, m.s.normalized, lw.router, m.s.route_scores, rows, c.experts, h, false, true); - try ops.topk(&k.glue, s, m.s.route_scores, lw.router_bias, m.s.route_pick, m.s.route_weights, rows, c.experts, c.topk, c.route_scale); - try modelopt.run(&k.moe, s, lw.experts, .{ .gate = c.gate_cap, .up = c.up_cap }, m.s.normalized, h, m.s.route_pick, m.s.route_weights, rows, c.topk, m.s.moe_out, m.s.moe_scratch); - try ops.conv(&k.glue, s, .{ - .x = m.s.moe_out, - .state = m.convOf(visit.of(.conv).?, 3), - .w = lw.mlp_conv, - .resid = m.s.t, - .out = next, - .hist = if (record) m.histOf(visit.of(.conv).?, 3) else 0, - .x_bf16 = 1, - .c = @intCast(h), - .rows = @intCast(rows), - .mode = 2, - }, 1); - std.mem.swap(u64, &partial, &next); - - if (visit.layer + 1 == lp.start) try m.copy(s, m.s.prelude, partial, rows * h * 2); - if (visit.pass < lp.passes - 1 and visit.layer + 1 == lp.end) { - try m.copy(s, m.s.bank0, m.s.blocks[n_blocks - 1], rows * h * 2); - try m.copy(s, m.s.bank1, partial, rows * h * 2); - } - } - - if (heads == 0) return; - try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); - try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); - try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); - try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); - } - - pub const Saved = struct { - at: u32, - visits: u32, - passes: u32, - hidden: u32, - buf: cuda.DeviceBuffer, - }; - - /// Compact bytes for all valid K/V rows and every convolution state of all 48 visits. - pub fn snapshotBytes(m: *const Model, at: usize) u64 { - var bytes = m.layout.bytes - m.layout.at(0).conv_offset; - for (0..m.w.p.visits.len) |v| { - const layer = m.w.p.at(m.w.p.visits.steps[v].layer); - const global = layer.kind == .global; - const count = if (global) at else @min(at, m.w.c.text.window - 1); - const row = @as(u64, layer.heads.kv) * layer.heads.dim * 2; - bytes += 2 * count * row; - } - return bytes; - } - - fn copyState(m: *const Model, s: cuda.Stream, saved: *const Saved, out: bool) !void { - const at: usize = saved.at; - var off: usize = 0; - for (0..m.w.p.visits.len) |v| { - const visit = m.w.p.visits.steps[v]; - const layer = m.w.p.at(visit.layer); - const geometry = m.layerGeometry(visit.layer); - const rb = @as(usize, layer.heads.dim) * 2; - const head_bytes = @as(usize, geometry.ring) * rb; // caches are [kv head][ring slot][dim] (attention.cu prep) - const global = layer.kind == .global; - const count = if (global) at else @min(at, m.w.c.text.window - 1); - const first = at - count; - const cache = m.cacheOf(visit.of(.conv).?); - for ([2]u64{ cache.k, cache.v }) |base| for (0..layer.heads.kv) |h| { - var pos = first; - while (pos < at) { - const row = pos % geometry.ring; - const n = @min(at - pos, geometry.ring - row); - const dev = base + h * head_bytes + row * rb; - const src = if (out) dev else saved.buf.ptr + off; - const dst = if (out) saved.buf.ptr + off else dev; - try m.copy(s, dst, src, n * rb); - off += n * rb; - pos += n; - } - }; - } - const conv = m.cache.ptr + m.layout.at(0).conv_offset; - const bytes = m.layout.bytes - m.layout.at(0).conv_offset; - try m.copy(s, if (out) saved.buf.ptr + off else conv, if (out) conv else saved.buf.ptr + off, bytes); - } - - pub fn save(m: *const Model, s: cuda.Stream, at: u32) !*Saved { - if (at == 0 or at > m.context) return error.NotAtMark; - const gpa = m.gpa; - const saved = try gpa.create(Saved); - errdefer gpa.destroy(saved); - const lp = m.w.c.text.loop.?; - saved.* = .{ .at = at, .visits = m.w.p.visits.len, .passes = lp.passes, .hidden = m.w.c.text.hidden, .buf = try cuda.DeviceBuffer.alloc(m.d, @intCast(@max(snapshotBytes(m, at), 256))) }; - errdefer saved.buf.free(); - try m.copyState(s, saved, true); - return saved; - } - - pub fn restore(m: *const Model, s: cuda.Stream, saved: *const Saved) !void { - const lp = m.w.c.text.loop.?; - if (saved.visits != m.w.p.visits.len or saved.passes != lp.passes or saved.hidden != m.w.c.text.hidden) - return error.StateOfAnotherModel; - if (saved.at == 0 or saved.at > m.context or saved.buf.len < snapshotBytes(m, saved.at)) return error.BadLoopSnapshot; - try m.copyState(s, saved, false); - } - - pub fn drop(m: *const Model, s: cuda.Stream, saved: *Saved) void { - s.synchronize() catch {}; - saved.buf.free(); - m.gpa.destroy(saved); - } -}; - -test "pass snapshots and rollback layout cover every visit" { - const config_test = @import("config_test.zig"); - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - const c = try config.parse(arena.allocator(), config_test.mini, &why); - var precisions: [24]@import("plan.zig").Precision = @splat(.nvfp4); - const p = try @import("plan.zig").build(&c.text, &precisions); - const layout = try loop.CacheLayout.init(&c.text, &p, 4096); - try std.testing.expectEqual(@as(u32, 48), layout.n); - try std.testing.expect(layout.at(17).kv_offset != layout.at(29).kv_offset); - try std.testing.expectEqual(@as(u64, layout.at(46).conv_offset + layout.at(46).conv_bytes), layout.at(47).conv_offset); -} diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig deleted file mode 100644 index 869e9f91ae3..00000000000 --- a/zig/src/families/inkling2/loop_math_cuda.zig +++ /dev/null @@ -1,148 +0,0 @@ -//! Inkling 2 Mini loop math (inkling2/loop_math.cu): raw AR, two-bank messages, rank-64 gates and split QKV inputs. -const std = @import("std"); -const cuda = @import("cuda"); - -pub const rank = 64; -pub const max_blocks = 8; -pub const max_queries = 3; - -/// loop_math.cu's ArArgs, field for field. `out[q][row][c]` is FP32 AR output before any controller or RMSNorm. -pub const ArArgs = extern struct { - blocks: [max_blocks]u64 = @splat(0), // BF16 [rows][c], each a completed block state - partial: u64, // BF16 when partial_bf16 != 0, otherwise FP32; always the final AR source - query: u64, // FP32 [nq][c] - out: u64, // FP32 [nq][rows][c] - n_blocks: i32, - partial_bf16: i32, - nq: i32, - rows: i32, - c: i32, - eps: f32, -}; - -pub const Kernels = struct { - mod: cuda.Module, - ar_fn: cuda.Function, - messages_fn: cuda.Function, - gate_fn: cuda.Function, - project_qkv_fn: cuda.Function, - round_bf16_fn: cuda.Function, - - pub fn load(d: *const cuda.Driver) !Kernels { - if (!cuda.kernels.available) return error.BuiltWithoutKernels; - var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop_math); - errdefer mod.unload(); - return .{ - .mod = mod, - .ar_fn = try mod.function("tf_ink2_loop_ar"), - .messages_fn = try mod.function("tf_ink2_loop_messages"), - .gate_fn = try mod.function("tf_ink2_loop_gate"), - .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), - .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), - }; - } - - pub fn unload(k: *Kernels) void { - k.mod.unload(); - k.* = undefined; - } -}; - -fn int(x: anytype) i32 { - return @intCast(x); -} - -fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { - try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); -} - -/// Unnormalized block attention residual. No scratch; nq <= 3 and at most 8 completed blocks plus `partial`. -pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { - if (a.n_blocks < 0 or a.n_blocks > max_blocks or a.nq <= 0 or a.nq > max_queries or a.rows <= 0 or a.c <= 0) - return error.Inkling2LoopArShape; - var args: cuda.Args = .{}; - args.add(a); - try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); -} - -/// Messages: BF16 banks, even/odd qm/kv FP32 queries; output [core][role][row][c] (role-major planes). -pub fn messages( - k: *const Kernels, - s: cuda.Stream, - bank0_bf16: u64, - bank1_bf16: u64, - queries_qm_f32: u64, - queries_kv_f32: u64, - out_f32: u64, - rows: usize, - core_layers: usize, - c: usize, - eps: f32, -) !void { - if (rows == 0 or core_layers == 0 or c == 0) return error.Inkling2LoopMessageShape; - var a: cuda.Args = .{}; - for ([_]u64{ bank0_bf16, bank1_bf16, queries_qm_f32, queries_kv_f32, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(core_layers), int(c) }) |v| a.add(v); - a.add(eps); - try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); -} - -/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. -pub fn gate( - k: *const Kernels, - s: cuda.Stream, - state_f32: u64, - message_f32: u64, - down_bf16: u64, - forget_bf16: u64, - gain_bf16: u64, - out_f32: u64, - rows: usize, - c: usize, - eps: f32, -) !void { - if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; - var a: cuda.Args = .{}; - for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(c) }) |v| a.add(v); - a.add(eps); - try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); -} - -/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. -pub fn projectQkv( - k: *const Kernels, - s: cuda.Stream, - u_q: u64, - u_k: u64, - u_v: u64, - wq: u64, - wk: u64, - wv: u64, - raw_q: u64, - raw_k: u64, - raw_v: u64, - rows: usize, - c: usize, - q_width: usize, - kv_width: usize, -) !void { - if (rows == 0 or c == 0 or q_width == 0 or kv_width == 0) return error.Inkling2LoopQkvShape; - var a: cuda.Args = .{}; - for ([_]u64{ u_q, u_k, u_v, wq, wk, wv, raw_q, raw_k, raw_v }) |v| a.add(v); - for ([_]i32{ int(rows), int(c), int(q_width), int(kv_width) }) |v| a.add(v); - try go(k.project_qkv_fn, s, .{ .x = @intCast((rows + 15) / 16), .y = @intCast((@max(q_width, kv_width) + 15) / 16), .z = 3 }, 256, &a); -} - -/// BF16-round FP32 then widen, preserving section 6.3 unlike rowdot(false); in/out may alias, no scratch, n=0 no-op. -pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n: usize) !void { - if (n == 0) return; - var a: cuda.Args = .{}; - for ([_]u64{ in_f32, out_f32 }) |v| a.add(v); - a.add(@as(i64, @intCast(n))); - try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); -} - -test "loop math argument ABI" { - try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); -} diff --git a/zig/src/families/inkling2/loop_model.zig b/zig/src/families/inkling2/loop_model.zig deleted file mode 100644 index c56b1ce7a2e..00000000000 --- a/zig/src/families/inkling2/loop_model.zig +++ /dev/null @@ -1,464 +0,0 @@ -//! f64 Mini: f32 sums/combine ascend (A12), bf16 experts/acts (A1/A2), f32 F/G (A7), postdot scale (A14); casts round. -const std = @import("std"); -const bf = @import("bf16_round"); - -pub const hidden_size = 2304; -pub const gate_rank = 64; -pub const physical_layers = 24; -pub const core_start = 6; -pub const core_end = 18; -pub const core_layers = core_end - core_start; -pub const num_passes = 3; -pub const visit_count = 48; -pub const message_roles = 4; -pub const rms_eps = 1e-6; - -pub const ShapeError = error{BadShape}; -pub const VisitError = error{BadVisit}; -pub const DriverError = error{ BadShape, BadVisit, BadDriverState, BadSequence }; - -fn narrow32(v: f64) f32 { - return @floatCast(v); -} - -fn widen32(v: f32) f64 { - return @floatCast(v); -} - -/// One round to nearest-even bf16; the returned f64 is exactly that bf16 value. -pub fn bf16(v: f64) f64 { - return bf.bf16(v); -} - -/// rho(x), with an f32 ordered sum of squares and the specified f32 mean/rsqrt/multiply. -pub fn rms(x: []const f64, eps: f64, out: []f64) ShapeError!void { - if (x.len == 0 or out.len != x.len or !std.math.isFinite(eps) or eps < 0) return error.BadShape; - var squares: f32 = 0; - for (x) |v| { - const a = narrow32(v); - squares += a * a; - } - const mean = squares / @as(f32, @floatFromInt(x.len)); - const inverse: f32 = 1 / @sqrt(mean + narrow32(eps)); - for (x, out) |v, *o| o.* = widen32(narrow32(v) * inverse); -} - -/// N_w(x): no bf16 rounding between rho and the weight product, one bf16 rounding at the end. -pub fn weightedRms(x: []const f64, weight: []const f64, eps: f64, out: []f64, scratch: []f64) ShapeError!void { - if (weight.len != x.len or scratch.len != x.len) return error.BadShape; - try rms(x, eps, scratch); - for (scratch, weight, out) |v, w, *o| o.* = bf16(widen32(narrow32(w) * narrow32(v))); -} - -/// binary32(1/sqrt(H)); in particular Mini's value is binary32(1/48), not a double scale. -pub fn residualScale(hidden: usize) ShapeError!f32 { - if (hidden == 0) return error.BadShape; - return narrow32(1 / @sqrt(@as(f64, @floatFromInt(hidden)))); -} - -fn normalizeSources(states: []const f64, partial: []const f64, eps: f64, normalized: []f64) ShapeError!usize { - if (partial.len == 0 or states.len % partial.len != 0) return error.BadShape; - const h = partial.len; - const count = states.len / h + 1; - if (normalized.len != count * h) return error.BadShape; - for (0..count - 1) |i| try rms(states[i * h ..][0..h], eps, normalized[i * h ..][0..h]); - try rms(partial, eps, normalized[(count - 1) * h ..][0..h]); - return count; -} - -fn retrieve(normalized: []const f64, query: []const f64, out: []f64, weights: []f64) ShapeError!void { - if (query.len == 0 or out.len != query.len or normalized.len % query.len != 0) return error.BadShape; - const h = query.len; - const count = normalized.len / h; - if (count == 0 or weights.len != count) return error.BadShape; - const scale = try residualScale(h); - var top: f32 = -std.math.inf(f32); - for (0..count) |i| { - var dot: f32 = 0; - for (query, normalized[i * h ..][0..h]) |q, v| dot += narrow32(q) * narrow32(v); - const logit = dot * scale; - weights[i] = widen32(logit); - top = @max(top, logit); - } - var denominator: f32 = 0; - for (weights) |*w| { - const d = narrow32(w.* - widen32(top)); - const e = @exp(d); - w.* = widen32(e); - denominator += e; - } - @memset(out, 0); - for (0..count) |i| { - const weight = narrow32(weights[i]) / denominator; - for (out, normalized[i * h ..][0..h]) |*o, v| { - const a = narrow32(o.*); - o.* = widen32(a + weight * narrow32(v)); - } - } -} - -/// AR_Q(S,p): states[S][H], queries/out[Q][H] row-major; empty S okay, partial last, normalize before attention. -pub fn attentionResidual(gpa: std.mem.Allocator, states: []const f64, partial: []const f64, queries: []const f64, query_rows: usize, eps: f64, out: []f64) !void { - if (partial.len == 0 or query_rows == 0 or states.len % partial.len != 0) return error.BadShape; - const h = partial.len; - if (queries.len != query_rows * h or out.len != queries.len) return error.BadShape; - const count = states.len / h + 1; - const normalized = try gpa.alloc(f64, count * h); - defer gpa.free(normalized); - const weights = try gpa.alloc(f64, count); - defer gpa.free(weights); - _ = try normalizeSources(states, partial, eps, normalized); - for (0..query_rows) |q| try retrieve(normalized, queries[q * h ..][0..h], out[q * h ..][0..h], weights); -} - -pub const MessageRole = enum(u2) { q = 0, k = 1, v = 2, mlp = 3 }; - -/// The previous pass's B_12 and P_18. No embedding, prelude, or current-pass state is included. -pub const MessageBank = struct { - block: []const f64, - partial: []const f64, -}; - -/// Both checkpoint tensors in their stored row-major layouts: 24 rows by H. -pub const MessageQueries = struct { - q_mlp: []const f64, - kv: []const f64, - - /// Core j uses row 2j for q/k and row 2j+1 for mlp/v, in their respective tensors. - pub fn row(q: MessageQueries, core: usize, role: MessageRole, hidden: usize) ShapeError![]const f64 { - if (core >= core_layers or hidden == 0 or q.q_mlp.len != 2 * core_layers * hidden or q.kv.len != 2 * core_layers * hidden) return error.BadShape; - const odd: usize = @intFromBool(role == .mlp or role == .v); - const row_index = 2 * core + odd; - const source = if (role == .q or role == .mlp) q.q_mlp else q.kv; - return source[row_index * hidden ..][0..hidden]; - } -}; - -fn bankNormalized(gpa: std.mem.Allocator, bank: MessageBank, eps: f64) ![]f64 { - if (bank.block.len == 0 or bank.partial.len != bank.block.len) return error.BadShape; - const normalized = try gpa.alloc(f64, 2 * bank.block.len); - errdefer gpa.free(normalized); - try rms(bank.block, eps, normalized[0..bank.block.len]); - try rms(bank.partial, eps, normalized[bank.block.len..]); - return normalized; -} - -/// One of the 48 cross-pass messages. Its bank values and output are binary32 values held in f64. -pub fn crossPassMessage(gpa: std.mem.Allocator, bank: MessageBank, query: []const f64, eps: f64, out: []f64) !void { - if (query.len != bank.block.len or out.len != query.len) return error.BadShape; - const normalized = try bankNormalized(gpa, bank, eps); - defer gpa.free(normalized); - var weights: [2]f64 = undefined; - try retrieve(normalized, query, out, &weights); -} - -/// All messages in [core layer][q,k,v,mlp][H] order. Queries are shared by passes two and three. -pub fn crossPassMessages(gpa: std.mem.Allocator, bank: MessageBank, queries: MessageQueries, eps: f64, out: []f64) !void { - const h = bank.block.len; - if (h == 0 or bank.partial.len != h or out.len != core_layers * message_roles * h) return error.BadShape; - const normalized = try bankNormalized(gpa, bank, eps); - defer gpa.free(normalized); - var weights: [2]f64 = undefined; - const roles = [_]MessageRole{ .q, .k, .v, .mlp }; - for (0..core_layers) |j| for (roles, 0..) |role, r| { - const query = try queries.row(j, role, h); - const at = (j * message_roles + r) * h; - try retrieve(normalized, query, out[at..][0..h], &weights); - }; -} - -/// Mini's rank-64 controller, represented with smaller ranks too for inexpensive host probes. -pub const GateWeights = struct { - down: []const f64, // [rank][2H], with the h half before the message half - forget: []const f64, // [H][rank] - gain: []const f64, // [H][rank] - rank: usize, -}; - -fn gateDot(row: []const f64, values: []const f64) f32 { - var sum: f32 = 0; - for (row, values) |w, v| sum += narrow32(w) * narrow32(v); - return sum; -} - -/// G(h,m) = (1-f)*h + g*m. The joined norm and bottleneck are bf16; F/G stay f32 (A7). -pub fn messageGate(gpa: std.mem.Allocator, h: []const f64, m: []const f64, w: GateWeights, eps: f64, out: []f64) !void { - const width = h.len; - if (width == 0 or m.len != width or out.len != width or w.rank == 0) return error.BadShape; - if (w.down.len != w.rank * 2 * width or w.forget.len != width * w.rank or w.gain.len != width * w.rank) return error.BadShape; - const joined = try gpa.alloc(f64, 2 * width); - defer gpa.free(joined); - const zeta = try gpa.alloc(f64, w.rank); - defer gpa.free(zeta); - try rms(h, eps, joined[0..width]); - try rms(m, eps, joined[width..]); - for (joined) |*v| v.* = bf16(v.*); - for (0..w.rank) |r| zeta[r] = bf16(widen32(gateDot(w.down[r * 2 * width ..][0 .. 2 * width], joined))); - for (0..width) |i| { - const forget = std.math.tanh(gateDot(w.forget[i * w.rank ..][0..w.rank], zeta)); - const gain = std.math.tanh(gateDot(w.gain[i * w.rank ..][0..w.rank], zeta)); - const keep: f32 = 1 - forget; - const left = keep * narrow32(h[i]); - const right = gain * narrow32(m[i]); - out[i] = widen32(left + right); - } -} - -pub const AttentionKind = enum { sliding, global }; - -/// One row of the fixed 48-visit schedule. cache_slot is visit numbering; reference_slot is HF's. -pub const Visit = struct { - index: u8, - layer: u8, - pass: u8, // zero outside the core, one-based inside it - cache_slot: u8, - reference_slot: u8, - kind: AttentionKind, - boundary: bool, - has_messages: bool, - ar_queries: u8, - attention_sources: u8, - mlp_sources: u8, -}; - -pub fn visit(index: usize) VisitError!Visit { - if (index >= visit_count) return error.BadVisit; - const layer: u8 = if (index < core_start) - @intCast(index) - else if (index < 42) - @intCast(core_start + (index - core_start) % core_layers) - else - @intCast(index - 24); - const pass: u8 = if (index >= 18 and index < 42) @intCast(1 + (index - core_start) / core_layers) else if (index >= core_start and index < 18) 1 else 0; - const reference: u8 = if (pass >= 2) @intCast(24 + (@as(usize, pass) - 2) * core_layers + layer - core_start) else layer; - const global = (@as(usize, layer) + 1) % 6 == 0; - const boundary = layer % 6 == 0; - const blocks: u8 = (layer + 5) / 6; - return .{ - .index = @intCast(index), - .layer = layer, - .pass = pass, - .cache_slot = @intCast(index), - .reference_slot = reference, - .kind = if (global) .global else .sliding, - .boundary = boundary, - .has_messages = pass >= 2, - .ar_queries = if (layer == 0) 0 else if (global) 3 else 1, - .attention_sources = if (layer == 0) 0 else blocks + 1, - .mlp_sources = blocks + 1 + @intFromBool(boundary), - }; -} - -pub const Sources = struct { - blocks: []const f64, // [completed block][H] - partial: []const f64, // p before attention, or unrounded t before the MLP -}; - -/// Residual/block only; caller attention/conv/MoE. Visit: begin->attentionSources->afterAttention->mlpSources->finish. -pub const Driver = struct { - gpa: std.mem.Allocator, - hidden: usize, - storage: []f64, // blocks[4H], prelude snapshot[2H], bank[2H], p[H], t[H] - block_count: usize, - next: usize, - phase: enum { ready, attention, mlp }, - active: Visit, - have_snapshot: bool, - - pub fn init(gpa: std.mem.Allocator, embedding: []const f64) !Driver { - if (embedding.len == 0) return error.BadShape; - const h = embedding.len; - const storage = try gpa.alloc(f64, 10 * h); - @memset(storage, 0); - for (embedding, storage[8 * h .. 9 * h]) |v, *p| p.* = bf16(v); - return .{ .gpa = gpa, .hidden = h, .storage = storage, .block_count = 0, .next = 0, .phase = .ready, .active = undefined, .have_snapshot = false }; - } - - pub fn deinit(d: *Driver) void { - d.gpa.free(d.storage); - d.* = undefined; - } - - fn blocks(d: *Driver) []f64 { - return d.storage[0 .. d.block_count * d.hidden]; - } - - fn partial(d: *Driver) []f64 { - return d.storage[8 * d.hidden .. 9 * d.hidden]; - } - - fn work(d: *Driver) []f64 { - return d.storage[9 * d.hidden .. 10 * d.hidden]; - } - - /// Applies the pass reset before visits 18 and 30, after saving that previous pass's two bank states. - pub fn begin(d: *Driver, index: usize) DriverError!Visit { - if (index >= visit_count) return error.BadVisit; - if (d.phase != .ready or d.next != index) return error.BadSequence; - if (index == core_start) { - if (d.block_count != 1) return error.BadDriverState; - @memcpy(d.storage[4 * d.hidden .. 5 * d.hidden], d.partial()); - @memcpy(d.storage[5 * d.hidden .. 6 * d.hidden], d.blocks()); - d.have_snapshot = true; - } - if (index == 18 or index == 30) { - if (!d.have_snapshot or d.block_count != 3) return error.BadDriverState; - @memcpy(d.storage[6 * d.hidden .. 7 * d.hidden], d.storage[2 * d.hidden .. 3 * d.hidden]); - @memcpy(d.storage[7 * d.hidden .. 8 * d.hidden], d.partial()); - @memcpy(d.partial(), d.storage[4 * d.hidden .. 5 * d.hidden]); - @memcpy(d.storage[0..d.hidden], d.storage[5 * d.hidden .. 6 * d.hidden]); - d.block_count = 1; - } - d.active = visit(index) catch return error.BadVisit; - d.phase = .attention; - return d.active; - } - - pub fn attentionSources(d: *Driver) DriverError!Sources { - if (d.phase != .attention) return error.BadSequence; - return .{ .blocks = d.blocks(), .partial = d.partial() }; - } - - /// Saves p as a completed boundary block, then forms f32 t without rounding it to bf16. - pub fn afterAttention(d: *Driver, attention: []const f64) DriverError!void { - if (d.phase != .attention) return error.BadSequence; - if (attention.len != d.hidden) return error.BadShape; - if (d.active.boundary) { - if (d.block_count == 4) return error.BadDriverState; - @memcpy(d.storage[d.block_count * d.hidden ..][0..d.hidden], d.partial()); - d.block_count += 1; - for (d.work(), attention) |*t, a| t.* = widen32(narrow32(a)); - } else { - for (d.work(), d.partial(), attention) |*t, p, a| t.* = widen32(narrow32(p) + narrow32(a)); - } - d.phase = .mlp; - } - - /// AR's second call sees the extended block list and t, not bf16(t). - pub fn mlpSources(d: *Driver) DriverError!Sources { - if (d.phase != .mlp) return error.BadSequence; - return .{ .blocks = d.blocks(), .partial = d.work() }; - } - - /// p_out = bf16(t + f32(post-MLP-convolution output)); the residual itself is never gated. - pub fn finish(d: *Driver, mlp: []const f64) DriverError!void { - if (d.phase != .mlp) return error.BadSequence; - if (mlp.len != d.hidden) return error.BadShape; - for (d.partial(), d.work(), mlp) |*p, t, o| p.* = bf16(widen32(narrow32(t) + narrow32(o))); - d.phase = .ready; - d.next += 1; - } - - /// Raw B_12 and P_18 of the immediately previous pass; valid until the next pass reset. - pub fn messageBank(d: *Driver) DriverError!MessageBank { - if (d.phase == .ready or !d.active.has_messages) return error.BadDriverState; - return .{ .block = d.storage[6 * d.hidden .. 7 * d.hidden], .partial = d.storage[7 * d.hidden .. 8 * d.hidden] }; - } - - /// The five final AR sources after visit 47: four completed blocks and P_24. - pub fn finalSources(d: *Driver) DriverError!Sources { - if (d.phase != .ready or d.next != visit_count or d.block_count != 4) return error.BadDriverState; - return .{ .blocks = d.blocks(), .partial = d.partial() }; - } -}; - -pub fn e2m1(code: u8) f64 { - const table = [_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; - const magnitude = table[code & 7]; - return std.math.copysign(magnitude, if (code & 8 != 0) @as(f64, -1) else @as(f64, 1)); -} - -/// OCP E4M3FN, including its subnormals and sole NaN encodings. -pub fn e4m3(code: u8) f64 { - const negative = code & 0x80 != 0; - const exponent: u8 = (code >> 3) & 0xf; - const mantissa: u8 = code & 7; - if (exponent == 15 and mantissa == 7) return std.math.nan(f64); - const magnitude = if (exponent == 0) - std.math.ldexp(@as(f64, @floatFromInt(mantissa)), -9) - else - std.math.ldexp(1 + @as(f64, @floatFromInt(mantissa)) / 8, @as(i32, exponent) - 7); - return if (negative) -magnitude else magnitude; -} - -/// A2(a): both source f32 scalars are cast to bf16 before one binary32 division. -pub fn nvfp4OuterFactor(amax: f64, denominator: f64) f64 { - const a = narrow32(bf16(amax)); - const d = narrow32(bf16(denominator)); - return widen32(a / d); -} - -fn nvWeight(code: u8, scale: u8, factor: f32) f64 { - const inner = narrow32(e2m1(code) * e4m3(scale)); // the E2M1*E4M3 product is exact - return bf16(widen32(inner * factor)); -} - -pub fn nvfp4ReferenceWeight(code: u8, scale: u8, amax: f64, denominator: f64) f64 { - return nvWeight(code, scale, narrow32(nvfp4OuterFactor(amax, denominator))); -} - -/// Decode one packed NVFP4 row: low nibble is the even input, one E4M3 scale per 16 inputs. -pub fn nvfp4ReferenceRow(codes: []const u8, scales: []const u8, amax: f64, denominator: f64, out: []f64) ShapeError!void { - if (out.len == 0 or out.len % 16 != 0 or codes.len != out.len / 2 or scales.len != out.len / 16) return error.BadShape; - const factor = narrow32(nvfp4OuterFactor(amax, denominator)); - for (out, 0..) |*v, c| { - const packed_byte = codes[c / 2]; - const code = if (c % 2 == 0) packed_byte & 0xf else packed_byte >> 4; - v.* = nvWeight(code, scales[c / 16], factor); - } -} - -pub fn mxfp8Scale(scale: u8) f64 { - return std.math.ldexp(@as(f64, 1), @as(i32, scale) - 127); -} - -pub fn mxfp8ReferenceWeight(code: u8, scale: u8) f64 { - return bf16(e4m3(code) * mxfp8Scale(scale)); -} - -/// Decode one MXFP8 row using the stored per-row exponent for each group of 32 input columns (A4). -pub fn mxfp8ReferenceRow(codes: []const u8, scales: []const u8, out: []f64) ShapeError!void { - if (out.len == 0 or out.len % 32 != 0 or codes.len != out.len or scales.len != out.len / 32) return error.BadShape; - for (out, codes, 0..) |*v, code, c| v.* = mxfp8ReferenceWeight(code, scales[c / 32]); -} - -/// A bf16 reference GEMM output, with ascending f32 accumulation and no activation quantization. -pub fn expertProjection(weights: []const f64, x: []const f64, rows: usize, out: []f64) ShapeError!void { - if (rows == 0 or x.len == 0 or out.len != rows or weights.len != rows * x.len) return error.BadShape; - for (0..rows) |r| { - var sum: f32 = 0; - for (weights[r * x.len ..][0..x.len], x) |w, v| sum += narrow32(w) * narrow32(v); - out[r] = bf16(widen32(sum)); - } -} - -fn softcap32(x: f32, cap: f32) f32 { - return cap * std.math.tanh(x / cap); -} - -/// bf16(softcap4(g) * sigmoid(g) * softcap25(u)), evaluated left to right in f32. -pub fn expertActivation(gate: f64, up: f64) f64 { - const g = narrow32(gate); - const sigmoid: f32 = 1 / (1 + @exp(-g)); - const act = softcap32(g, 4) * sigmoid * softcap32(narrow32(up), 25); - return bf16(widen32(act)); -} - -/// Combine f32 from zero by ascending id, not route order (A12); expert_outputs [route][H], ids/route_weights [route]. -pub fn combineExperts(expert_count: usize, ids: []const u32, route_weights: []const f64, expert_outputs: []const f64, hidden: usize, out: []f64) ShapeError!void { - if (expert_count == 0 or hidden == 0 or ids.len != route_weights.len or expert_outputs.len != ids.len * hidden or out.len != hidden) return error.BadShape; - @memset(out, 0); - for (0..expert_count) |e| { - var found = false; - for (ids, 0..) |id, r| if (id == e) { - if (found) return error.BadShape; - found = true; - const weight = narrow32(route_weights[r]); - for (out, expert_outputs[r * hidden ..][0..hidden]) |*sum, value| { - const term = weight * narrow32(value); - sum.* = widen32(narrow32(sum.*) + term); - } - } else if (id >= expert_count) return error.BadShape; - } - for (out) |*v| v.* = bf16(v.*); -} diff --git a/zig/src/families/inkling2/loop_model_test.zig b/zig/src/families/inkling2/loop_model_test.zig deleted file mode 100644 index ee0bcf64dab..00000000000 --- a/zig/src/families/inkling2/loop_model_test.zig +++ /dev/null @@ -1,214 +0,0 @@ -const std = @import("std"); -const model = @import("loop_model.zig"); - -const Driver = model.Driver; -const GateWeights = model.GateWeights; -const MessageBank = model.MessageBank; -const MessageQueries = model.MessageQueries; -const attentionResidual = model.attentionResidual; -const bf16 = model.bf16; -const combineExperts = model.combineExperts; -const crossPassMessage = model.crossPassMessage; -const crossPassMessages = model.crossPassMessages; -const e2m1 = model.e2m1; -const e4m3 = model.e4m3; -const expertActivation = model.expertActivation; -const expertProjection = model.expertProjection; -const hidden_size = model.hidden_size; -const messageGate = model.messageGate; -const mxfp8ReferenceRow = model.mxfp8ReferenceRow; -const mxfp8ReferenceWeight = model.mxfp8ReferenceWeight; -const mxfp8Scale = model.mxfp8Scale; -const nvfp4OuterFactor = model.nvfp4OuterFactor; -const nvfp4ReferenceRow = model.nvfp4ReferenceRow; -const nvfp4ReferenceWeight = model.nvfp4ReferenceWeight; -const residualScale = model.residualScale; -const rms = model.rms; -const visit = model.visit; -const visit_count = model.visit_count; -const weightedRms = model.weightedRms; - -fn widen32(v: f32) f64 { - return @floatCast(v); -} - -fn expectClose(actual: f64, expected: f64, tolerance: f64) !void { - try std.testing.expectApproxEqAbs(expected, actual, tolerance); -} - -test "norm scale and weighted RMS's sole final bf16 rounding" { - const x = [_]f64{ 3, 4, 0, 0 }; - var out: [4]f64 = undefined; - var scratch: [4]f64 = undefined; - try rms(&x, 0, &out); - try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.2))), out[0]); - try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.6))), out[1]); - try weightedRms(&x, &.{ 2, 0.5, 1, 1 }, 0, &out, &scratch); - // Hand: rho=[1.2,1.6,0,0], then [2.4,0.8,0,0]. BF16(0.8) is 0.80078125. - try std.testing.expectEqualSlices(f64, &.{ 2.40625, 0.80078125, 0, 0 }, &out); -} - -test "attention residual normalizes values and applies binary32 inverse-root-H after its dot" { - const state = [_]f64{ 3, 4, 0, 0 }; - const partial = [_]f64{ 0, 10, 0, 0 }; - const query = [_]f64{ 1, 0, 0, 0 }; - var out: [4]f64 = undefined; - try attentionResidual(std.testing.allocator, &state, &partial, &query, 1, 0, &out); - // rho(S)=[1.2,1.6,0,0], rho(p)=[0,2,0,0], logits .6 and zero; w0=1/(1+exp(-.6)), output=w0*rho(S)+(1-w0)*rho(p). - const w0 = 1 / (1 + @exp(@as(f64, -0.6))); - try expectClose(out[0], 1.2 * w0, 2e-7); - try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); - try std.testing.expectEqual(@as(u32, 0x3caaaaab), @as(u32, @bitCast(try residualScale(hidden_size)))); -} - -test "message bank normalizes exactly its two states and checkpoint query rows are role-interleaved" { - const a = [_]f64{ 3, 4, 0, 0 }; - const p = [_]f64{ 0, 10, 0, 0 }; - var out: [4]f64 = undefined; - try crossPassMessage(std.testing.allocator, .{ .block = &a, .partial = &p }, &.{ 1, 0, 0, 0 }, 0, &out); - const w0 = 1 / (1 + @exp(@as(f64, -0.6))); - try expectClose(out[0], 1.2 * w0, 2e-7); - try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); - - var q_rows: [24]f64 = undefined; - var kv_rows: [24]f64 = undefined; - for (&q_rows, 0..) |*v, i| v.* = @floatFromInt(i); - for (&kv_rows, 0..) |*v, i| v.* = @floatFromInt(100 + i); - const queries: MessageQueries = .{ .q_mlp = &q_rows, .kv = &kv_rows }; - try std.testing.expectEqual(@as(f64, 4), (try queries.row(2, .q, 1))[0]); - try std.testing.expectEqual(@as(f64, 5), (try queries.row(2, .mlp, 1))[0]); - try std.testing.expectEqual(@as(f64, 104), (try queries.row(2, .k, 1))[0]); - try std.testing.expectEqual(@as(f64, 105), (try queries.row(2, .v, 1))[0]); - - var messages: [visit_count]f64 = undefined; - const one_bank: MessageBank = .{ .block = &.{3}, .partial = &.{4} }; - try crossPassMessages(std.testing.allocator, one_bank, queries, 0, &messages); - for (messages) |message| try std.testing.expectEqual(@as(f64, 1), message); -} - -test "rank gate rounds both joined norms and its down projection before f32 forget and gain" { - const h = [_]f64{ 3, 4, 0, 0 }; - const m = [_]f64{ 0, 10, 0, 0 }; - const weights: GateWeights = .{ - .down = &.{ 0.5, 1.5, 0, 0, 0.5, 1.0078125, 0, 0 }, - .forget = &.{ 1, 0, 0, 0 }, - .gain = &.{ 0, 1, 0, 0 }, - .rank = 1, - }; - var out: [4]f64 = undefined; - try messageGate(std.testing.allocator, &h, &m, weights, 0, &out); - // bf16 rho(h)=[1.203125,1.6015625,0,0], rho(m)=[0,2,0,0]; D*n=5.01953125 rounds to z=5.03125 (else 5.0). - const z: f32 = 5.03125; - const a: f32 = std.math.tanh(z); - const expected0: f32 = (1 - a) * 3; - const expected1: f32 = 4 + a * 10; - try std.testing.expectEqual(@as(f64, widen32(expected0)), out[0]); - try std.testing.expectEqual(@as(f64, widen32(expected1)), out[1]); - try std.testing.expectEqualSlices(f64, &.{ 0, 0 }, out[2..4]); -} - -test "48 visits reset from the prelude and bank B12 plus final partial of only the previous pass" { - var driver = try Driver.init(std.testing.allocator, &.{7}); - defer driver.deinit(); - const zero = [_]f64{0}; - for (0..visit_count) |v| { - _ = try driver.begin(v); - if (v == 6 or v == 18 or v == 30) { - const src = try driver.attentionSources(); - try std.testing.expectEqual(@as(usize, 1), src.blocks.len); - try std.testing.expectEqual(@as(f64, 7), src.blocks[0]); - try std.testing.expectEqual(@as(f64, 21), src.partial[0]); // sum of attention deltas 1...6 - } - if (v == 18) { - const bank = try driver.messageBank(); - try std.testing.expectEqual(@as(f64, 57), bank.block[0]); // sum 7...12 - try std.testing.expectEqual(@as(f64, 93), bank.partial[0]); // sum 13...18 - } else if (v == 30) { - const bank = try driver.messageBank(); - try std.testing.expectEqual(@as(f64, 129), bank.block[0]); // sum 19...24 - try std.testing.expectEqual(@as(f64, 165), bank.partial[0]); // sum 25...30 - } - const delta = [_]f64{@floatFromInt(v + 1)}; - try driver.afterAttention(&delta); - try driver.finish(&zero); - } - const final = try driver.finalSources(); - // Pass 3 supplies the last two core blocks. BF16 rounds the final exact sum 273 to even 272. - try std.testing.expectEqualSlices(f64, &.{ 7, 21, 201, 237 }, final.blocks); - try std.testing.expectEqual(@as(f64, 272), final.partial[0]); -} - -test "visit table preserves layer kinds, AR counts, private visit slots and reference slots" { - const expected = [_]struct { index: usize, layer: u8, pass: u8, reference: u8, messages: bool, ar: u8, attn: u8, mlp: u8 }{ - .{ .index = 0, .layer = 0, .pass = 0, .reference = 0, .messages = false, .ar = 0, .attn = 0, .mlp = 2 }, - .{ .index = 5, .layer = 5, .pass = 0, .reference = 5, .messages = false, .ar = 3, .attn = 2, .mlp = 2 }, - .{ .index = 6, .layer = 6, .pass = 1, .reference = 6, .messages = false, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 17, .layer = 17, .pass = 1, .reference = 17, .messages = false, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 18, .layer = 6, .pass = 2, .reference = 24, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 29, .layer = 17, .pass = 2, .reference = 35, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 30, .layer = 6, .pass = 3, .reference = 36, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 41, .layer = 17, .pass = 3, .reference = 47, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 42, .layer = 18, .pass = 0, .reference = 18, .messages = false, .ar = 1, .attn = 4, .mlp = 5 }, - .{ .index = 47, .layer = 23, .pass = 0, .reference = 23, .messages = false, .ar = 3, .attn = 5, .mlp = 5 }, - }; - for (expected) |e| { - const v = try visit(e.index); - try std.testing.expectEqual(e.layer, v.layer); - try std.testing.expectEqual(e.pass, v.pass); - try std.testing.expectEqual(e.reference, v.reference_slot); - try std.testing.expectEqual(@as(u8, @intCast(e.index)), v.cache_slot); - try std.testing.expectEqual(e.messages, v.has_messages); - try std.testing.expectEqual(e.ar, v.ar_queries); - try std.testing.expectEqual(e.attn, v.attention_sources); - try std.testing.expectEqual(e.mlp, v.mlp_sources); - } - try std.testing.expectError(error.BadVisit, visit(48)); -} - -test "NVFP4 uses bf16 amax and denominator and low nibble before high nibble" { - // 2689 rounds to bf16 2688, so the reference factor is exactly one rather than 2689/2688. - try std.testing.expectEqual(@as(f64, 1), nvfp4OuterFactor(2689, 2688)); - try std.testing.expectEqual(@as(f64, 1.5), nvfp4ReferenceWeight(3, 0x38, 2689, 2688)); - var row: [16]f64 = undefined; - var codes: [8]u8 = @splat(0); - codes[0] = 0xb3; - const scales = [_]u8{0x38}; - try nvfp4ReferenceRow(&codes, &scales, 2689, 2688, &row); - try std.testing.expectEqual(@as(f64, 1.5), row[0]); - try std.testing.expectEqual(@as(f64, -1.5), row[1]); - try std.testing.expectEqual(@as(f64, 0x1p-9), e4m3(1)); - try std.testing.expectEqual(@as(f64, -0.0), e2m1(8)); -} - -test "MXFP8 exponent is UE8M0 and each stored scale covers one row's 32 inputs" { - try std.testing.expectEqual(@as(f64, 8), mxfp8Scale(130)); - try std.testing.expectEqual(@as(f64, 12), mxfp8ReferenceWeight(0x3c, 130)); // 1.5 * 2^3 - var codes: [64]u8 = @splat(0); - codes[0] = 0x38; // one - codes[31] = 0x3c; // 1.5, still group zero - codes[32] = 0x3c; // group one - var out: [64]f64 = undefined; - try mxfp8ReferenceRow(&codes, &.{ 130, 129 }, &out); - try std.testing.expectEqual(@as(f64, 8), out[0]); - try std.testing.expectEqual(@as(f64, 12), out[31]); - try std.testing.expectEqual(@as(f64, 6), out[32]); -} - -test "expert projection and softcapped SwiGLU have no activation quantization" { - var projected: [2]f64 = undefined; - try expertProjection(&.{ 1, 2, -1, 0.5 }, &.{ 3, 4 }, 2, &projected); - try std.testing.expectEqualSlices(f64, &.{ 11, -1 }, &projected); - const g: f32 = 1; - const expected: f32 = 4 * std.math.tanh(g / 4) * (1 / (1 + @exp(-g))) * (25 * std.math.tanh(g / 25)); - try std.testing.expectEqual(@as(f64, bf16(widen32(expected))), expertActivation(1, 1)); -} - -test "expert sum is ascending id even when f32 route-order association gives another bf16 result" { - const ids = [_]u32{ 2, 1, 0 }; - const weights = [_]f64{ 1, 1, 1 }; - // Route order gives -1 + 2^-24 + 1 = 2^-24 in f32; ascending id gives (1 + 2^-24) - 1 = 0 by a tie to even. - const outputs = [_]f64{ -1, 0x1p-24, 1 }; - var out: [1]f64 = undefined; - try combineExperts(3, &ids, &weights, &outputs, 1, &out); - try std.testing.expectEqual(@as(f64, 0), out[0]); -} diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig deleted file mode 100644 index cd5cf841ee7..00000000000 --- a/zig/src/families/inkling2/loop_weights.zig +++ /dev/null @@ -1,227 +0,0 @@ -//! Inkling 2 Mini's text checkpoint on one CUDA rank. Every scheduled visit shares these physical layer weights. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -const modelopt = @import("modelopt.zig"); - -pub const Controller = struct { - down: u64, - forget: u64, - gain: u64, -}; - -pub const Attention = struct { - wq: u64, - wk: u64, - wv: u64, - wr: u64, - wo: u64, - gate: u64, - sink: u64, - q_scale: u64, - rel_scale: u64, - rel_proj: u64, - k_conv: u64, - v_conv: u64, - k_dynamic: u64 = 0, - v_dynamic: u64 = 0, - /// Sliding layers use entry zero for q, k and v. Global layers use the three separate norms. - norms: [3]u64, -}; - -/// Controller order is q, k, v and MLP, matching loop_math_cuda.messages' message layout. -pub const Layer = struct { - attn: Attention, - attn_conv: u64, - mlp_norm: u64, - mlp_conv: u64, - router: u64, - router_bias: u64, - experts: modelopt.Layer, - controllers: [4]Controller, -}; - -pub const Weights = struct { - gpa: std.mem.Allocator, - c: config.Config, - p: plan_.Plan, - embed: u64 = 0, - embed_norm: u64 = 0, - norm: u64 = 0, - unembed: u64 = 0, - output_query: u64 = 0, - attn_queries: []u64 = &.{}, - mlp_queries: []u64 = &.{}, - cross_qm: u64 = 0, - cross_kv: u64 = 0, - layers: []Layer = &.{}, - buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, - bytes: usize = 0, - - pub fn deinit(w: *Weights) void { - for (w.buffers.items) |*b| b.free(); - w.buffers.deinit(w.gpa); - w.gpa.free(w.layers); - w.gpa.free(w.attn_queries); - w.gpa.free(w.mlp_queries); - w.* = undefined; - } -}; - -/// All text tensors occupy one aligned device arena; expert uploads use this same bump allocator. -const Loader = struct { - w: *Weights, - arena: cuda.DeviceBuffer, - used: usize = 0, - - pub fn alloc(l: *Loader, len: usize) !u64 { - const at = std.mem.alignForward(usize, l.used, 256); - const end = try std.math.add(usize, at, len); - if (end > l.arena.len) return error.LoopWeightsOverflow; - l.used = end; - l.w.bytes += len; - return l.arena.ptr + at; - } - - fn put(l: *Loader, bytes: []const u8) !u64 { - const p = try l.alloc(bytes.len); - try l.arena.upload(p - l.arena.ptr, bytes); - return p; - } - - fn tensor(l: *Loader, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: core.safetensors.DType, dims: []const usize) !u64 { - var buf: [256]u8 = undefined; - const name = try std.fmt.bufPrint(&buf, fmt, args); - return l.put((try ck.expect(name, dtype, dims)).bytes); - } -}; - -fn checkpointBytes(ck: *const core.Checkpoint) !usize { - var total: usize = 0; - for (ck.files.items) |file| for (file.names.keys(), file.names.values()) |name, entry| { - if (!std.mem.startsWith(u8, name, "model.llm.")) continue; - const padded = std.mem.alignForward(usize, entry.end - entry.begin, 256); - total = try std.math.add(usize, total, padded); - }; - return total; -} - -fn controllers(l: *Loader, ck: *core.Checkpoint, c: *const config.Text, i: u32, rank: u32, out: *[4]Controller) !void { - const h: usize = c.hidden; - const names = [4][]const u8{ "attn", "k", "v", "mlp" }; - for (names, out) |role, *g| { - var prefix: [160]u8 = undefined; - const p = try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.controllers.{s}", .{ i, role }); - var down: [224]u8 = undefined; - var forget: [224]u8 = undefined; - var gain: [224]u8 = undefined; - g.* = .{ - .down = try l.put((try ck.expect(try std.fmt.bufPrint(&down, "{s}.down_weight", .{p}), .bf16, &.{ rank, 2 * h })).bytes), - .forget = try l.put((try ck.expect(try std.fmt.bufPrint(&forget, "{s}.forget_weight", .{p}), .bf16, &.{ h, rank })).bytes), - .gain = try l.put((try ck.expect(try std.fmt.bufPrint(&gain, "{s}.gain_weight", .{p}), .bf16, &.{ h, rank })).bytes), - }; - } -} - -/// Load every text tensor, including all four controller triplets and both cross-pass query matrices. -pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, c: *const config.Config, p: plan_.Plan) !Weights { - if (c.text.loop == null) return error.Inkling2LoopRequired; - var formats: [config.max_layers]modelopt.Format = undefined; - for (p.layers[0..c.text.layers], 0..) |layer, k| { - formats[k] = switch (layer.precision) { - .nvfp4 => .nvfp4, - .mxfp8 => .mxfp8, - }; - } - const total = try checkpointBytes(ck); - var arena = try cuda.DeviceBuffer.alloc(d, @max(total, 256)); - var w: Weights = .{ .gpa = gpa, .c = c.*, .p = p }; - errdefer w.deinit(); - w.buffers.append(gpa, arena) catch |err| { - arena.free(); - return err; - }; - w.layers = try gpa.alloc(Layer, c.text.layers); - w.attn_queries = try gpa.alloc(u64, c.text.layers); - w.mlp_queries = try gpa.alloc(u64, c.text.layers); - var l: Loader = .{ .w = &w, .arena = arena }; - const h: usize = c.text.hidden; - w.embed = try l.tensor(ck, "model.llm.embed.weight", .{}, .bf16, &.{ c.text.vocab, h }); - w.embed_norm = try l.tensor(ck, "model.llm.embed_norm.weight", .{}, .bf16, &.{h}); - w.norm = try l.tensor(ck, "model.llm.norm.weight", .{}, .bf16, &.{h}); - w.unembed = try l.tensor(ck, "model.llm.unembed.weight", .{}, .bf16, &.{ c.text.vocab, h }); - w.output_query = try l.tensor(ck, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); - w.cross_qm = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.end - c.text.loop.?.start), h }); - w.cross_kv = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.end - c.text.loop.?.start), h }); - - for (w.layers, 0..) |*layer, k| { - const i: u32 = @intCast(k); - const L = .{i}; - const hd = c.text.heads(i); - const q: usize = @as(usize, hd.q) * hd.dim; - const kv: usize = @as(usize, hd.kv) * hd.dim; - w.mlp_queries[k] = try l.tensor(ck, "model.llm.attn_res.mlp_queries.{d}", L, .f32, &.{h}); - if (i == 0) { - w.attn_queries[k] = 0; - } else if (config.isGlobal(i)) { - w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{ 3, h }); - } else { - w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{h}); - } - const A = struct { - fn put(loader: *Loader, checkpoint: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dims: []const usize) !u64 { - return loader.tensor(checkpoint, fmt, args, .bf16, dims); - } - }; - layer.attn = .{ - .wq = try A.put(&l, ck, "model.llm.layers.{d}.attn.wq_du.weight", L, &.{ q, h }), - .wk = try A.put(&l, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L, &.{ kv, h }), - .wv = try A.put(&l, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L, &.{ kv, h }), - .wr = try A.put(&l, ck, "model.llm.layers.{d}.attn.wr_du.weight", L, &.{ @as(usize, hd.q) * c.text.d_rel, h }), - .wo = try A.put(&l, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L, &.{ h, q }), - .gate = try A.put(&l, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L, &.{ q, h }), - .sink = try A.put(&l, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L, &.{ hd.q, h }), - .q_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L, &.{ hd.q, hd.dim }), - .rel_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L, &.{ hd.q, c.text.d_rel }), - .rel_proj = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L, &.{ c.text.d_rel, c.text.extent(i) }), - .k_conv = undefined, - .v_conv = undefined, - .norms = undefined, - }; - const sliding_norm: ?u64 = if (config.isGlobal(i)) null else try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}); - inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { - const conv = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) - else - try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight", L, &.{ kv, 1, config.conv_taps }); - if (j == 0) layer.attn.k_conv = conv else layer.attn.v_conv = conv; - if (config.isGlobal(i)) { - const dyn = try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight_proj", L, &.{ @as(usize, hd.kv) * config.conv_taps, h }); - if (j == 0) layer.attn.k_dynamic = dyn else layer.attn.v_dynamic = dyn; - } - const norm = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) - else - sliding_norm.?; - layer.attn.norms[j + 1] = norm; - } - layer.attn.norms[0] = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}.q_input_norm.weight", L, &.{h}) - else - layer.attn.norms[1]; - layer.attn_conv = try A.put(&l, ck, "model.llm.layers.{d}.attn_sconv.weight", L, &.{ h, 1, config.conv_taps }); - layer.mlp_norm = try A.put(&l, ck, "model.llm.layers.{d}.mlp_norm.weight", L, &.{h}); - layer.mlp_conv = try A.put(&l, ck, "model.llm.layers.{d}.mlp_sconv.weight", L, &.{ h, 1, config.conv_taps }); - layer.router = try A.put(&l, ck, "model.llm.layers.{d}.mlp.gate.weight", L, &.{ c.text.experts, h }); - layer.router_bias = try l.tensor(ck, "model.llm.layers.{d}.mlp.gate.bias", L, .f32, &.{c.text.experts}); - var prefix: [96]u8 = undefined; - layer.experts = try modelopt.load(&l, ck, try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.mlp.experts.", L), formats[k], c.text.experts, h, c.text.expert_inter); - @memset(&layer.controllers, .{ .down = 0, .forget = 0, .gain = 0 }); - const lp = c.text.loop.?; - if (i >= lp.start and i < lp.end) try controllers(&l, ck, &c.text, i, lp.rank, &layer.controllers); - } - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - return w; -} diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig index d78d6df3abd..5b9328faed9 100644 --- a/zig/src/families/inkling2/metal/serving_test.zig +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -73,9 +73,9 @@ fn serial(b: lanes.backend.Backend, ids: []const u32) !Reference { try b.vtable.prefill_features.?(b.ptr, &s, &taps, .{ .ptr = &sink, .take = TapSink.take }); defer b.release(&s); try std.testing.expectEqual(@as(usize, 1), sink.seen); + var next = try b.read(try b.first(&s, ids.len)); const first = try b.firstRow(&s); var out: Reference = .{ .tokens = undefined, .first = first, .tap = sink.bytes }; - var next = try b.read(try b.first(&s, ids.len)); out.tokens[0] = next; try std.testing.expectEqual(next, first.token); for (1..made) |i| { @@ -210,6 +210,7 @@ fn transactions(dir: []const u8, drafter_dir: []const u8, ids: []const u32, want defer s.deinit(gpa); try b.prefill(&s); defer b.release(&s); + try std.testing.expectEqual(want.tokens[0], try b.read(try b.first(&s, ids.len))); try expectFirstRow(want.first, try b.firstRow(&s)); try std.testing.expectEqualSlices(u8, &want.tap, &(try featureRow(target_b, &s, ids.len - 1))); diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index dd0105c93ea..909c7b8df32 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -163,14 +163,15 @@ fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) err return if (limit > resident + margin) limit - resident - margin else 0; } +/// The longest context every stream can hold at once: each owns a target state and draft rows; the scores are shared. fn longest(bytes: u64, most: u32, streams: u64, draft_fixed: u64, draft_token: u64, draft_shared_token: u64) usize { - const one: u64 = st.cacheBytes(1) + streams * (draft_fixed + draft_token) + draft_shared_token; + const one: u64 = streams * (st.cacheBytes(1) + draft_fixed + draft_token) + draft_shared_token; if (one > bytes) return 0; var lo: usize = 1; var hi: usize = most; while (lo < hi) { const mid = lo + (hi - lo + 1) / 2; - const need = st.cacheBytes(mid) + streams * (draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); + const need = streams * (st.cacheBytes(mid) + draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); if (need <= bytes) lo = mid else hi = mid - 1; } return lo; @@ -278,9 +279,11 @@ test "Inkling native load limit clamps before integer conversion" { } test "Inkling native longest context accounts target, streams and shared draft scores" { - const budget = st.cacheBytes(7) + 2 * (11 + 7 * 13) + 7 * 17; + const budget = 2 * (st.cacheBytes(7) + 11 + 7 * 13) + 7 * 17; try std.testing.expectEqual(@as(usize, 7), longest(budget, 8, 2, 11, 13, 17)); + try std.testing.expectEqual(@as(usize, 6), longest(budget - 1, 8, 2, 11, 13, 17)); try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1) - 1, 8, 1, 0, 0, 0)); + try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1), 8, 2, 0, 0, 0)); const per_token = dspark.Drafter.streamBytes(1) - dspark.Drafter.streamBytes(0); const conservative = dspark.Drafter.streamBytes(0) + 127 * per_token + 129 * per_token; try std.testing.expect(conservative >= dspark.Drafter.streamBytes(129)); diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig deleted file mode 100644 index bef2f7d69ef..00000000000 --- a/zig/tests/cuda/contract_inkling2_loop_math.zig +++ /dev/null @@ -1,479 +0,0 @@ -//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. -const std = @import("std"); -const core = @import("core"); -const ink = @import("inkling2"); -const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_ops_ref.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; -const lm = ink.loop_math_cuda; -pub const eps = ref.eps; -pub const mini_h = 2304; - -/// Exact raw-output checks, with interval references and accumulator simulations for gate 4. -pub fn Checked(comptime T: type) type { - return struct { - const Self = @This(); - inner: ref.Gated(T), - rig: *rig_.Rig = undefined, - msg: [200]u8 = undefined, - - pub fn deinit(self: *Self) void { - self.inner.deinit(); - } - - pub fn kernel(self: *Self) g.Kernel { - self.rig = &self.inner.rig; - return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; - } - - const vt = g.hooks(Self); - - pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { - return self.inner.prepare(shape, fill, seed); - } - - pub fn run(self: *Self) !void { - try self.inner.run(); - } - - pub fn count(self: *Self) usize { - return self.inner.count(); - } - - pub fn reference(self: *Self, want: []f64, mag: []f64) !void { - try self.inner.reference(want, mag); - } - - pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { - try self.inner.bounds(want, mag, allow); - } - - pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { - try self.inner.simulate(acc, order, out); - } - - pub fn check(self: *Self, _: g.Gate) !?[]const u8 { - const a = self.rig.gpu.gpa; - const got = try a.dupe(u8, try self.rig.outputBytes()); - defer a.free(got); - return self.inner.k.check(a, got, &self.msg); - } - }; -} - -pub fn queryScale(cols: usize) ref.Iv { - return if (cols == mini_h) ref.Iv.of(scale(cols)) else ref.Iv.of(@floatFromInt(cols)).rsqrt(); -} - -pub fn softmax(logits: []ref.Iv) void { - var m = logits[0]; - for (logits[1..]) |v| m = .{ .m = @max(m.m, v.m), .lo = @max(m.lo, v.lo), .hi = @max(m.hi, v.hi) }; - var den = ref.Iv.of(0); - for (logits) |*v| { - v.* = v.sub(m).exp(); - den = den.add(v.*); - } - for (logits) |*v| v.* = v.div(den); -} - -/// Irregular integer squares stay exact in FP32 for gate 4, but overflow FP16 and round in every BF16 order. -fn stressBank(i: usize) f32 { - return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; -} - -/// Messages nearly cancel two normalized banks; the unmatched first tap keeps FP16 normalization overflow visible. -fn messageStressBank(bank: usize, col: usize, cols: usize) f32 { - if (bank == 0) return stressBank(col); - if (col == 0) return 0; - return -stressBank((col + 1) % cols); -} - -/// AR cyclically assigns [x, -x, 0] over its sources so zero-query outputs expose RMS-sum differences. -pub fn arStressSource(source: usize, col: usize) f32 { - if (source == 0 and col == 0) return 0; - const value = stressBank(col - col % 3); - return switch ((col + 2 * source) % 3) { - 0 => value, - 1 => -value, - 2 => 0, - else => unreachable, - }; -} - -pub fn close(got: f32, want: f32) bool { - if (std.math.isNan(want)) return std.math.isNan(got); - if (!std.math.isFinite(want)) return got == want; - if (!std.math.isFinite(got)) return false; - const tolerance = 1e-4 * (1.0 + @abs(want)); - return @abs(got - want) <= tolerance; -} - -pub fn bf(x: u16) f32 { - return @floatCast(ref.bf(x)); -} - -pub fn bfRound(x: f32) f32 { - return bf(c.toBf16(x)); -} -pub fn cudaMax(a: f32, b: f32) f32 { - if (std.math.isNan(a)) return b; - if (std.math.isNan(b)) return a; - return @max(a, b); -} - -pub fn sameBf(got: u16, want: u16) bool { - if ((want & 0x7fff) > 0x7f80) return (got & 0x7fff) > 0x7f80; // NaN payload is not part of the math rule - return got == want; -} - -pub fn scale(cols: usize) f32 { - return if (cols == mini_h) 1.0 / 48.0 else 1.0 / @sqrt(@as(f32, @floatFromInt(cols))); -} - -fn warp(v: *[32]f32) f32 { - var offset: usize = 16; - while (offset != 0) : (offset >>= 1) { - const old = v.*; - for (0..32) |lane| v.*[lane] = old[lane] + old[lane ^ offset]; - } - return v.*[0]; -} - -/// The exact lane chains and butterfly tree of loop_math.cu. Terms are fused into each lane's accumulator. -pub fn reduce(a: []const f32, b: []const f32, threads: usize) f32 { - var partial: [32]f32 = @splat(0); - for (0..threads / 32) |w| { - var lanes: [32]f32 = undefined; - for (0..32) |lane| { - const tid = w * 32 + lane; - var sum: f32 = 0; - var i = tid; - while (i < a.len) : (i += threads) sum = @mulAdd(f32, a[i], b[i], sum); - lanes[lane] = sum; - } - partial[w] = warp(&lanes); - } - return warp(&partial); -} - -pub fn fail(msg: []u8, comptime fmt: []const u8, args: anytype) !?[]const u8 { - return try std.fmt.bufPrint(msg, fmt, args); -} - -const message_shapes = [_]c.Shape{ - .{ .rows = 1, .n = 4 * 12 * mini_h, .k = mini_h }, - .{ .rows = 16, .n = 4 * 128, .k = 128 }, - .{ .rows = 2048, .n = 4 * 128, .k = 128 }, -}; - -/// Two normalized banks and the checkpoint's even/odd q,mlp and k,v queries, compared element by element. -pub const Messages = struct { - kern: *const lm.Kernels, - aliased: bool = false, - shape: c.Shape = undefined, - banks: [2][]u16 = .{ &.{}, &.{} }, - queries: [2][]f32 = .{ &.{}, &.{} }, - dev: [5]u64 = @splat(0), - out: u64 = 0, - - pub fn spec(self: *const Messages) c.Spec { - return .{ .name = if (self.aliased) "control: inkling2 loop messages with both previous-pass inputs wired to bank zero" else "inkling2 loop tf_ink2_loop_messages (two normalized banks, post-dot 1/48, four roles)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) message_shapes[0..2] else &message_shapes }; - } - - fn depth(s: c.Shape) usize { - return 2 * ((s.k + 255) / 256 + 10); - } - - pub fn control(self: *const Messages) ?g.Gate { - return if (self.aliased) .shapes else null; - } - - pub fn free(self: *Messages, a: std.mem.Allocator) void { - for (&self.banks) |*x| a.free(x.*); - for (&self.queries) |*x| a.free(x.*); - self.banks = .{ &.{}, &.{} }; - self.queries = .{ &.{}, &.{} }; - } - - pub fn prepare(self: *Messages, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.k == 0 or shape.n % (4 * shape.k) != 0) return false; - self.free(a); - self.shape = shape; - const cols = shape.k; - const layers = shape.n / (4 * cols); - for (&self.banks, 0..) |*x, bank| { - x.* = try a.alloc(u16, shape.rows * cols); - if (fill == .stress) { - for (x.*, 0..) |*v, i| v.* = c.toBf16(messageStressBank(bank, i % cols, cols)); - } else for (x.*) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); - } - for (&self.queries) |*x| { - x.* = try ref.f32s(a, rng, 2 * layers * cols, -0.25, 0.25); - if (fill == .stress) @memset(x.*, 0); - } - if (fill == .nonfinite) { - ref.plant(u16, self.banks[0], shape.rows, cols, ref.asBf); - ref.plant(u16, self.banks[1], shape.rows, cols, ref.asBf); - } - for (self.banks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - for (self.queries, 0..) |x, i| self.dev[2 + i] = try ref.input(rig, x); - self.out = try rig.output(shape.rows * shape.n * 4); - return true; - } - - pub fn run(self: *Messages, rig: *rig_.Rig) !void { - const b1 = if (self.aliased) self.dev[0] else self.dev[1]; - const layers = self.shape.n / (4 * self.shape.k); - try lm.messages(self.kern, rig.s, self.dev[0], b1, self.dev[2], self.dev[3], self.out, self.shape.rows, layers, self.shape.k, eps); - } - - pub fn count(self: *const Messages) usize { - return self.shape.rows * self.shape.n; - } - - pub fn solve(self: *const Messages, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.k; - const layers = self.shape.n / (4 * cols); - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - const later = ref.later(s); - for (0..self.shape.rows) |row| { - var inv: [2]ref.Iv = undefined; - for (0..2) |b| { - for (terms, self.banks[b][row * cols ..][0..cols]) |*t, v| { - const x = ref.Iv.of(ref.bf(v)); - t.* = x.mul(x); - } - inv[b] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); - } - for (0..layers) |j| for (0..4) |role| { - const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; - var logits: [2]ref.Iv = undefined; - for (0..2) |b| { - for (terms, query, self.banks[b][row * cols ..][0..cols]) |*t, q, v| t.* = ref.Iv.of(q).mul(ref.Iv.of(ref.bf(v)).mul(inv[b])); - logits[b] = later.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); - } - softmax(&logits); - for (0..cols) |i| { - var value = ref.Iv.of(0); - for (0..2) |b| { - const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); - value = value.add(logits[b].mul(beta)); - } - const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; - out[at] = value; - } - }; - } - } - - pub fn check(self: *const Messages, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.k; - const layers = self.shape.n / (4 * cols); - const raw0 = try a.alloc(f32, cols); - defer a.free(raw0); - const raw1 = try a.alloc(f32, cols); - defer a.free(raw1); - const beta0 = try a.alloc(f32, cols); - defer a.free(beta0); - const beta1 = try a.alloc(f32, cols); - defer a.free(beta1); - for (0..self.shape.rows) |row| { - for (raw0, self.banks[0][row * cols ..][0..cols]) |*x, v| x.* = bf(v); - for (raw1, self.banks[1][row * cols ..][0..cols]) |*x, v| x.* = bf(v); - const inv0 = 1.0 / @sqrt(reduce(raw0, raw0, 256) / @as(f32, @floatFromInt(cols)) + eps); - const inv1 = 1.0 / @sqrt(reduce(raw1, raw1, 256) / @as(f32, @floatFromInt(cols)) + eps); - for (beta0, raw0) |*x, v| x.* = v * inv0; - for (beta1, raw1) |*x, v| x.* = v * inv1; - for (0..layers) |j| for (0..4) |role| { - const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; - const l0 = reduce(query, beta0, 256) * scale(cols); - const l1 = reduce(query, beta1, 256) * scale(cols); - const m = cudaMax(l0, l1); - const e0 = @exp(l0 - m); - const e1 = @exp(l1 - m); - const den = e0 + e1; - const w0 = e0 / den; - const w1 = e1 / den; - for (0..cols) |i| { - const want = w0 * beta0[i] + w1 * beta1[i]; - const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; - const value = ref.readF32(got, at); - if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); - } - }; - } - return null; - } -}; - -const gate_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 2 * mini_h }, - .{ .rows = 16, .n = mini_h, .k = 2 * mini_h }, - .{ .rows = 2048, .n = 128, .k = 256 }, -}; - -/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. -pub const Gate = struct { - kern: *const lm.Kernels, - wrong_gain: bool = false, - shape: c.Shape = undefined, - h: []f32 = &.{}, - m: []f32 = &.{}, - d: []u16 = &.{}, - f: []u16 = &.{}, - gain: []u16 = &.{}, - dev: [5]u64 = @splat(0), - out: u64 = 0, - - pub fn spec(self: *const Gate) c.Spec { - return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; - } - - fn depth(s: c.Shape) usize { - return (s.k + 255) / 256 + 10 + lm.rank; - } - - pub fn control(self: *const Gate) ?g.Gate { - return if (self.wrong_gain) .shapes else null; - } - - pub fn free(self: *Gate, a: std.mem.Allocator) void { - a.free(self.h); - a.free(self.m); - a.free(self.d); - a.free(self.f); - a.free(self.gain); - self.h = &.{}; - self.m = &.{}; - self.d = &.{}; - self.f = &.{}; - self.gain = &.{}; - } - - pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.k != 2 * shape.n) return false; - self.free(a); - self.shape = shape; - const cols = shape.n; - self.h = try ref.f32s(a, rng, shape.rows * cols, -1, 1); - self.m = try ref.f32s(a, rng, shape.rows * cols, -1, 1); - self.d = try ref.bfs(a, rng, lm.rank * 2 * cols, -0.1, 0.1); - self.f = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); - self.gain = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); - if (fill == .stress) { - for (self.h, 0..) |*v, i| v.* = stressBank(i % cols); - for (self.m, 0..) |*v, i| v.* = stressBank(i % cols); - for (self.d) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - for (self.f) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - } - if (fill == .nonfinite) { - ref.plant(f32, self.h, shape.rows, cols, ref.asF32); - ref.plant(f32, self.m, shape.rows, cols, ref.asF32); - } - self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; - self.out = try rig.output(shape.rows * cols * 4); - return true; - } - - pub fn run(self: *Gate, rig: *rig_.Rig) !void { - try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); - } - - pub fn count(self: *const Gate) usize { - return self.shape.rows * self.shape.n; - } - - pub fn solve(self: *const Gate, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.n; - const n = try a.alloc(ref.Iv, 2 * cols); - defer a.free(n); - const terms = try a.alloc(ref.Iv, 2 * cols); - defer a.free(terms); - const scratch = try a.alloc(f64, 2 * cols); - defer a.free(scratch); - const zeta = try a.alloc(ref.Iv, lm.rank); - defer a.free(zeta); - const later = ref.later(s); - const zeta_depth = (2 * cols + 31) / 32 + 5; - for (0..self.shape.rows) |row| { - const h = self.h[row * cols ..][0..cols]; - const m = self.m[row * cols ..][0..cols]; - var inv: [2]ref.Iv = undefined; - for (0..2) |b| { - const x = if (b == 0) h else m; - for (terms[0..cols], x) |*t, v| { - const e = ref.Iv.of(v); - t.* = e.mul(e); - } - inv[b] = ref.rms(s.sum(terms[0..cols], depth(self.shape), scratch), cols, eps); - } - for (n[0..cols], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); - for (n[cols..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); - for (0..lm.rank) |r| { - for (terms, n, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); - zeta[r] = later.sum(terms, zeta_depth, scratch).bf(); - } - for (0..cols) |i| { - for (terms[0..lm.rank], zeta, self.f[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); - const forget = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); - for (terms[0..lm.rank], zeta, self.gain[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); - const gain = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); - const keep = ref.Iv.of(1).sub(forget); - const old = keep.mul(ref.Iv.of(h[i])); - const added = gain.mul(ref.Iv.of(m[i])); - out[row * cols + i] = old.add(added); - } - } - } - - pub fn check(self: *const Gate, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.n; - const n = try a.alloc(f32, 2 * cols); - defer a.free(n); - const weights = try a.alloc(f32, 2 * cols); - defer a.free(weights); - const zeta = try a.alloc(f32, lm.rank); - defer a.free(zeta); - const zf = try a.alloc(f32, lm.rank); - defer a.free(zf); - const zg = try a.alloc(f32, lm.rank); - defer a.free(zg); - for (0..self.shape.rows) |row| { - const h = self.h[row * cols ..][0..cols]; - const m = self.m[row * cols ..][0..cols]; - const ih = 1.0 / @sqrt(reduce(h, h, 256) / @as(f32, @floatFromInt(cols)) + eps); - const im = 1.0 / @sqrt(reduce(m, m, 256) / @as(f32, @floatFromInt(cols)) + eps); - for (n[0..cols], h) |*v, x| v.* = bfRound(x * ih); - for (n[cols..], m) |*v, x| v.* = bfRound(x * im); - for (0..lm.rank) |r| { - for (weights, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*v, w| v.* = bf(w); - zeta[r] = bfRound(reduce(weights, n, 256)); - } - for (0..cols) |i| { - for (zf, self.f[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); - for (zg, self.gain[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); - var sf: f32 = 0; - var sg: f32 = 0; - for (0..lm.rank) |r| { - sf = @mulAdd(f32, zf[r], zeta[r], sf); - sg = @mulAdd(f32, zg[r], zeta[r], sg); - } - const forget = std.math.tanh(sf); - const gain = std.math.tanh(sg); - const keep: f32 = 1.0 - forget; - const old: f32 = keep * h[i]; - const added: f32 = gain * m[i]; - const want: f32 = old + added; - const value = ref.readF32(got, row * cols + i); - if (!close(value, want)) return fail(msg, "row {d} col {d}: {e} where {e} is due", .{ row, i, value, want }); - } - } - return null; - } -}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig deleted file mode 100644 index 49bd3ae650e..00000000000 --- a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig +++ /dev/null @@ -1,426 +0,0 @@ -//! Mini QKV projection, raw AR and BF16 tap rounding, with the loop suites' shared registration. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const check = @import("check.zig"); -const ink = @import("inkling2"); -const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_ops_ref.zig"); -const base = @import("contract_inkling2_loop_math.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; -const lm = ink.loop_math_cuda; -const K = base.Checked; -const eps = base.eps; -const mini_h = base.mini_h; -const queryScale = base.queryScale; -const softmax = base.softmax; -const arStressSource = base.arStressSource; -const close = base.close; -const bf = base.bf; -const bfRound = base.bfRound; -const cudaMax = base.cudaMax; -const sameBf = base.sameBf; -const scale = base.scale; -const reduce = base.reduce; -const fail = base.fail; -const Messages = base.Messages; -const Gate = base.Gate; -const qkv_shapes = [_]c.Shape{ - .{ .rows = 1, .n = 3072, .k = mini_h }, - .{ .rows = 16, .n = 384, .k = 128 }, - .{ .rows = 2048, .n = 384, .k = 128 }, -}; - -/// Distinct q/k/v rows, with the Small single-input aliasing bug planted as the control. -pub const ProjectQkv = struct { - kern: *const lm.Kernels, - shared_input: bool = false, - shape: c.Shape = undefined, - u: [3][]u16 = .{ &.{}, &.{}, &.{} }, - w: [3][]u16 = .{ &.{}, &.{}, &.{} }, - dev: [6]u64 = @splat(0), - out: [3]u64 = @splat(0), - - pub fn spec(self: *const ProjectQkv) c.Spec { - return .{ .name = if (self.shared_input) "control: Mini split QKV projection using Small's one normalized input for all roles" else "inkling2 loop tf_ink2_loop_project_qkv (distinct normalized q/k/v inputs, unchanged raw layouts)", .accum = .f32, .depth = depth, .out = .bf16, .served = if (self.shared_input) qkv_shapes[0..2] else &qkv_shapes }; - } - - fn depth(s: c.Shape) usize { - return s.k; - } - - pub fn control(self: *const ProjectQkv) ?g.Gate { - return if (self.shared_input) .shapes else null; - } - - pub fn free(self: *ProjectQkv, a: std.mem.Allocator) void { - for (&self.u) |*x| a.free(x.*); - for (&self.w) |*x| a.free(x.*); - self.u = .{ &.{}, &.{}, &.{} }; - self.w = .{ &.{}, &.{}, &.{} }; - } - - pub fn prepare(self: *ProjectQkv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.n % 3 != 0 or shape.k == 0) return false; - self.free(a); - self.shape = shape; - for (&self.u) |*x| x.* = try ref.bfs(a, rng, shape.rows * shape.k, -1, 1); - for (&self.w, 0..) |*x, role| x.* = try ref.bfs(a, rng, (if (role == 0) shape.n else shape.n / 3) * shape.k, -0.1, 0.1); - if (fill == .stress) { - // Mirrored products cancel to eight small FP32 terms; lower precisions lose their large partials. - const half = shape.k / 2; - for (self.u) |bank| for (0..shape.rows) |row| { - const values = bank[row * shape.k ..][0..shape.k]; - for (0..half) |i| { - values[i] = c.toBf16(ref.int(rng, 8, 16)); - values[half + i] = values[i]; - } - if (shape.k % 2 != 0) values[shape.k - 1] = 0; - }; - for (self.w) |bank| for (0..bank.len / shape.k) |row| { - const values = bank[row * shape.k ..][0..shape.k]; - for (0..half) |i| { - const v = ref.int(rng, 8, 16); - values[i] = c.toBf16(v); - values[half + i] = c.toBf16(-v); - } - for (0..@min(8, half)) |i| values[half + i] = c.toBf16(1 - bf(values[i])); - if (shape.k % 2 != 0) values[shape.k - 1] = 0; - }; - } - if (fill == .nonfinite) for (&self.u) |*x| ref.plant(u16, x.*, shape.rows, shape.k, ref.asBf); - for (self.u, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - for (self.w, 0..) |x, i| self.dev[3 + i] = try ref.input(rig, x); - for (0..3) |role| self.out[role] = try rig.output(shape.rows * (if (role == 0) shape.n else shape.n / 3) * 2); - return true; - } - - pub fn run(self: *ProjectQkv, rig: *rig_.Rig) !void { - const k = if (self.shared_input) self.dev[0] else self.dev[1]; - const v = if (self.shared_input) self.dev[0] else self.dev[2]; - try lm.projectQkv(self.kern, rig.s, self.dev[0], k, v, self.dev[3], self.dev[4], self.dev[5], self.out[0], self.out[1], self.out[2], self.shape.rows, self.shape.k, self.shape.n, self.shape.n / 3); - } - - pub fn count(self: *const ProjectQkv) usize { - return self.shape.rows * self.shape.n * 5 / 3; - } - - pub fn solve(self: *const ProjectQkv, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.k; - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - var offset: usize = 0; - for (0..3) |role| { - const width = if (role == 0) self.shape.n else self.shape.n / 3; - for (0..self.shape.rows) |row| for (0..width) |j| { - for (terms, self.u[role][row * cols ..][0..cols], self.w[role][j * cols ..][0..cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(x) * ref.bf(w)); - out[offset + row * width + j] = s.sum(terms, depth(self.shape), scratch).bf(); - }; - offset += self.shape.rows * width; - } - } - - pub fn check(self: *const ProjectQkv, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.k; - const x = try a.alloc(f32, cols); - defer a.free(x); - const w = try a.alloc(f32, cols); - defer a.free(w); - var byte_at: usize = 0; - for (0..3) |role| { - const width = if (role == 0) self.shape.n else self.shape.n / 3; - for (0..self.shape.rows) |row| for (0..width) |j| { - for (x, self.u[role][row * cols ..][0..cols]) |*v, u| v.* = bf(u); - for (w, self.w[role][j * cols ..][0..cols]) |*v, u| v.* = bf(u); - var sum: f32 = 0; - for (0..cols) |i| sum = @mulAdd(f32, x[i], w[i], sum); - const want = c.toBf16(sum); - const at = byte_at + (row * width + j) * 2; - const value = std.mem.readInt(u16, got[at..][0..2], .little); - if (!sameBf(value, want)) return fail(msg, "role {d} row {d} output {d}: {x} where {x} is due", .{ role, row, j, value, want }); - }; - byte_at += self.shape.rows * width * 2; - } - return null; - } -}; - -const ar_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 1 }, - .{ .rows = 16, .n = 128, .k = 3 }, - .{ .rows = 2048, .n = 128, .k = 3 }, -}; - -/// Raw AR before controllers. Two completed blocks plus a partial; control omits the second completed block. -pub const Ar = struct { - kern: *const lm.Kernels, - partial_bf16: bool, - short: bool = false, - shape: c.Shape = undefined, - blocks: [2][]u16 = .{ &.{}, &.{} }, - partial32: []f32 = &.{}, - partial16: []u16 = &.{}, - query: []f32 = &.{}, - dev: [4]u64 = @splat(0), // two blocks, partial, query - out: u64 = 0, - - pub fn spec(self: *const Ar) c.Spec { - return .{ .name = if (self.short) "control: inkling2 loop raw AR omitting its second completed block" else if (self.partial_bf16) "inkling2 loop tf_ink2_loop_ar (BF16 partial, FP32 unnormalized output)" else "inkling2 loop tf_ink2_loop_ar (FP32 partial, FP32 unnormalized output)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.short) ar_shapes[1..2] else &ar_shapes }; - } - - fn depth(s: c.Shape) usize { - return (s.n + 511) / 512 + 10 + 3; - } - - pub fn control(self: *const Ar) ?g.Gate { - return if (self.short) .shapes else null; - } - - pub fn free(self: *Ar, a: std.mem.Allocator) void { - for (&self.blocks) |*x| a.free(x.*); - a.free(self.partial32); - a.free(self.partial16); - a.free(self.query); - self.blocks = .{ &.{}, &.{} }; - self.partial32 = &.{}; - self.partial16 = &.{}; - self.query = &.{}; - } - - pub fn prepare(self: *Ar, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > lm.max_queries) return false; - self.free(a); - self.shape = shape; - for (&self.blocks, 0..) |*x, source| { - x.* = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (x.*, 0..) |*v, i| v.* = c.toBf16(arStressSource(source, i % shape.n)); - } - } - if (self.partial_bf16) { - self.partial16 = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (self.partial16, 0..) |*v, i| v.* = c.toBf16(arStressSource(2, i % shape.n)); - } - self.dev[2] = try ref.input(rig, self.partial16); - } else { - self.partial32 = try ref.f32s(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (self.partial32, 0..) |*v, i| v.* = arStressSource(2, i % shape.n); - } - self.dev[2] = try ref.input(rig, self.partial32); - } - self.query = try ref.f32s(a, rng, shape.k * shape.n, -0.25, 0.25); - if (fill == .stress) @memset(self.query, 0); - if (fill == .nonfinite) for (&self.blocks) |*x| ref.plant(u16, x.*, shape.rows, shape.n, ref.asBf); - for (self.blocks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - self.dev[3] = try ref.input(rig, self.query); - self.out = try rig.output(shape.rows * shape.n * shape.k * 4); - return true; - } - - pub fn run(self: *Ar, rig: *rig_.Rig) !void { - var args: lm.ArArgs = .{ .partial = self.dev[2], .query = self.dev[3], .out = self.out, .n_blocks = if (self.short) 1 else 2, .partial_bf16 = @intFromBool(self.partial_bf16), .nq = @intCast(self.shape.k), .rows = @intCast(self.shape.rows), .c = @intCast(self.shape.n), .eps = eps }; - args.blocks[0] = self.dev[0]; - args.blocks[1] = self.dev[1]; - try lm.ar(self.kern, rig.s, args); - } - - pub fn count(self: *const Ar) usize { - return self.shape.rows * self.shape.n * self.shape.k; - } - - fn entry(self: *const Ar, source: usize, row: usize, col: usize) f32 { - const at = row * self.shape.n + col; - return if (source < 2) bf(self.blocks[source][at]) else if (self.partial_bf16) bf(self.partial16[at]) else self.partial32[at]; - } - - pub fn solve(self: *const Ar, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.n; - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - for (0..self.shape.rows) |row| { - var inv: [3]ref.Iv = undefined; - for (0..3) |j| { - for (terms, 0..) |*t, i| { - const x = ref.Iv.of(self.entry(j, row, i)); - t.* = x.mul(x); - } - inv[j] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); - } - for (0..self.shape.k) |q| { - var logits: [3]ref.Iv = undefined; - for (0..3) |j| { - for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]).mul(ref.Iv.of(self.query[q * cols + i])); - logits[j] = s.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); - } - softmax(&logits); - for (0..cols) |i| { - var value = ref.Iv.of(0); - for (0..3) |j| { - const beta = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]); - value = value.add(logits[j].mul(beta)); - } - out[(q * self.shape.rows + row) * cols + i] = value; - } - } - } - } - - pub fn check(self: *const Ar, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.n; - const sources = 3; - const raw = try a.alloc(f32, cols); - defer a.free(raw); - const beta = try a.alloc(f32, sources * cols); - defer a.free(beta); - const weights = try a.alloc(f32, sources); - defer a.free(weights); - for (0..self.shape.rows) |row| { - var invs: [3]f32 = undefined; - for (0..sources) |j| { - for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); - invs[j] = 1.0 / @sqrt(reduce(raw, raw, 512) / @as(f32, @floatFromInt(cols)) + eps); - for (beta[j * cols ..][0..cols], raw) |*v, x| v.* = x * invs[j]; - } - for (0..self.shape.k) |q| { - var logits: [3]f32 = undefined; - var m = -std.math.inf(f32); - for (0..sources) |j| { - const query = self.query[q * cols ..][0..cols]; - logits[j] = reduce(query, beta[j * cols ..][0..cols], 512) * scale(cols); - m = cudaMax(m, logits[j]); - } - var den: f32 = 0; - for (0..sources) |j| { - weights[j] = @exp(logits[j] - m); - den += weights[j]; - } - for (0..sources) |j| weights[j] /= den; - for (0..cols) |i| { - var want: f32 = 0; - for (0..sources) |j| want = @mulAdd(f32, weights[j], beta[j * cols + i], want); - const at = (q * self.shape.rows + row) * cols + i; - const value = ref.readF32(got, at); - if (!close(value, want)) return fail(msg, "query {d} row {d} col {d}: {e} where {e} is due", .{ q, row, i, value, want }); - } - } - } - return null; - } -}; - -test "AR normalizes each FP32 query term before reduction and scales after its dot" { - const source = [_]f32{ - @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), - @bitCast(@as(u32, 0x40400001)), 0, - }; - const query = [_]f32{ - @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), - @bitCast(@as(u32, 0xc0000001)), 0, - }; - const inv: f32 = @bitCast(@as(u32, 0x3f800001)); - var normalized: [4]f32 = undefined; - for (&normalized, source) |*v, x| v.* = x * inv; - const dot = reduce(&query, &normalized, 512); - const old = reduce(&query, &source, 512) * inv * scale(source.len); - const scaled = dot * scale(source.len); - try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); - try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); -} - -const round_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 1 }, - .{ .rows = 2048, .n = 32, .k = 1 }, -}; - -/// Dynamic taps' required BF16 storage rounding, followed by exact widening for the FP32 convolution. -pub const RoundBf16 = struct { - kern: *const lm.Kernels, - short: bool = false, - shape: c.Shape = undefined, - x: []f32 = &.{}, - dev: u64 = 0, - out: u64 = 0, - - pub fn spec(self: *const RoundBf16) c.Spec { - return .{ .name = if (self.short) "control: inkling2 loop dynamic taps leave the final value unrounded" else "inkling2 loop tf_ink2_loop_round_bf16 (global dynamic taps, BF16 then FP32)", .accum = .none, .depth = ref.noSums, .out = .f32, .served = if (self.short) round_shapes[0..1] else &round_shapes }; - } - - pub fn control(self: *const RoundBf16) ?g.Gate { - return if (self.short) .shapes else null; - } - - pub fn free(self: *RoundBf16, a: std.mem.Allocator) void { - a.free(self.x); - self.x = &.{}; - } - - pub fn prepare(self: *RoundBf16, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0) return false; - self.free(a); - self.shape = shape; - self.x = try ref.f32s(a, rng, shape.rows * shape.n, -32, 32); - if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); - self.dev = try ref.input(rig, self.x); - self.out = try rig.output(self.x.len * 4); - return true; - } - - pub fn run(self: *RoundBf16, rig: *rig_.Rig) !void { - try lm.roundBf16(self.kern, rig.s, self.dev, self.out, self.x.len - @intFromBool(self.short)); - } - - pub fn count(self: *const RoundBf16) usize { - return self.x.len; - } - - pub fn solve(self: *const RoundBf16, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { - for (out, self.x) |*o, x| o.* = ref.Iv.of(x).bf(); - } - - pub fn check(self: *const RoundBf16, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - for (self.x, 0..) |x, i| { - const want = bfRound(x); - const value = ref.readF32(got, i); - if (!ref.sameF32(value, want)) return fail(msg, "tap {d}: {e} where {e} is due", .{ i, value, want }); - } - return null; - } -}; - -pub const Set = struct { - k: lm.Kernels = undefined, - loaded: bool = false, - messages: [2]K(Messages) = undefined, - gates: [2]K(Gate) = undefined, - qkvs: [2]K(ProjectQkv) = undefined, - ars: [3]K(Ar) = undefined, - rounds: [2]K(RoundBf16) = undefined, - - pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { - set.k = try lm.Kernels.load(gpu.d); - set.loaded = true; - const k = &set.k; - const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; - for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; - for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; - for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; - for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; - for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; - inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); - } - - pub fn deinit(set: *Set) void { - if (!set.loaded) return; - inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| x.deinit(); - set.k.unload(); - set.loaded = false; - } -}; From 9f542e6fa3cfd0f0298f42cd6e889c7f3cee48e9 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:50:46 +0800 Subject: [PATCH 52/84] inkling2: serve inkling2_loop through jschmied's #4441 engine; drop #4387's loop engine and port its serving checks #4387's separate loop engine advertised structured output it always refused and duplicated #4441's registered path. Its draws, resume and two-stream checks now run against #4441's Mini; copy drafting is not checked, as that engine has no draft path. --- THIRD_PARTY_NOTICES.md | 4 +- ...nkling-2-mini-runs-whole-on-our-spark-g.md | 25 ++- docs/recipes/inkling-2-mini-cuda/README.md | 24 ++- zig/build/cuda_kernels.zig | 1 - .../contract/inkling2_experts_records.zig | 5 - zig/src/cuda/kernels.zig | 1 - zig/src/families/inkling2/host_test.zig | 3 - zig/src/families/inkling2/inkling2.zig | 12 +- zig/tests/cuda/contract_inkling2.zig | 3 - zig/tests/cuda/contract_limits.zig | 2 +- zig/tests/cuda/inkling2_serving_tests.zig | 155 ++---------------- zig/tests/cuda/main_usage.zig | 2 +- zig/tests/fixtures/gradient-serving.tsv | 2 +- 13 files changed, 45 insertions(+), 194 deletions(-) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 55542a8cff8..d6354857ee0 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -575,8 +575,8 @@ stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)). The headers, no tensor data or weights. `tools/zig/inkling2_fixtures.py` rebuilds all three from the Mini release, or from its extracted headers, with the same revision annotation. No revision was derived from fixture digests. -The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, -`loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and +The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, the CUDA and Metal loop kernels +and the stored-expert implementations in `modelopt.zig` and `zig/kernels/cuda/inkling2/modelopt.cu` are independent TensorFold implementations of the supplied math-only Mini specification. Its primary reference is huggingface/transformers PR #51050 at head `6173a2f6`: the Mini configuration and forward pass in `models/inkling2_loop/modular_inkling2_loop.py` and `modeling_inkling2_loop.py`, with the temporary diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index fd957e0b1e0..13c327f825b 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -1,14 +1,13 @@ -# Inkling 2 Mini on CUDA: upstream #4387 with jschmied's #4364, #4365 and #4441, and a whole-model run on TOP +# Inkling 2 Mini on CUDA: jschmied's #4441 engine registered, with #4387's checks and a whole-model run on TOP -- Merges Ash's #4387 and jschmied's C1 (#4364), C3 (#4365) and H2 + C4 (#4441) with their commits; #4387's engine - serves `inkling2_loop`, with jschmied's three fixes (layer-sized plan, one sliding-norm upload, raw gate and sink). -- `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: #4387's serving - checks, the float64 reference and its planted control, then first-token time, prompt speed, decode speed and - memory at 1 and 4 streams. The recipe's README notes what RTX Spark (Windows and WSL2) needs. -- Mini prompt snapshots save and restore each key head's ring rows: the CUDA caches are head-major, and the - row-major copy left restored prompts' logits off from a fresh prefill. -- Mini loop messages now store `[core][role][row][c]` planes, matching each controller's role offset across multi-row prompt chunks; the CUDA reference checks the same served layout. -- The sampled CUDA serving reference widens the same BF16 logits the device sampler consumes, while retaining exact comparisons of the original FP32 logits. -- Mini CUDA serves `--parallel N` streams at once: each lane owns its sequence state and CUDA stream over shared - weights, and a shared round queues every lane's forward before it waits. Before, the server admitted N requests - to one lane and failed the others with `NoFreeSlot`. The TOP receipt adds the bandwidth limit and a 4-stream gate. +- Merges Ash's #4387 and jschmied's C1 (#4364), C3 (#4365) and H2 + C4 (#4441) with their commits. `inkling2_loop` + is now served by #4441's engine (graphs, fused input projections, every stream's rows in one forward); #4387's + separate loop engine is removed, so CUDA no longer advertises structured output it refused. +- #4387's serving checks (device draws against host selection, fresh against resumed prompts, two streams in shared + rounds against each alone) run against #4441's engine. Copy drafting is not checked: that engine has no draft path yet. +- `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: the serving checks, + the float64 reference and its planted control, then first-token time, prompt speed, decode speed, memory + (`/proc/meminfo`) and the bandwidth limit at 1 and 4 streams; 4 streams must give 1.5 times one stream's total. + The recipe's README notes what RTX Spark (native Windows and WSL2) needs. +- Metal Mini admission budgets a target state for every stream, so concurrent full-window requests no longer run out + of state; the Metal checkpoint check reads the first logprob row after the first token. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 33c990ed2ef..01012908551 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -4,16 +4,13 @@ GPU door. The job has no network, so the checkpoint must already sit in the pilot folder as `Inkling-2-Mini` (or `models/Inkling-2-Mini`); the script refuses and lists the Inkling configs under `/assets` when it does not. -The server is #4387's engine (`inkling2.native`, model type `inkling2_loop`) with jschmied's three load and -attention fixes from his #4387 comments; #4441's engine (`inkling2.mini_native`) rides along for its float64 -reference. The script fails on any of: `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test -inkling2-mini-ref` (32 greedy tokens equal to the float64 host reference), that reference's planted control staying -green, a failed stream in `tools/bench_concurrent.py` at 1 and 4 streams, or 4 streams giving under 1.5 times one -stream's total tok/s. The receipt also sets one stream's decode against GB10's bandwidth limit: the weight bytes a -token reads (from the checkpoint's headers) over 273 GB/s. - -Each `--parallel` stream gets its own lane: a complete sequence state (cache and forward scratch, about 1.5 GiB at an -8K window) and CUDA stream over the shared weights. A shared round queues every lane's forward before it waits on any. +The server is jschmied's #4441 engine (`inkling2.native`, model type `inkling2_loop`, on his #4364 and #4365): graphs, +fused input projections and one batched forward for every stream's rows in a round. #4387's checks run against it. +The script fails on any of: `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test inkling2-mini-ref` (32 +greedy tokens equal to the float64 host reference), that reference's planted control staying green, a failed stream +in `tools/bench_concurrent.py` at 1 and 4 streams, or 4 streams giving under 1.5 times one stream's total tok/s. The +receipt also sets one stream's decode against GB10's bandwidth limit: the weight bytes a token reads (from the +checkpoint's headers) over 273 GB/s. ## Receipt: TOP's GB10, one capped run @@ -44,6 +41,7 @@ Linux route. From #1010 (`5b1f10812`) and #2107: WDDM pool through `cuMemGetInfo_v2`, and `nvidia-smi`'s NPU row is filtered out. - Under WSL2 `/proc/meminfo` is WSL's RAM (about 30 GiB of 128 GB), not the GPU's 96 GB WDDM pool; with `WSL_DISTRO_NAME` set, admission reads the CUDA pool instead (`TENSORFOLD_UNIFIED_HOST_COUNTS` overrides it). -- For Mini, I need three things before it builds and serves there: the Inkling CUDA kernels compiled by MSVC's - front end (only nvcc with gcc 14 has built them so far), one load of the 18.9 GiB single-shard checkpoint - through Windows' threaded reads, and the GB10's exactness checks repeated on the N1X. No N1X run of Mini exists yet. +- For Mini on native Windows, I need the Inkling CUDA kernels compiled with MSVC as nvcc's host front end (only gcc 14 + has built them so far) and one load of the 18.9 GiB single-shard checkpoint through Windows' threaded reads. +- For Mini under WSL2, I need neither: it is the Linux build with gcc 14. Only the pool reading above differs. +- Either way, the GB10's exactness checks must be repeated on the N1X. No N1X run of Mini exists yet. diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index f3cc43f061d..1c7a7360839 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -168,7 +168,6 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // ours: Inkling 2's grouped experts .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations - .{ .name = "inkling2_loop_math", .src = "inkling2/loop_math", .flags = &.{"-O3"} }, // Mini residuals, cross-pass messages, gates and split QKV .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention .{ .name = "inkling2_loop", .src = "inkling2/loop", .flags = glue }, // Inkling 2 Mini: loop messages, gates .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 01452e97e89..9577e43ac38 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -18,11 +18,6 @@ pub const pending = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 272, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, }; /// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. pub const cuda_132 = [_]registry.Override{}; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 64c70ecc89d..e1e2fc1ffa8 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -118,7 +118,6 @@ pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops") pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; -pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const inkling2_loop: []const u8 = if (available) &Blob("fatbin_inkling2_loop").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 7c562a8a24c..05c88f6e672 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -7,9 +7,6 @@ test { _ = @import("mini_host_test.zig"); _ = @import("plan.zig"); _ = @import("loop.zig"); - _ = @import("loop_cache.zig"); - _ = @import("loop_model.zig"); - _ = @import("loop_model_test.zig"); _ = @import("prompt.zig"); _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 21e7f7e3c94..0eecf58de99 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -11,18 +11,14 @@ pub const config = @import("config.zig"); pub const plan = @import("plan.zig"); pub const names = @import("names.zig"); pub const loop = @import("loop.zig"); -pub const loop_cache = @import("loop_cache.zig"); -pub const loop_model = @import("loop_model.zig"); -pub const loop_math_cuda = @import("loop_math_cuda.zig"); pub const mini_weights = @import("mini_weights.zig"); pub const mini_model = @import("mini_model.zig"); pub const mini_backend = @import("mini_backend.zig"); pub const mini_snap = @import("mini_snap.zig"); /// The float64 reference the CUDA forward's greedy tokens are checked against. pub const mini_ref = @import("mini_ref.zig"); -pub const mini_native = @import("mini_native.zig"); -/// The native CUDA registry's retained Inkling 2 loop entry. -pub const native = @import("cuda_native.zig"); +/// The native CUDA registry's entry for inkling2_loop (native/cuda_families.zig). +pub const native = @import("mini_native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -36,9 +32,6 @@ test { _ = modelopt; _ = native; _ = loop; - _ = loop_cache; - _ = loop_model; - _ = loop_math_cuda; _ = config; _ = plan; _ = mini_model; @@ -47,5 +40,4 @@ test { _ = mini_backend; _ = mini_snap; _ = mini_ref; - _ = mini_native; } diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index 1ab486edf31..57b41e050ae 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -10,7 +10,6 @@ pub const Set = struct { attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, experts: @import("contract_inkling2_experts.zig").Set = .{}, - loop_math: @import("contract_inkling2_loop_math_extra.zig").Set = .{}, /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -23,12 +22,10 @@ pub const Set = struct { errdefer set.ops.deinit(); try set.experts.init(gpu, s, a, list); errdefer set.experts.deinit(); - try set.loop_math.init(gpu, s, a, list); return set; } pub fn deinit(set: *Set) void { - set.loop_math.deinit(); set.experts.deinit(); set.ops.deinit(); set.attn.deinit(); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index b15fa6d7c99..21c7a2acf32 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -49,7 +49,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index 1d0141b7b22..45a2d1b2ed1 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -1,4 +1,4 @@ -//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots, admission and copied drafts. +//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots and admission. const std = @import("std"); const lanes = @import("lanes"); const mini = @import("inkling2"); @@ -7,7 +7,8 @@ const core = @import("core"); const check = @import("check.zig"); const native = mini.native; -const Lane = @typeInfo(@FieldType(@FieldType(native.Owned, "backend"), "lanes")).pointer.child; +const Mini = mini.mini_backend.Mini; +const Saved = mini.mini_snap.Saved; const Gpu = check.Gpu; const sampled: lanes.Sampling = .{ .seed = 37, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; @@ -23,20 +24,15 @@ const Trace = struct { } }; -/// Lane 0: a lone stream always takes the first free lane. -fn target(loaded: *native.Loaded) *Lane { - return &loaded.target.backend.lanes[0]; -} - -fn download(l: *Lane, src: u64, out: []f32) !void { - try l.s.synchronize(); - try cuda.memory.download(l.s.d, src, std.mem.sliceAsBytes(out)); +fn download(t: *Mini, src: u64, out: []f32) !void { + try t.s.synchronize(); + try cuda.memory.download(t.d, src, std.mem.sliceAsBytes(out)); } /// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.stream.Reuse) !Trace { - const t = target(loaded); - const v = t.m.w.c.text.unpadded_vocab; + const t = loaded.target; + const v: usize = t.m.c.unpadded_vocab; var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-trace", .prompt = prompt, .max_new = @intCast(n), .sampling = sampling, .reuse = reuse }); defer s.deinit(gpu.gpa); const b = loaded.backend; @@ -48,7 +44,7 @@ fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes const draw_row: ?[]f32 = if (host and cuda.sample.ruleFor(sampling) != null) try gpu.gpa.alloc(f32, v) else null; defer if (draw_row) |rounded| gpu.gpa.free(rounded); try b.prefill(&s); - try download(t, t.last.ptr, logits[0..v]); + try download(t, t.lanes.getPtr(&s).?.last, logits[0..v]); // the prompt's last row, kept for the stream's slot var handle: ?u64 = try b.first(&s, prompt.len); for (0..n) |i| { ids[i] = if (host) blk: { @@ -91,13 +87,12 @@ fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { /// Save one complete state at `cut`, restore it through the genuine prompt-reuse hook and rerun the suffix. fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling, fresh: *const Trace) !void { - const Saved = @TypeOf(target(loaded).m).Saved; const Keeper = struct { - b: *native.Owned, + b: *Mini, saved: ?*Saved = null, fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { const k: *@This() = @ptrCast(@alignCast(ptr)); - k.saved = k.b.backend.saveState(s, mark) catch null; + k.saved = k.b.saveState(s, mark) catch null; } }; const t = loaded.target; @@ -111,7 +106,7 @@ fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sa try b.prefill(&s); break :snapshot keeper.saved orelse return error.MiniSnapshotNotSaved; }; - defer t.backend.dropState(saved); + defer t.dropState(saved); var resumed = try trace(gpu, loaded, prompt, sampling, fresh.ids.len, false, .{ .saved = saved, .at = cut }); defer resumed.deinit(gpu.gpa); if (resumed.cached != cut or resumed.failed) return error.MiniSnapshotNotRestored; @@ -130,20 +125,7 @@ fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void } } -fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.proposer.Proposer) !void { - var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); - defer cfg.deinit(gpu.gpa); - cfg.timed = false; - var clock: lanes.fake.FixedClock = .{}; - var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); - defer e.deinit(); - if (proposer) |p| s.proposer = p; - try e.addStream(s); - while (!s.finished) try e.step(); - if (s.reason != .length) return error.MiniServingDidNotFinish; -} - -/// Both lanes decode at once in shared rounds; a third request finds no free lane until one ends. +/// Both slots decode at once in shared rounds; a third request finds no free slot until one ends. fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) !void { var plain_a = try trace(gpu, loaded, a, null, 10, false, .{}); defer plain_a.deinit(gpu.gpa); @@ -155,7 +137,7 @@ fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) ! defer second.deinit(gpu.gpa); var third = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-third", .prompt = a, .max_new = 10 }); defer third.deinit(gpu.gpa); - var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, loaded.rows, loaded.rows - 1); // the host's widths (native/cuda_startup_phase.zig) defer cfg.deinit(gpu.gpa); cfg.timed = false; var clock: lanes.fake.FixedClock = .{}; @@ -176,111 +158,6 @@ fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) ! if (!native.fits(loaded.ctx, @intCast(a.len), third.max_new)) return error.MiniSlotNotReleased; } -/// Priced copies deliberately alternate whole matches, first-row rejection and a prefix match. -const Copier = struct { - prompt_len: usize, - plain: []const u32, - out: [4]u32 = undefined, - calls: usize = 0, - rejected: bool = false, - partial: bool = false, - continued: bool = false, - full: bool = false, - was_rejected: bool = false, - - fn propose(ptr: *anyopaque, context: []const u32, most: i64) anyerror![]const u32 { - const c: *@This() = @ptrCast(@alignCast(ptr)); - const n = context.len - c.prompt_len; - if (n >= c.plain.len or most < 2) return &.{}; - if (c.was_rejected) c.continued = true; - const count = @min(c.out.len, @min(c.plain.len - n, @as(usize, @intCast(most)))); - for (c.out[0..count], 0..) |*token, i| token.* = c.plain[n + i]; - const mode = c.calls % 3; - c.was_rejected = false; - if (mode == 0 and count >= 2) { - c.full = true; - } else if (mode == 1 and count >= 2) { - c.out[0] = if (c.out[0] == 0) 1 else 0; - c.rejected = true; - c.was_rejected = true; - } else if (count >= 2) { - c.out[1] = if (c.out[1] == 0) 1 else 0; - c.partial = true; - } - c.calls += 1; - return c.out[0..count]; - } - - fn proposer(c: *Copier) lanes.proposer.Proposer { - return .{ .ptr = c, .vtable = &.{ - .propose = propose, - .last_match = struct { - fn f(_: *anyopaque) i64 { - return 1; - } - }.f, - .priced = true, - } }; - } -}; - -/// Rewind a rejected, partially accepted or fully accepted window, then compare continuation bits with serial decode. -fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, plain: []const u32, accepted: usize) !void { - const t = target(loaded); - const v = t.m.w.c.text.unpadded_vocab; - const next = accepted + 1; - const ref = try gpu.gpa.alloc(f32, v); - defer gpu.gpa.free(ref); - var serial = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-serial", .prompt = prompt, .max_new = 12, .sampling = sampling }); - defer serial.deinit(gpu.gpa); - const b = loaded.backend; - try b.prefill(&serial); - for (plain[0 .. next + 1], 0..) |token, i| _ = try b.queue(&serial, .{ .value = token }, prompt.len + i + 1); - try download(t, t.m.s.logits, ref); - b.release(&serial); - - var drafted = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-drafted", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); - defer drafted.deinit(gpu.gpa); - defer b.release(&drafted); - try b.prefill(&drafted); - const pending = plain[0]; - var tokens: [4]u32 = undefined; - for (&tokens, 0..) |*token, i| token.* = plain[i + 1]; - if (accepted < tokens.len) tokens[accepted] = if (tokens[accepted] == 0) 1 else 0; - var positions: [5]u64 = undefined; - for (&positions, 0..) |*p, i| p.* = prompt.len + i + 1; - const window: lanes.backend.Window = .{ .stream = &drafted, .tokens = &tokens, .parents = null, .positions = &positions, .pending = pending, .held = 0 }; - var picks: [5]u32 = undefined; - var drafts: [4]u32 = undefined; - var out = [1]lanes.backend.Verified{.{ .sampled = &picks, .drafts = &drafts }}; - try b.verify(&.{window}, &out); - if (picks[accepted] != plain[next]) return error.MiniWrongCorrection; - var path: [5]u32 = undefined; - for (path[0..next], 0..) |*p, i| p.* = @intCast(i); - try b.keep(&.{window}, &.{path[0..next]}); - const handle = try b.queue(&drafted, .{ .value = plain[next] }, prompt.len + next + 1); - const after = try gpu.gpa.alloc(f32, v); - defer gpu.gpa.free(after); - try download(t, t.m.s.logits, after); - if (!std.mem.eql(u8, std.mem.sliceAsBytes(ref), std.mem.sliceAsBytes(after))) return error.MiniRollbackChangedLogits; - if (try b.read(handle) != plain[next + 1]) return error.MiniPostRejectionTokenChanged; -} - -fn copiedDrafts(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { - for ([_]?lanes.Sampling{ null, sampled }) |sampling| { - var plain = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); - defer plain.deinit(gpu.gpa); - var copier: Copier = .{ .prompt_len = prompt.len, .plain = plain.ids }; - var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-copied", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); - defer s.deinit(gpu.gpa); - try serve(gpu, loaded, &s, copier.proposer()); - if (!std.mem.eql(u32, s.emitted(), plain.ids)) return error.MiniCopiesChangedTarget; - if (s.drafted == 0 or s.accepted == 0 or s.accepted == s.drafted) return error.MiniCopyCoverageMissing; - if (!(copier.full and copier.rejected and copier.partial and copier.continued)) return error.MiniCopyCaseMissing; - for ([_]usize{ 0, 1, 4 }) |accepted| try rollback(gpu, loaded, prompt, sampling, plain.ids, accepted); - } -} - fn readIds(gpu: Gpu, path: []const u8) ![]u32 { const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, path, gpu.gpa, .limited(1 << 26)); defer gpu.gpa.free(text); @@ -296,7 +173,7 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { defer gpu.gpa.free(ids); if (ids.len < 4096) return error.MiniServingPromptTooShort; const context = ids.len + 64; - var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true, .lanes = 2 }); + var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = false, .lanes = 2 }); defer loaded.deinit(loaded.ctx); try hostReference(gpu, &loaded, ids[0..4096]); check.pass("Mini CUDA serving matches the host reference token for token", .{}); @@ -304,6 +181,4 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens", .{}); try admission(gpu, &loaded, ids[0..257], ids[17..1042]); check.pass("Mini CUDA two lanes decode together in shared rounds without changing tokens; a third waits", .{}); - try copiedDrafts(gpu, &loaded, ids[0..64]); - check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly", .{}); } diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 8ca35c034e9..8bf8fab026d 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -3,7 +3,7 @@ pub const usage = \\usage: tf-cuda-test \\ qwen4 synthetic native Qwen4: binary64 logits/tokens, state seams, lanes and copied drafts - \\ inkling2-serving MODEL IDS_FILE Mini CUDA host-reference, resume, admission and copy-rollback serving equivalence + \\ inkling2-serving MODEL IDS_FILE Mini CUDA host-reference, resume and admission serving equivalence \\ qwen-draft-frames MODEL DRAFTER IDS OUT native 27B DFlash frames: raw bytes equal across partitions, controls red \\ experts-rows experts_rows.cu's windows and chunks against the decode kernel's one-row launches \\ route-rows route_rows.cu's router logits and softmax top-k against float64 (synthetic rows) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 5177fd7a454..2171d2c8a7b 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 3c02d147eff2053efb805faff7c9434df2eaf50883a5f85f2a3215e zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 3be92a6a0d47152a5d8eea1be0d42964607bab8541c12ff8bf435a5a91652801 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #4441 C4d: inkling2_loop image registered +zig/src/cuda/kernels.zig 30d1f43d7dae38cbaeeec1ebe2a7d1deeb9ae968d80f2f99fa642bfd3c79d8fa raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt image registered; #1858: the idol_decoder image registered; #4441 C4d: inkling2_loop image registered; the inkling2_loop_math image removed with #4387's loop stack (Mini serves on #4441's) zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw From 54bf2c7f0cf3f72e5ab9ef9d4449c81a260fc6e0 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:34:39 +0800 Subject: [PATCH 53/84] docs: Inkling 2 Mini GB10 receipt on #4441's engine: 32.5 tok/s at one stream, 117.8 at four --- docs/recipes/inkling-2-mini-cuda/README.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 01012908551..05d59e3757d 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -14,21 +14,20 @@ checkpoint's headers) over 273 GB/s. ## Receipt: TOP's GB10, one capped run -Job `top-0759755a0515` at `2301ab379`, `--context 8192`, greedy, 256 tokens, 3 reps, medians. This is one run with +Job `top-16bffb6ca094` at `9f542e6fa`, `--context 8192`, greedy, 256 tokens, 3 reps, medians. This is one run with these settings, not a benchmark. | Streams | First token (code / chat) | Prompt (code) | Decode a stream | Total decode | Failed | |---|---|---|---|---|---| -| 1 | 0.36 s / 0.18 s | 41.9 tok/s | 5.7 tok/s | 5.7 tok/s | 0 | -| 4 | 0.90 s / 0.45 s | 17.3 tok/s | 2.3 tok/s | 9.4 tok/s (1.65x) | 0 | +| 1 | 0.077 s / 0.038 s | 195.9 tok/s | 32.5 tok/s | 32.5 tok/s | 0 | +| 4 | 0.189 s / 0.092 s | 82.6 tok/s | 29.6 tok/s | 117.8 tok/s (3.62x) | 0 | -Memory (`/proc/meminfo`, host used): 10.7 GiB before the server, 35.3 GiB with Mini loaded with 4 lanes, and the same -after both levels. GPU (`nvidia-smi`): 23.9 GiB held by the server. +Memory (`/proc/meminfo`, host used): 10.9 GiB before the server, 31.6 GiB with Mini loaded for 4 streams, and the +same after both levels. GPU (`nvidia-smi`): 20.0 GiB held by the server. Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the -whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 5.7 tok/s is 12% of it. The gap is not bandwidth: -the 175 ms a token is consistent with roughly 1,350 small launches and one-row matrix kernels per token, unbatched -across lanes [INFERENCE, not profiled]. CUDA graphs per lane and batched expert rows across lanes are what is missing. +whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 32.5 tok/s is 66% of it. #4387's own engine, removed +here, gave 5.7 tok/s at one stream and 9.4 at four on the same GB10 (job `top-0759755a0515`). ## RTX Spark (N1X): what differs and what must change From 128bd7a6362dc49f2304992873a8b379728f4137 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:34:18 +0800 Subject: [PATCH 54/84] inkling2: contract the served loop.cu message and gate kernels; refuse expired Metal token handles; test the vocab bound Ports the removed loop_math contract's FP64 references and planted controls to tf_ink2_loop_mix and the three gate launches. Metal's token ring now refuses a handle over 4,096 draws old instead of returning the newer token in its slot. A host test sends id vocab through Mini's forward with no device, proving the refusal comes before any launch. --- ...nkling-2-mini-runs-whole-on-our-spark-g.md | 8 +- docs/recipes/inkling-2-mini-cuda/README.md | 8 +- .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 75 ++++ .../recipes/inkling-2-mini-cuda/run-script.sh | 1 + .../contract/inkling2_experts_records.zig | 6 +- zig/src/families/inkling2/metal/backend.zig | 18 +- zig/src/families/inkling2/mini_model.zig | 9 + zig/tests/cuda/contract_inkling2.zig | 4 + zig/tests/cuda/contract_inkling2_loop.zig | 358 ++++++++++++++++++ zig/tests/cuda/contract_limits.zig | 2 +- 10 files changed, 481 insertions(+), 8 deletions(-) create mode 100755 docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh create mode 100644 zig/tests/cuda/contract_inkling2_loop.zig diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index 13c327f825b..b37b9db11b9 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -9,5 +9,11 @@ the float64 reference and its planted control, then first-token time, prompt speed, decode speed, memory (`/proc/meminfo`) and the bandwidth limit at 1 and 4 streams; 4 streams must give 1.5 times one stream's total. The recipe's README notes what RTX Spark (native Windows and WSL2) needs. +- `tf-cuda-test kernel-contract "inkling2 loop"` checks the served `loop.cu` message mix and three gate launches + against FP64 references, with planted controls (an aliased block, a gate reading the wrong role plane). +- `llama-cpp-baseline.sh` serves Unsloth's UD-Q4_K_M GGUF with llama.cpp CUDA on TOP at the same settings, for + size, speed and greedy agreement with the float64 reference. - Metal Mini admission budgets a target state for every stream, so concurrent full-window requests no longer run out - of state; the Metal checkpoint check reads the first logprob row after the first token. + of state; the Metal checkpoint check reads the first logprob row after the first token, and an expired token + handle (more than 4,096 draws old) is refused instead of reading a newer token. +- A forward with token id `vocab` is refused before any launch (host test). diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 05d59e3757d..9eddd6c13c0 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -6,7 +6,8 @@ GPU door. The job has no network, so the checkpoint must already sit in the pilo The server is jschmied's #4441 engine (`inkling2.native`, model type `inkling2_loop`, on his #4364 and #4365): graphs, fused input projections and one batched forward for every stream's rows in a round. #4387's checks run against it. -The script fails on any of: `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test inkling2-mini-ref` (32 +The script fails on any of: `tf-cuda-test kernel-contract "inkling2 loop"` (the served message and gate kernels +against FP64 references, with their planted controls), `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test inkling2-mini-ref` (32 greedy tokens equal to the float64 host reference), that reference's planted control staying green, a failed stream in `tools/bench_concurrent.py` at 1 and 4 streams, or 4 streams giving under 1.5 times one stream's total tok/s. The receipt also sets one stream's decode against GB10's bandwidth limit: the weight bytes a token reads (from the @@ -22,8 +23,9 @@ these settings, not a benchmark. | 1 | 0.077 s / 0.038 s | 195.9 tok/s | 32.5 tok/s | 32.5 tok/s | 0 | | 4 | 0.189 s / 0.092 s | 82.6 tok/s | 29.6 tok/s | 117.8 tok/s (3.62x) | 0 | -Memory (`/proc/meminfo`, host used): 10.9 GiB before the server, 31.6 GiB with Mini loaded for 4 streams, and the -same after both levels. GPU (`nvidia-smi`): 20.0 GiB held by the server. +Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 10.9 GiB before the server, +31.6 GiB with Mini loaded for 4 streams, and the same after both levels; the server held 20.0 GiB of GPU memory +(`nvidia-smi`). Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 32.5 tok/s is 66% of it. #4387's own engine, removed diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh new file mode 100755 index 00000000000..084e8c61e06 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -0,0 +1,75 @@ +#!/bin/sh +# llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10. +# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +# The job has no network: the pilot folder's inkling-gguf holds llama.cpp at 690b87d88 (ggml-org #32704's merge), +# Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file renamed .gguf, and CMake 3.31.6's linux-aarch64 archive. +set -eu +pilot=/assets/drama3-pilot +src=$pilot/inkling-gguf +staged=$pilot/cuda-build-toolchain +gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu +cmake=cmake-3.31.6-linux-aarch64 +gguf=$src/Inkling-2-Mini-UD-Q4_K_M.gguf +out=/work/out/inkling2-llama +(cd "$src" && sha256sum -c --quiet) </dev/null +/work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null +rm -rf "$out" +mkdir -p "$out" +mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } +mem "before the server" +# run-script.sh's settings: 4 streams of 8,192 positions each +/work/llama-build/bin/llama-server -m "$gguf" --jinja -ngl 99 -c 32768 --parallel 4 --host 127.0.0.1 --port 8189 \ + --no-webui >"$out/server.log" 2>&1 & +server=$! +trap 'kill $server 2>/dev/null || :' EXIT +python3 - <<'EOF' +import time, urllib.request +for _ in range(600): + try: + urllib.request.urlopen("http://127.0.0.1:8189/health", timeout=5) + raise SystemExit(0) + except OSError: + time.sleep(1) +raise SystemExit("llama-server did not answer /health in 10 min") +EOF +mem "server loaded" +for level in 1 4; do + python3 tools/bench_concurrent.py http://127.0.0.1:8189 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ + --temperatures 0 --label "llama-$level" --output "$out/streams-$level.json" + mem "after $level streams" +done +python3 - "$out" <<'EOF' +import json, sys, urllib.request +out = sys.argv[1] +def post(path, body): + req = urllib.request.Request(f"http://127.0.0.1:8189{path}", json.dumps(body).encode(), {"Content-Type": "application/json"}) + return json.load(urllib.request.urlopen(req, timeout=300)) +agg = {} +for level in (1, 4): + cells = json.load(open(f"{out}/streams-{level}.json"))["cells"] + if any(c.get("failed") for c in cells): + raise SystemExit(f"{level} streams: a request failed") + agg[level] = max(c["aggregate_tps"] for c in cells) + for c in cells: + r = c["request"] + print(f"RESULT llama.cpp q4_k_m gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") +print(f"RESULT llama.cpp q4_k_m gb10 aggregate decode: 1 stream {agg[1]:.1f} tok/s, 4 streams {agg[4]:.1f} tok/s ({agg[4] / agg[1]:.2f}x)") +# run-script.sh's float64 reference continuation of this prompt (job top-16bffb6ca094: TensorFold equals it on all 32) +prompt = "The three laws of thermodynamics, explained for a curious student:" +want = "\n\n 1. Energy cannot be created or destroyed, only transformed.\n 2. Entropy (disorder) in a closed system always increases." +got = post("/completion", {"prompt": prompt, "n_predict": 32, "temperature": 0, "cache_prompt": False})["content"] +ids = lambda s: post("/tokenize", {"content": s})["tokens"] +w, g = ids(want), ids(got) +same = next((i for i, (a, b) in enumerate(zip(w, g)) if a != b), min(len(w), len(g))) +print(f"RESULT llama.cpp q4_k_m greedy vs float64 reference: first {same} of {len(w)} tokens equal: {got!r}") +EOF diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh index 65c630e1743..8450321a0a3 100755 --- a/docs/recipes/inkling-2-mini-cuda/run-script.sh +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -35,6 +35,7 @@ zig build install native -Dsm=121 -Dnvcc=/usr/local/cuda/bin/nvcc -Doptimize=Rel bin=/work/sm121/bin rm -rf "$out" mkdir -p "$out" +"$bin/tf-cuda-test" kernel-contract "inkling2 loop" # #4387's serving checks take any 4,096+ ids; these are fixed so every run sees the same prompt python3 -c 'import random; r = random.Random(4387); print(" ".join(str(r.randrange(1000, 199000)) for _ in range(4200)))' >"$out/ids.txt" "$bin/tf-cuda-test" inkling2-serving "$model" "$out/ids.txt" diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 9577e43ac38..89bb1ba5820 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -11,8 +11,12 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, }; -/// Measured on sm_121 alone (GB10, #4387): the other SMs' receipts are missing, so these refuse there (cuda_pending). +/// ModelOpt measured on sm_121 alone (GB10, #4387); loop is unmeasured. Missing receipts refuse there (cuda_pending). pub const pending = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_mix", .symbol = "tf_ink2_loop_mix", .image = "inkling2_loop", .threads = 256, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop", .threads = 256, .dynamic = 18432, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_lin", .symbol = "tf_ink2_loop_gate_lin", .image = "inkling2_loop", .threads = 128, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_mix", .symbol = "tf_ink2_loop_gate_mix", .image = "inkling2_loop", .threads = 256, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index 8b7bc6e2c2c..417523dfb80 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -284,8 +284,7 @@ pub const Metal = struct { } fn read(self: *Metal, handle: u64) !u32 { - if (handle >= self.next) return error.InvalidInklingTokenHandle; - const token = self.tokens[handle % ring]; + const token = try ringToken(self.tokens, self.next, handle); if (token >= self.vocab()) return error.InvalidInklingToken; return token; } @@ -405,6 +404,12 @@ fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } +/// The token behind `handle`: only the last `ring` handles drawn are still held. +fn ringToken(tokens: []const u32, next: u64, handle: u64) !u32 { + if (handle >= next or next - handle > ring) return error.InvalidInklingTokenHandle; + return tokens[handle % ring]; +} + fn firstLogprobRow(l: []const f32, tokens: []const u32, next: usize, count: u8) lanes.LogprobRow { std.debug.assert(tokens.len == ring and next > 0); return logprobRow(l, tokens[(next - 1) % ring], count); @@ -444,3 +449,12 @@ test "sampled first-token logprob uses the last written handle, not argmax" { const lse = @log(@as(f64, 1) + @exp(-@as(f64, 1)) + @exp(-@as(f64, 2)) + @exp(-@as(f64, 3))); try std.testing.expectApproxEqAbs(@as(f32, -3) - @as(f32, @floatCast(lse)), row.logprob, 1e-6); } + +test "a token handle expires once the ring has wrapped past it" { + var tokens: [ring]u32 = @splat(0); + tokens[0] = 7; + try std.testing.expectEqual(@as(u32, 7), try ringToken(&tokens, ring, 0)); + try std.testing.expectError(error.InvalidInklingTokenHandle, ringToken(&tokens, ring + 1, 0)); + try std.testing.expectEqual(@as(u32, 7), try ringToken(&tokens, ring + 1, ring)); + try std.testing.expectError(error.InvalidInklingTokenHandle, ringToken(&tokens, ring, ring)); +} diff --git a/zig/src/families/inkling2/mini_model.zig b/zig/src/families/inkling2/mini_model.zig index 065e64c7dff..e9a88cdaae6 100644 --- a/zig/src/families/inkling2/mini_model.zig +++ b/zig/src/families/inkling2/mini_model.zig @@ -363,3 +363,12 @@ test "the forward's launches type-check against the shared operators" { std.testing.refAllDecls(Model); std.testing.refAllDecls(Kernels); } + +test "the forward refuses token id vocab before any launch" { + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, @embedFile("fixtures/mini_config.json"), &why); + // no driver, weights or caches: a launch before the check would fault + var m: Model = .{ .gpa = std.testing.allocator, .d = undefined, .w = undefined, .c = &c.text, .context = 64, .slots = 1, .sliding = undefined, .full = undefined }; + const bad = [_]u32{ 1, c.text.vocab }; + try std.testing.expectError(error.InvalidToken, m.forward(undefined, undefined, &.{.{ .slot = 0, .p0 = 0, .tokens = &bad }}, true, 0, 1)); +} diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index 57b41e050ae..6bb9eeba3b6 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -9,6 +9,7 @@ pub const Set = struct { gpa: std.mem.Allocator, attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, + loop: @import("contract_inkling2_loop.zig").Set = .{}, experts: @import("contract_inkling2_experts.zig").Set = .{}, /// The set, its kernels appended to `list`. @@ -20,6 +21,8 @@ pub const Set = struct { errdefer set.attn.deinit(); try set.ops.init(gpu, s, a, list); errdefer set.ops.deinit(); + try set.loop.init(gpu, s, a, list); + errdefer set.loop.deinit(); try set.experts.init(gpu, s, a, list); errdefer set.experts.deinit(); return set; @@ -27,6 +30,7 @@ pub const Set = struct { pub fn deinit(set: *Set) void { set.experts.deinit(); + set.loop.deinit(); set.ops.deinit(); set.attn.deinit(); set.gpa.destroy(set); diff --git a/zig/tests/cuda/contract_inkling2_loop.zig b/zig/tests/cuda/contract_inkling2_loop.zig new file mode 100644 index 00000000000..850c9cff3ff --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop.zig @@ -0,0 +1,358 @@ +//! Inkling 2 Mini's served message and gate launches under FP64 references and planted controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const loop = @import("inkling2").loop; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const hidden = 2304; +const rank = 64; +const eps = ref.eps; +const mix_shapes = [_]c.Shape{ .{ .rows = 1, .n = hidden, .k = 3 }, .{ .rows = 3, .n = hidden, .k = 2 } }; +const gate_shapes = [_]c.Shape{ .{ .rows = 1, .n = hidden, .k = rank }, .{ .rows = 3, .n = hidden, .k = rank } }; + +/// Raw outputs use the old loop contract's FP32 tolerance; BF16 references include their final rounding. +pub fn Checked(comptime T: type) type { + return struct { + const Self = @This(); + inner: ref.Gated(T), + rig: *rig_.Rig = undefined, + msg: [200]u8 = undefined, + + pub fn deinit(self: *Self) void { + self.inner.deinit(); + } + pub fn kernel(self: *Self) g.Kernel { + self.rig = &self.inner.rig; + return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; + } + const vt = g.hooks(Self); + pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return self.inner.prepare(shape, fill, seed); + } + pub fn run(self: *Self) !void { + try self.inner.run(); + } + pub fn count(self: *Self) usize { + return self.inner.count(); + } + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + try self.inner.reference(want, mag); + } + pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { + try self.inner.bounds(want, mag, allow); + } + pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.inner.simulate(acc, order, out); + } + pub fn check(self: *Self, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const buf = try a.alloc(f64, 2 * self.count()); + defer a.free(buf); + const want = buf[0..self.count()]; + try self.reference(want, buf[self.count()..]); + const got = try self.rig.outputBytes(); + for (want, 0..) |w, i| { + const x = c.read(self.inner.k.spec().out, got, i); + const ok = if (std.math.isNan(w)) std.math.isNan(x) else if (!std.math.isFinite(w)) x == w else std.math.isFinite(x) and @abs(x - w) <= 1e-4 * (1 + @abs(w)); + if (!ok) return try std.fmt.bufPrint(&self.msg, "output {d}: {e} where {e} is due", .{ i, x, w }); + } + return null; + } + }; +} + +fn stressBank(i: usize) f32 { + return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; +} + +/// The four role queries over completed blocks and a partial, with Mini's post-dot 1/48 scale. +pub const Mix = struct { + kern: *const loop.Kernels, + f32_partial: bool = false, + aliased: bool = false, + shape: c.Shape = undefined, + blocks: []u16 = &.{}, + partial: []f32 = &.{}, + queries: []f32 = &.{}, + args: loop.MixArgs = undefined, + + pub const sums = {}; + pub fn spec(self: *const Mix) c.Spec { + return .{ .name = if (self.aliased) "control: inkling2 loop mix with block one replaced by block zero" else "inkling2 loop tf_ink2_loop_mix (four role queries, normalized sources)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) mix_shapes[0..1] else &mix_shapes }; + } + fn depth(s: c.Shape) usize { + return 2 * ref.blockDepth(s.n, 256) + 16; + } + pub fn control(self: *const Mix) ?g.Gate { + return if (self.aliased) .shapes else null; + } + pub fn free(self: *Mix, a: std.mem.Allocator) void { + a.free(self.blocks); + a.free(self.partial); + a.free(self.queries); + self.blocks = &.{}; + self.partial = &.{}; + self.queries = &.{}; + } + pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != hidden or shape.k < 1 or shape.k > loop.max_blocks + 1) return false; + self.free(a); + self.shape = shape; + const nb = shape.k - 1; + const plane = shape.rows * hidden; + self.blocks = try ref.bfs(a, rng, nb * plane, -1, 1); + self.partial = try ref.f32s(a, rng, plane, -1, 1); + self.queries = try ref.f32s(a, rng, 4 * hidden, -0.25, 0.25); + if (fill == .stress) { + for (self.blocks, 0..) |*v, i| v.* = c.toBf16(stressBank(i % hidden)); + for (self.partial, 0..) |*v, i| v.* = stressBank(i % hidden); + @memset(self.queries, 0); + } + if (!self.f32_partial) { + for (self.partial) |*v| v.* = c.fromBf16(c.toBf16(v.*)); + } + if (fill == .nonfinite) { + if (nb != 0) ref.plant(u16, self.blocks[0..plane], shape.rows, hidden, ref.asBf); + ref.plant(f32, self.partial, shape.rows, hidden, ref.asF32); + } + var args: loop.MixArgs = .{ .partial = 0, .out = 0, .out_stride = @intCast(plane), .n_blocks = @intCast(nb), .partial_f32 = @intFromBool(self.f32_partial), .nq = 4, .rows = @intCast(shape.rows), .h = hidden, .eps = eps, .scale = 1.0 / 48.0 }; + for (0..nb) |b| args.blocks[b] = try ref.input(rig, self.blocks[b * plane ..][0..plane]); + if (self.f32_partial) { + args.partial = try ref.input(rig, self.partial); + } else { + const bits = try a.alloc(u16, plane); + defer a.free(bits); + for (bits, self.partial) |*d, v| d.* = c.toBf16(v); + args.partial = try ref.input(rig, bits); + } + for (0..4) |q| args.query[q] = try ref.input(rig, self.queries[q * hidden ..][0..hidden]); + args.out = try rig.output(4 * plane * 4); + self.args = args; + return true; + } + pub fn run(self: *Mix, rig: *rig_.Rig) !void { + var args = self.args; + if (self.aliased) args.blocks[1] = args.blocks[0]; + try loop.mix(self.kern, rig.s, args); + } + pub fn count(self: *const Mix) usize { + return 4 * self.shape.rows * hidden; + } + fn source(self: *const Mix, s: usize, row: usize, col: usize) f64 { + const plane = self.shape.rows * hidden; + return if (s < self.shape.k - 1) ref.bf(self.blocks[s * plane + row * hidden + col]) else self.partial[row * hidden + col]; + } + pub fn solve(self: *const Mix, a: std.mem.Allocator, sum: ref.Sums, out: []ref.Iv) !void { + const terms = try a.alloc(ref.Iv, hidden); + defer a.free(terms); + const scratch = try a.alloc(f64, hidden); + defer a.free(scratch); + const d = depth(self.shape); + for (0..self.shape.rows) |row| { + var inv: [loop.max_blocks + 1]ref.Iv = undefined; + for (0..self.shape.k) |s| { + for (terms, 0..) |*t, col| { + const x = ref.Iv.of(self.source(s, row, col)); + t.* = x.mul(x); + } + inv[s] = ref.rms(sum.sum(terms, d, scratch), hidden, eps); + } + for (0..4) |q| { + var logits: [loop.max_blocks + 1]ref.Iv = undefined; + for (0..self.shape.k) |s| { + for (terms, 0..) |*t, col| t.* = ref.Iv.of(self.queries[q * hidden + col]).mul(ref.Iv.of(self.source(s, row, col))).mul(inv[s]); + logits[s] = sum.sum(terms, d, scratch).mul(ref.Iv.of(1.0 / 48.0)); + } + softmax(logits[0..self.shape.k]); + for (0..hidden) |col| { + var value = ref.Iv.of(0); + for (0..self.shape.k) |s| value = value.add(logits[s].mul(ref.Iv.of(self.source(s, row, col)).mul(inv[s]))); + out[(q * self.shape.rows + row) * hidden + col] = value; + } + } + } + } +}; + +fn softmax(logits: []ref.Iv) void { + var peak = logits[0]; + for (logits[1..]) |v| peak = .{ .m = @max(peak.m, v.m), .lo = @max(peak.lo, v.lo), .hi = @max(peak.hi, v.hi) }; + var den = ref.Iv.of(0); + for (logits) |*v| { + v.* = v.sub(peak).exp(); + den = den.add(v.*); + } + for (logits) |*v| v.* = v.div(den); +} + +const Stage = enum { down, lin, mix }; + +/// Three gates read message role planes 0, 1 and 2; each registration checks one launch's result. +pub const Gate = struct { + kern: *const loop.Kernels, + stage: Stage, + wrong_slot: bool = false, + shape: c.Shape = undefined, + h: []f32 = &.{}, + msg: []f32 = &.{}, + down_w: []u16 = &.{}, + forget: []u16 = &.{}, + gain: []u16 = &.{}, + norm: []u16 = &.{}, + args: loop.GateArgs = undefined, + + pub const sums = {}; + pub fn spec(self: *const Gate) c.Spec { + const names = [_][]const u8{ "inkling2 loop tf_ink2_loop_gate_down (BF16 rank-64 projections)", "inkling2 loop tf_ink2_loop_gate_lin (forget/gain blend)", "inkling2 loop tf_ink2_loop_gate_mix (BF16 normed output)" }; + return .{ .name = if (self.wrong_slot) "control: inkling2 loop gate zero reads message role plane one" else names[@backingInt(self.stage)], .accum = .f32, .depth = depth, .out = if (self.stage == .lin) .f32 else .bf16, .served = if (self.wrong_slot) gate_shapes[0..1] else &gate_shapes }; + } + fn depth(s: c.Shape) usize { + return ref.blockDepth(s.n, 256) + (2 * s.n + 31) / 32 + 5 + 2 * rank; + } + pub fn control(self: *const Gate) ?g.Gate { + return if (self.wrong_slot) .shapes else null; + } + pub fn free(self: *Gate, a: std.mem.Allocator) void { + a.free(self.h); + a.free(self.msg); + a.free(self.down_w); + a.free(self.forget); + a.free(self.gain); + a.free(self.norm); + self.h = &.{}; + self.msg = &.{}; + self.down_w = &.{}; + self.forget = &.{}; + self.gain = &.{}; + self.norm = &.{}; + } + pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != hidden or shape.k != rank) return false; + self.free(a); + self.shape = shape; + const plane = shape.rows * hidden; + self.h = try ref.f32s(a, rng, 3 * plane, -1, 1); + self.msg = try ref.f32s(a, rng, 4 * plane, -1, 1); + self.down_w = try ref.bfs(a, rng, 3 * rank * 2 * hidden, -0.1, 0.1); + self.forget = try ref.bfs(a, rng, 3 * hidden * rank, -0.2, 0.2); + self.gain = try ref.bfs(a, rng, 3 * hidden * rank, -0.2, 0.2); + self.norm = try ref.bfs(a, rng, 3 * hidden, 0.5, 1.5); + if (fill == .stress) { + for (self.h, 0..) |*v, i| v.* = stressBank(i % hidden); + for (self.msg, 0..) |*v, i| v.* = stressBank(i % hidden); + for (self.down_w) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.forget) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + } + if (fill == .nonfinite) { + ref.plant(f32, self.h, 3 * shape.rows, hidden, ref.asF32); + ref.plant(f32, self.msg, 4 * shape.rows, hidden, ref.asF32); + } + var args: loop.GateArgs = .{ .msg = try ref.input(rig, self.msg), .msg_stride = @intCast(plane), .slot = .{ 0, 1, 2 }, .down = 0, .out = 0, .out_stride = @intCast(plane), .rows = @intCast(shape.rows), .h_dim = hidden, .rank = rank, .eps_unit = eps, .eps = eps, .ys = 0 }; + for (0..3) |gate| { + args.h[gate] = try ref.input(rig, self.h[gate * plane ..][0..plane]); + args.down_w[gate] = try ref.input(rig, self.down_w[gate * rank * 2 * hidden ..][0 .. rank * 2 * hidden]); + args.forget[gate] = try ref.input(rig, self.forget[gate * hidden * rank ..][0 .. hidden * rank]); + args.gain[gate] = try ref.input(rig, self.gain[gate * hidden * rank ..][0 .. hidden * rank]); + args.norm[gate] = try ref.input(rig, self.norm[gate * hidden ..][0..hidden]); + } + const dn = 3 * shape.rows * rank * 2; + const yn = 3 * plane * 4; + const on = 3 * plane * 2; + args.down = if (self.stage == .down) try rig.output(dn) else try rig.scratch(dn); + args.ys = if (self.stage == .lin) try rig.output(yn) else try rig.scratch(yn); + args.out = if (self.stage == .mix) try rig.output(on) else try rig.scratch(on); + self.args = args; + return true; + } + pub fn run(self: *Gate, rig: *rig_.Rig) !void { + var args = self.args; + if (self.wrong_slot) args.slot[0] = 1; + try loop.gates(self.kern, rig.s, args, 3); + } + pub fn count(self: *const Gate) usize { + return switch (self.stage) { + .down => 3 * self.shape.rows * rank, + .lin, .mix => 3 * self.shape.rows * hidden, + }; + } + pub fn solve(self: *const Gate, a: std.mem.Allocator, sum: ref.Sums, out: []ref.Iv) !void { + const terms = try a.alloc(ref.Iv, 2 * hidden); + defer a.free(terms); + const scratch = try a.alloc(f64, 2 * hidden); + defer a.free(scratch); + const normalized = try a.alloc(ref.Iv, 2 * hidden); + defer a.free(normalized); + const zeta = try a.alloc(ref.Iv, rank); + defer a.free(zeta); + const ys = try a.alloc(ref.Iv, 3 * self.shape.rows * hidden); + defer a.free(ys); + const later = ref.later(sum); + const d = depth(self.shape); + for (0..3) |gate| for (0..self.shape.rows) |row| { + const h = self.h[(gate * self.shape.rows + row) * hidden ..][0..hidden]; + const m = self.msg[(gate * self.shape.rows + row) * hidden ..][0..hidden]; + var inv: [2]ref.Iv = undefined; + for (0..2) |side| { + const x = if (side == 0) h else m; + for (terms[0..hidden], x) |*t, v| { + const e = ref.Iv.of(v); + t.* = e.mul(e); + } + inv[side] = ref.rms(sum.sum(terms[0..hidden], d, scratch), hidden, eps); + } + for (normalized[0..hidden], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); + for (normalized[hidden..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); + for (0..rank) |r| { + for (terms, normalized, self.down_w[(gate * rank + r) * 2 * hidden ..][0 .. 2 * hidden]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); + zeta[r] = later.sum(terms, (2 * hidden + 31) / 32 + 5, scratch).bf(); + if (self.stage == .down) out[(gate * self.shape.rows + row) * rank + r] = zeta[r]; + } + for (0..hidden) |col| { + for (terms[0..rank], zeta, self.forget[(gate * hidden + col) * rank ..][0..rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const f = ref.tanh(later.sum(terms[0..rank], rank, scratch)); + for (terms[0..rank], zeta, self.gain[(gate * hidden + col) * rank ..][0..rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const gain = ref.tanh(later.sum(terms[0..rank], rank, scratch)); + const y = ref.Iv.of(1).sub(f).mul(ref.Iv.of(h[col])).add(gain.mul(ref.Iv.of(m[col]))); + const at = (gate * self.shape.rows + row) * hidden + col; + ys[at] = y; + if (self.stage == .lin) out[at] = y; + } + }; + if (self.stage != .mix) return; + for (0..3) |gate| for (0..self.shape.rows) |row| { + const at = (gate * self.shape.rows + row) * hidden; + for (terms[0..hidden], ys[at..][0..hidden]) |*t, y| t.* = ref.sq(y); + const inv = ref.rms(later.sum(terms[0..hidden], d, scratch), hidden, eps); + for (out[at..][0..hidden], ys[at..][0..hidden], self.norm[gate * hidden ..][0..hidden]) |*o, y, n| o.* = ref.Iv.of(ref.bf(n)).mul(y.mul(inv)).bf(); + }; + } +}; + +const groups = .{ "mixes", "gates" }; +pub const Set = struct { + k: loop.Kernels = undefined, + loaded: bool = false, + mixes: [3]Checked(Mix) = undefined, + gates: [4]Checked(Gate) = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.k = try loop.Kernels.load(gpu.d); + set.loaded = true; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.mixes, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = &set.k, .f32_partial = i == 1, .aliased = i == 2 } } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = &set.k, .stage = @fromBackingInt(@intCast(i % 3)), .wrong_slot = i == 3 } } }; + inline for (groups) |field| for (&@field(set, field)) |*x| try list.append(a, x.kernel()); + } + pub fn deinit(set: *Set) void { + if (!set.loaded) return; + inline for (groups) |field| for (&@field(set, field)) |*x| x.deinit(); + set.k.unload(); + set.loaded = false; + } +}; diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 21c7a2acf32..49aa25809fd 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -49,7 +49,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_loop", "inkling2_modelopt", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; From 354f41c61b5161f561d41f2c748f1ba7e0d608d8 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:15:00 +0800 Subject: [PATCH 55/84] docs: llama.cpp baseline reads the Desk's staged GGUF and b12611 source --- .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index 084e8c61e06..76cb337705d 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -1,24 +1,25 @@ #!/bin/sh # llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10. # swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh -# The job has no network: the pilot folder's inkling-gguf holds llama.cpp at 690b87d88 (ggml-org #32704's merge), -# Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file renamed .gguf, and CMake 3.31.6's linux-aarch64 archive. +# The job has no network: the Desk staged Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file (renamed .gguf) in the +# pilot folder's inkling-gguf, and llama.cpp b12611 (690b87d88, ggml-org #32704's merge) with CMake 3.31.6's +# linux-aarch64 archive in inkling-llamacpp. set -eu pilot=/assets/drama3-pilot -src=$pilot/inkling-gguf +llama=$pilot/inkling-llamacpp staged=$pilot/cuda-build-toolchain gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu cmake=cmake-3.31.6-linux-aarch64 -gguf=$src/Inkling-2-Mini-UD-Q4_K_M.gguf +gguf=$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf out=/work/out/inkling2-llama -(cd "$src" && sha256sum -c --quiet) </dev/null From 184bef55a64b781db2005b70fbf926b463e13984 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:28:08 +0800 Subject: [PATCH 56/84] docs: llama.cpp baseline links libggml-cuda against the toolkit and driver with the staged gcc --- docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index 76cb337705d..feb7d909a5f 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -19,9 +19,13 @@ EOF tar -C /work -xJf "$staged/$gcc.tar.xz" tar -C /work -xzf "$llama/$cmake.tar.gz" cc=/work/$gcc/bin/aarch64-none-linux-gnu +cuda_lib=/usr/local/cuda/targets/sbsa-linux/lib +export LD_LIBRARY_PATH=$cuda_lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} +# the staged gcc's ld searches only its own sysroot: point it at the toolkit and the host driver for libggml-cuda's needs /work/$cmake/bin/cmake -S "$llama/llama.cpp-b12611" -B /work/llama-build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121 \ -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER="$cc-gcc" -DCMAKE_CXX_COMPILER="$cc-g++" \ -DCMAKE_CUDA_COMPILER=/usr/local/cuda/bin/nvcc -DCMAKE_CUDA_HOST_COMPILER="$cc-g++" -DLLAMA_OPENSSL=OFF \ + -DCMAKE_EXE_LINKER_FLAGS="-Wl,-rpath-link,$cuda_lib:$cuda_lib/stubs:/usr/lib/aarch64-linux-gnu" \ -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_EXAMPLES=OFF >/dev/null /work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null rm -rf "$out" From fbbd43cbef8b8453cddc96d68f13ba3f11836f97 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:46:49 +0800 Subject: [PATCH 57/84] contract: gate the loop launches on their FP64 intervals, not a midpoint tolerance a BF16 tie can miss --- zig/tests/cuda/contract_inkling2_loop.zig | 59 ++--------------------- 1 file changed, 4 insertions(+), 55 deletions(-) diff --git a/zig/tests/cuda/contract_inkling2_loop.zig b/zig/tests/cuda/contract_inkling2_loop.zig index 850c9cff3ff..d221eaf618f 100644 --- a/zig/tests/cuda/contract_inkling2_loop.zig +++ b/zig/tests/cuda/contract_inkling2_loop.zig @@ -15,57 +15,6 @@ const eps = ref.eps; const mix_shapes = [_]c.Shape{ .{ .rows = 1, .n = hidden, .k = 3 }, .{ .rows = 3, .n = hidden, .k = 2 } }; const gate_shapes = [_]c.Shape{ .{ .rows = 1, .n = hidden, .k = rank }, .{ .rows = 3, .n = hidden, .k = rank } }; -/// Raw outputs use the old loop contract's FP32 tolerance; BF16 references include their final rounding. -pub fn Checked(comptime T: type) type { - return struct { - const Self = @This(); - inner: ref.Gated(T), - rig: *rig_.Rig = undefined, - msg: [200]u8 = undefined, - - pub fn deinit(self: *Self) void { - self.inner.deinit(); - } - pub fn kernel(self: *Self) g.Kernel { - self.rig = &self.inner.rig; - return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; - } - const vt = g.hooks(Self); - pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { - return self.inner.prepare(shape, fill, seed); - } - pub fn run(self: *Self) !void { - try self.inner.run(); - } - pub fn count(self: *Self) usize { - return self.inner.count(); - } - pub fn reference(self: *Self, want: []f64, mag: []f64) !void { - try self.inner.reference(want, mag); - } - pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { - try self.inner.bounds(want, mag, allow); - } - pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { - try self.inner.simulate(acc, order, out); - } - pub fn check(self: *Self, _: g.Gate) !?[]const u8 { - const a = self.rig.gpu.gpa; - const buf = try a.alloc(f64, 2 * self.count()); - defer a.free(buf); - const want = buf[0..self.count()]; - try self.reference(want, buf[self.count()..]); - const got = try self.rig.outputBytes(); - for (want, 0..) |w, i| { - const x = c.read(self.inner.k.spec().out, got, i); - const ok = if (std.math.isNan(w)) std.math.isNan(x) else if (!std.math.isFinite(w)) x == w else std.math.isFinite(x) and @abs(x - w) <= 1e-4 * (1 + @abs(w)); - if (!ok) return try std.fmt.bufPrint(&self.msg, "output {d}: {e} where {e} is due", .{ i, x, w }); - } - return null; - } - }; -} - fn stressBank(i: usize) f32 { return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; } @@ -338,15 +287,15 @@ const groups = .{ "mixes", "gates" }; pub const Set = struct { k: loop.Kernels = undefined, loaded: bool = false, - mixes: [3]Checked(Mix) = undefined, - gates: [4]Checked(Gate) = undefined, + mixes: [3]ref.Gated(Mix) = undefined, + gates: [4]ref.Gated(Gate) = undefined, pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { set.k = try loop.Kernels.load(gpu.d); set.loaded = true; const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; - for (&set.mixes, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = &set.k, .f32_partial = i == 1, .aliased = i == 2 } } }; - for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = &set.k, .stage = @fromBackingInt(@intCast(i % 3)), .wrong_slot = i == 3 } } }; + for (&set.mixes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.k, .f32_partial = i == 1, .aliased = i == 2 } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.k, .stage = @fromBackingInt(@intCast(i % 3)), .wrong_slot = i == 3 } }; inline for (groups) |field| for (&@field(set, field)) |*x| try list.append(a, x.kernel()); } pub fn deinit(set: *Set) void { From e0e5c6a6f7a37f458ef7c53d9248fcab0bfd4a98 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:16:29 +0800 Subject: [PATCH 58/84] docs: llama.cpp baseline stops when llama-server exits and prints its log --- docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index feb7d909a5f..9a87ae351b6 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -37,15 +37,18 @@ mem "before the server" --no-webui >"$out/server.log" 2>&1 & server=$! trap 'kill $server 2>/dev/null || :' EXIT -python3 - <<'EOF' -import time, urllib.request +python3 - "$server" "$out/server.log" <<'EOF' +import sys, time, urllib.request +pid, log = sys.argv[1:] for _ in range(600): try: urllib.request.urlopen("http://127.0.0.1:8189/health", timeout=5) raise SystemExit(0) except OSError: + if open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()[0] == "Z": + break time.sleep(1) -raise SystemExit("llama-server did not answer /health in 10 min") +raise SystemExit("llama-server exited or did not answer /health in 10 min:\n" + open(log).read()[-4000:]) EOF mem "server loaded" for level in 1 4; do From e425283b8e409d2c5513a0cbf633b6f308bbfc45 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:11:56 +0800 Subject: [PATCH 59/84] docs: Inkling 2 Mini compare.sh runs TensorFold and llama.cpp in one GB10 job with each server's peak memory and file bytes --- docs/recipes/inkling-2-mini-cuda/compare.sh | 13 ++++ .../inkling-2-mini-cuda/peak-memory.py | 62 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100755 docs/recipes/inkling-2-mini-cuda/compare.sh create mode 100755 docs/recipes/inkling-2-mini-cuda/peak-memory.py diff --git a/docs/recipes/inkling-2-mini-cuda/compare.sh b/docs/recipes/inkling-2-mini-cuda/compare.sh new file mode 100755 index 00000000000..6e7abf25c8a --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/compare.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Inkling 2 Mini on TOP's GB10, TensorFold beside llama.cpp, in one job so both meet the same machine: +# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/compare.sh +# Prints the bytes of the weights each engine loads, then runs run-script.sh and llama-cpp-baseline.sh one after the +# other, each under peak-memory.py watching its server. +set -eu +here=docs/recipes/inkling-2-mini-cuda +pilot=/assets/drama3-pilot +bytes() { stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {printf "%d bytes (%.3f GiB)", s, s / 2^30}'; } +echo "RESULT tensorfold bf16 checkpoint: $(bytes "$pilot"/Inkling-2-Mini/*.safetensors "$pilot"/models/Inkling-2-Mini/*.safetensors)" +echo "RESULT llama.cpp UD-Q4_K_M GGUF: $(bytes "$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf")" +python3 "$here/peak-memory.py" tensorfold-native sh "$here/run-script.sh" +python3 "$here/peak-memory.py" llama-server sh "$here/llama-cpp-baseline.sh" diff --git a/docs/recipes/inkling-2-mini-cuda/peak-memory.py b/docs/recipes/inkling-2-mini-cuda/peak-memory.py new file mode 100755 index 00000000000..dafdaf9f9b9 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/peak-memory.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""peak-memory.py NAME COMMAND...: runs COMMAND and prints the peak memory of the server whose program is NAME. + +It samples twice a second while COMMAND runs and exits with COMMAND's status. GB10 has one memory pool, so the peak +is the largest sum in one sample of the GPU memory nvidia-smi gives the job's compute processes and the server's +RssAnon + RssShmem. RssFile stays out: a mapped weight file's pages are page cache the kernel can drop, and VmHWM +(printed beside the peak) counts them. The fall in MemAvailable since the last sample before the server counts every +byte once, with whatever else the job held meanwhile. +""" +import glob, os, subprocess, sys, time + +name, command = sys.argv[1], sys.argv[2:] + + +def server() -> str | None: + for path in glob.glob("/proc/[0-9]*/cmdline"): + try: + program = open(path, "rb").read().split(b"\0")[0].decode() + except OSError: + continue + if os.path.basename(program) == name: + return path.split("/")[2] + return None + + +def kib(path: str) -> dict[str, int]: + """The kB fields of a /proc status or meminfo file.""" + fields = (line.split(":", 1) for line in open(path)) + return {k: int(v.split()[0]) for k, v in fields if v.endswith("kB\n")} + + +def gpu_kib() -> int: + rows = subprocess.run(["nvidia-smi", "--query-compute-apps=used_memory", "--format=csv,noheader,nounits"], + capture_output=True, text=True, check=True).stdout.split() + return 1024 * sum(int(mib) for mib in rows) + + +job = subprocess.Popen(command) +before = kib("/proc/meminfo")["MemAvailable"] +peak, hwm, fall, seen = (0, 0, 0), 0, 0, False +while job.poll() is None: + pid = server() + try: + status = kib(f"/proc/{pid}/status") if pid else None + except OSError: + status = None + available = kib("/proc/meminfo")["MemAvailable"] + if status: + seen = True + gpu, resident = gpu_kib(), status.get("RssAnon", 0) + status.get("RssShmem", 0) + peak = max(peak, (gpu + resident, gpu, resident)) + hwm, fall = max(hwm, status.get("VmHWM", 0)), max(fall, before - available) + elif not seen: + before = available + time.sleep(0.5) +gib = lambda k: f"{k / 2**20:.2f} GiB" +if seen: + print(f"RESULT {name} peak memory: {gib(peak[0])} (GPU {gib(peak[1])} + resident anon and shmem {gib(peak[2])}), " + f"VmHWM {gib(hwm)}, MemAvailable fell {gib(fall)}", flush=True) +elif job.returncode == 0: + sys.exit(f"{name} never ran under {' '.join(command)}: no peak memory to report") +sys.exit(job.returncode) From 91dd60e31c78b8d4d60a123bf708f7be0eb49711 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:11:56 +0800 Subject: [PATCH 60/84] docs: llama.cpp baseline scores its picks teacher-forced on the float64 reference and prints its slot context --- docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index 9a87ae351b6..79a2582a131 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -51,6 +51,8 @@ for _ in range(600): raise SystemExit("llama-server exited or did not answer /health in 10 min:\n" + open(log).read()[-4000:]) EOF mem "server loaded" +# the receipt names what the server did with -c and -ngl +grep -m 2 -E 'n_ctx_slot|offloaded' "$out/server.log" || : for level in 1 4; do python3 tools/bench_concurrent.py http://127.0.0.1:8189 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ --temperatures 0 --label "llama-$level" --output "$out/streams-$level.json" @@ -80,4 +82,11 @@ ids = lambda s: post("/tokenize", {"content": s})["tokens"] w, g = ids(want), ids(got) same = next((i for i, (a, b) in enumerate(zip(w, g)) if a != b), min(len(w), len(g))) print(f"RESULT llama.cpp q4_k_m greedy vs float64 reference: first {same} of {len(w)} tokens equal: {got!r}") +# teacher-forced, as tf-cuda-test inkling2-mini-ref scores TensorFold: after the reference's own prefix, is llama.cpp's +# next pick the reference's token? A free run says nothing past its first difference. +start = post("/tokenize", {"content": prompt, "add_special": True})["tokens"] +piece = lambda t: post("/detokenize", {"tokens": [t]})["content"] +pick = lambda i: post("/completion", {"prompt": start + w[:i], "n_predict": 1, "temperature": 0, "cache_prompt": False})["content"] +misses = [i for i in range(len(w)) if pick(i) != piece(w[i])] +print(f"RESULT llama.cpp q4_k_m teacher-forced on the float64 reference: {len(w) - len(misses)} of {len(w)} picks equal, differing at {misses}") EOF From 43a9d14b43afaae8fa209e1948e39918a81ff4fc Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:07:03 +0800 Subject: [PATCH 61/84] docs: Inkling 2 Mini GB10 receipt from top-bde5d508e589 at fbbd43cbe: 32.9 tok/s at one stream, 120.1 at four --- docs/recipes/inkling-2-mini-cuda/README.md | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 9eddd6c13c0..94fcb82f741 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -15,20 +15,27 @@ checkpoint's headers) over 273 GB/s. ## Receipt: TOP's GB10, one capped run -Job `top-16bffb6ca094` at `9f542e6fa`, `--context 8192`, greedy, 256 tokens, 3 reps, medians. This is one run with +Job `top-bde5d508e589` at `fbbd43cbe`, `--context 8192`, greedy, 256 tokens, 3 reps, medians. This is one run with these settings, not a benchmark. -| Streams | First token (code / chat) | Prompt (code) | Decode a stream | Total decode | Failed | +| Streams | First token (code / chat) | Prompt (code) | Decode a stream (code / chat) | Total decode (code / chat) | Failed | |---|---|---|---|---|---| -| 1 | 0.077 s / 0.038 s | 195.9 tok/s | 32.5 tok/s | 32.5 tok/s | 0 | -| 4 | 0.189 s / 0.092 s | 82.6 tok/s | 29.6 tok/s | 117.8 tok/s (3.62x) | 0 | +| 1 | 0.076 s / 0.036 s | 196.8 tok/s | 32.9 / 32.8 tok/s | 32.9 / 32.8 tok/s | 0 | +| 4 | 0.189 s / 0.090 s | 82.3 tok/s | 29.9 / 30.2 tok/s | 118.7 / 120.1 tok/s | 0 | -Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 10.9 GiB before the server, -31.6 GiB with Mini loaded for 4 streams, and the same after both levels; the server held 20.0 GiB of GPU memory +The 4-stream gate takes each level's better prompt: 120.1 over 32.9 tok/s, 3.65x. + +Checks in the same job: the CUDA engine matched the host reference token for token, fresh and resumed prompts gave +identical logits and tokens, and two lanes in shared rounds kept their tokens; 0 of 32 greedy tokens differed from +the float64 reference (smallest reference margin 0.11), and its planted control (no messages) differed at 6. The +kernel contract passed gates 1-4 on all 5 loop kernels with both planted controls red. + +Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 10.4 GiB before the server, +30.7 GiB with Mini loaded for 4 streams, and the same after both levels; the server held 20.0 GiB of GPU memory (`nvidia-smi`). Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the -whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 32.5 tok/s is 66% of it. #4387's own engine, removed +whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 32.9 tok/s is 67% of it. #4387's own engine, removed here, gave 5.7 tok/s at one stream and 9.4 at four on the same GB10 (job `top-0759755a0515`). ## RTX Spark (N1X): what differs and what must change From a529ce711333c96366786f28292dd5a0f003fbf0 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:07:52 +0800 Subject: [PATCH 62/84] docs: Inkling 2 Mini compare.sh builds llama-server as its own phase, caps the measured part at 600 s, shows llama-server's exit and log, prints GGUF bytes past 2 GiB --- docs/recipes/inkling-2-mini-cuda/compare.sh | 17 ++++--- .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 51 +++++-------------- .../inkling-2-mini-cuda/llama-cpp-build.sh | 28 ++++++++++ 3 files changed, 51 insertions(+), 45 deletions(-) create mode 100755 docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh diff --git a/docs/recipes/inkling-2-mini-cuda/compare.sh b/docs/recipes/inkling-2-mini-cuda/compare.sh index 6e7abf25c8a..b55848479b7 100755 --- a/docs/recipes/inkling-2-mini-cuda/compare.sh +++ b/docs/recipes/inkling-2-mini-cuda/compare.sh @@ -1,13 +1,18 @@ #!/bin/sh -# Inkling 2 Mini on TOP's GB10, TensorFold beside llama.cpp, in one job so both meet the same machine: +# Inkling 2 Mini on TOP's GB10, llama.cpp's side of the README's comparison: # swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/compare.sh -# Prints the bytes of the weights each engine loads, then runs run-script.sh and llama-cpp-baseline.sh one after the -# other, each under peak-memory.py watching its server. +# Prints the bytes of the weights each engine loads, builds llama-server, then measures it under peak-memory.py with +# the measured part capped at 10 minutes. TensorFold's side is run-script.sh's own job (its float64 reference alone +# takes over 4 minutes), under the same peak-memory.py. set -eu here=docs/recipes/inkling-2-mini-cuda pilot=/assets/drama3-pilot -bytes() { stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {printf "%d bytes (%.3f GiB)", s, s / 2^30}'; } +bytes() { stat -L -c %s "$@" 2>/dev/null | awk '{s += $1} END {printf "%.0f bytes (%.3f GiB)", s, s / 2^30}'; } echo "RESULT tensorfold bf16 checkpoint: $(bytes "$pilot"/Inkling-2-Mini/*.safetensors "$pilot"/models/Inkling-2-Mini/*.safetensors)" echo "RESULT llama.cpp UD-Q4_K_M GGUF: $(bytes "$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf")" -python3 "$here/peak-memory.py" tensorfold-native sh "$here/run-script.sh" -python3 "$here/peak-memory.py" llama-server sh "$here/llama-cpp-baseline.sh" +start=$(date +%s) +sh "$here/llama-cpp-build.sh" +echo "build: $(($(date +%s) - start)) s" +start=$(date +%s) +timeout 600 python3 "$here/peak-memory.py" llama-server sh "$here/llama-cpp-baseline.sh" +echo "measure: $(($(date +%s) - start)) s" diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index 79a2582a131..7f807d8aeb2 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -1,33 +1,11 @@ #!/bin/sh -# llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10. -# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh -# The job has no network: the Desk staged Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file (renamed .gguf) in the -# pilot folder's inkling-gguf, and llama.cpp b12611 (690b87d88, ggml-org #32704's merge) with CMake 3.31.6's -# linux-aarch64 archive in inkling-llamacpp. +# llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10, served by the +# llama-server llama-cpp-build.sh left in /work/llama-build. compare.sh runs both. set -eu pilot=/assets/drama3-pilot -llama=$pilot/inkling-llamacpp -staged=$pilot/cuda-build-toolchain -gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu -cmake=cmake-3.31.6-linux-aarch64 gguf=$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf out=/work/out/inkling2-llama -sha256sum -c --quiet </dev/null -/work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null +export LD_LIBRARY_PATH=/usr/local/cuda/targets/sbsa-linux/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} rm -rf "$out" mkdir -p "$out" mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } @@ -36,20 +14,15 @@ mem "before the server" /work/llama-build/bin/llama-server -m "$gguf" --jinja -ngl 99 -c 32768 --parallel 4 --host 127.0.0.1 --port 8189 \ --no-webui >"$out/server.log" 2>&1 & server=$! -trap 'kill $server 2>/dev/null || :' EXIT -python3 - "$server" "$out/server.log" <<'EOF' -import sys, time, urllib.request -pid, log = sys.argv[1:] -for _ in range(600): - try: - urllib.request.urlopen("http://127.0.0.1:8189/health", timeout=5) - raise SystemExit(0) - except OSError: - if open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()[0] == "Z": - break - time.sleep(1) -raise SystemExit("llama-server exited or did not answer /health in 10 min:\n" + open(log).read()[-4000:]) -EOF +trap 'status=$?; kill $server 2>/dev/null || :; [ $status = 0 ] || { echo "llama-server log, last 60 lines:"; tail -n 60 "$out/server.log"; }' EXIT +until python3 -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:8189/health", timeout=5)' 2>/dev/null; do + if ! kill -0 "$server" 2>/dev/null; then + wait "$server" && code=0 || code=$? + echo "llama-server exited with status $code before answering /health" >&2 + exit 1 + fi + sleep 1 +done mem "server loaded" # the receipt names what the server did with -c and -ngl grep -m 2 -E 'n_ctx_slot|offloaded' "$out/server.log" || : diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh new file mode 100755 index 00000000000..9aa1b82f5a6 --- /dev/null +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Builds llama.cpp b12611's CUDA llama-server into /work/llama-build for llama-cpp-baseline.sh. The job has no network: +# the Desk staged Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file (renamed .gguf) in the pilot folder's +# inkling-gguf, and llama.cpp b12611 (690b87d88, ggml-org #32704's merge) with CMake 3.31.6's linux-aarch64 archive in +# inkling-llamacpp. +set -eu +pilot=/assets/drama3-pilot +llama=$pilot/inkling-llamacpp +staged=$pilot/cuda-build-toolchain +gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu +cmake=cmake-3.31.6-linux-aarch64 +sha256sum -c --quiet </dev/null +/work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null +# loads every shared library the server needs: a loader error shows here, before the measured part +LD_LIBRARY_PATH=$cuda_lib /work/llama-build/bin/llama-server --version From 0754e13446e2ccc9a4d1efbf8b1c9fc6b764b728 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:53:04 +0800 Subject: [PATCH 63/84] inkling2: refuse block counts past the residual mixes' eight and head widths the attention kernels do not run, before loading --- zig/src/families/inkling2/config.zig | 19 +++++++++++++++++++ zig/src/families/inkling2/config_test.zig | 10 ++++++++++ zig/src/families/inkling2/kernels.zig | 5 +++-- zig/src/families/inkling2/loop.zig | 3 ++- .../inkling2/metal/attention_plan.zig | 5 +++-- zig/src/families/inkling2/ops.zig | 3 ++- 6 files changed, 39 insertions(+), 6 deletions(-) diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index 193aeae7eb9..594efb83ab2 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -11,6 +11,13 @@ pub const max_visits = 256; /// The widest gate rank the loop kernels hold (loop.cu kMaxRank; Mini's gate_rank is 64). pub const max_gate_rank = 128; +/// The attention kernels' fixed widths (attention.cu and the Metal attention shaders). +pub const head_dim = 128; +pub const d_rel = 16; + +/// The most finished attention-residual blocks a residual mix reads (ops.cu and loop.cu; Small makes 8, Mini 4). +pub const max_blocks = 8; + /// Every sixth layer attends over the whole context; the reference derives its layer types the same way. pub const global_every = 6; @@ -196,6 +203,10 @@ fn heads(o: std.json.ObjectMap, prefix: []const u8, why: *Why) !Heads { why.set("{d} query heads do not split over {d} key/value heads", .{ q, kv }); return error.Layout; } + if (dim != head_dim) { + why.set("{s}head_dim {d} is not {d}, the attention kernels' width", .{ prefix, dim, head_dim }); + return error.Unsupported; + } return .{ .q = q, .kv = kv, .dim = dim }; } @@ -253,6 +264,14 @@ fn parseText(o: std.json.ObjectMap, looped: bool, why: *Why) !Text { why.set("n_layers_per_attn_res_block {d} is past num_hidden_layers {d}", .{ t.block, t.layers }); return error.Layout; } + if (std.math.divCeil(u32, t.layers, t.block) catch unreachable > max_blocks) { + why.set("n_layers_per_attn_res_block {d} splits {d} layers into more than the residual mixes' {d} blocks", .{ t.block, t.layers, max_blocks }); + return error.Layout; + } + if (t.d_rel != d_rel) { + why.set("d_rel {d} is not {d}, the attention kernels' width", .{ t.d_rel, d_rel }); + return error.Unsupported; + } if (try int(o, "sconv_kernel_size", why) != conv_taps) { why.set("sconv_kernel_size must be {d}: the checkpoint's published short convolutions", .{conv_taps}); return error.Unsupported; diff --git a/zig/src/families/inkling2/config_test.zig b/zig/src/families/inkling2/config_test.zig index e92f6ca8082..c7159fca2ae 100644 --- a/zig/src/families/inkling2/config_test.zig +++ b/zig/src/families/inkling2/config_test.zig @@ -146,6 +146,16 @@ test "an mlp_ratio past 1024 is refused instead of overflowing, as is a block lo try refused(tiny, "\"n_layers_per_attn_res_block\": 6", "\"n_layers_per_attn_res_block\": 4294967295", error.Layout, "is past num_hidden_layers"); } +test "attention-residual blocks past the mixes' eight and widths the attention kernels do not run are refused" { + var why: config.Why = .{}; + try t.expectEqual(@as(u32, config.max_blocks), (try config.parse(t.allocator, real, &why)).text.layers / 6); + try refused(real, "\"n_layers_per_attn_res_block\": 6", "\"n_layers_per_attn_res_block\": 5", error.Layout, "into more than the residual mixes' 8 blocks"); + try refused(tiny, "\"n_layers_per_attn_res_block\": 6", "\"n_layers_per_attn_res_block\": 1", error.Layout, "splits 12 layers into more than"); + try refused(tiny, "\"head_dim\": 128,\n \"d_rel\"", "\"head_dim\": 64,\n \"d_rel\"", error.Unsupported, "head_dim 64 is not 128"); + try refused(tiny, "\"swa_head_dim\": 128", "\"swa_head_dim\": 256", error.Unsupported, "swa_head_dim 256 is not 128"); + try refused(tiny, "\"d_rel\": 16", "\"d_rel\": 32", error.Unsupported, "d_rel 32 is not 16"); +} + test "a scoring function, a layer count, a quantization_config and a root that the engine cannot read are refused" { try refused(tiny, "\"use_gate_bias\": true,\n \"tie_word_embeddings\"", "\"use_gate_bias\": true,\n \"scoring_func\": \"softmax\",\n \"tie_word_embeddings\"", error.Unsupported, "scoring_func must be"); try refused(tiny, "\"hidden_size\": 128,\n \"num_hidden_layers\": 12", "\"hidden_size\": 128,\n \"num_hidden_layers\": 129", error.Layout, "129 layers: the plan tables hold 128"); diff --git a/zig/src/families/inkling2/kernels.zig b/zig/src/families/inkling2/kernels.zig index cfdf45eb374..5cb8f24f5af 100644 --- a/zig/src/families/inkling2/kernels.zig +++ b/zig/src/families/inkling2/kernels.zig @@ -1,9 +1,10 @@ //! Inkling 2's attention kernels (inkling2/attention.cu): the launch plan's geometry and the four launches. const std = @import("std"); const cuda = @import("cuda"); +const config = @import("config.zig"); -pub const head_dim = 128; -pub const d_rel = 16; +pub const head_dim = config.head_dim; +pub const d_rel = config.d_rel; pub const extent = 1024; /// Keys a tile of tf_ink2_attn reads at once, and (row, head) pairs a block holds. pub const tile_keys = 64; diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig index 8aeb70ad604..a7c7ebed03b 100644 --- a/zig/src/families/inkling2/loop.zig +++ b/zig/src/families/inkling2/loop.zig @@ -2,8 +2,9 @@ //! C2 stand-in: the arithmetic #4337's Metal implementation runs; the kernel contract for these is C2's slice. const std = @import("std"); const cuda = @import("cuda"); +const config = @import("config.zig"); -pub const max_blocks = 8; +pub const max_blocks = config.max_blocks; pub const max_queries = 4; pub const max_gates = 3; pub const max_rank = 128; diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig index 6688dc8d7a0..49095e4facc 100644 --- a/zig/src/families/inkling2/metal/attention_plan.zig +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -1,8 +1,9 @@ //! Pure host geometry and ABI declarations for Inkling 2 Mini Metal attention. const std = @import("std"); +const config = @import("../config.zig"); -pub const head_dim = 128; -pub const d_rel = 16; +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; diff --git a/zig/src/families/inkling2/ops.zig b/zig/src/families/inkling2/ops.zig index 66e7b5d50a5..cb890a73a51 100644 --- a/zig/src/families/inkling2/ops.zig +++ b/zig/src/families/inkling2/ops.zig @@ -1,8 +1,9 @@ //! Inkling 2's glue kernels (inkling2/ops.cu): embedding, residual mix, row dots, router, SwiGLU epilogue, convs. const std = @import("std"); const cuda = @import("cuda"); +const config = @import("config.zig"); -pub const max_blocks = 8; +pub const max_blocks = config.max_blocks; pub const max_queries = 3; /// ops.cu's MixArgs, field for field. From 276e99ab4536f72c74b0580ada48f69965e976c2 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:53:04 +0800 Subject: [PATCH 64/84] inkling2 metal: drop the unused in-flight forward option --- zig/src/families/inkling2/metal/forward.zig | 5 ----- 1 file changed, 5 deletions(-) diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index a40caf566ea..7dd3e0c49ae 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -17,7 +17,6 @@ pub const Segment = struct { cache: *state.Cache, rows: usize }; pub const Options = struct { all: bool = false, ids: ?Ref = null, - flight: ?*mtl.CommandBuffer = null, taps: ?state.Ref = null, }; @@ -334,10 +333,6 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, commitFullHistories(m, e, s, segments); e.end(); cb.commit(); - if (options.flight) |flight| { - flight.* = cb.retain(); - return; - } cb.wait(); if (cb.failure()) |msg| { std.log.err("inkling2_loop forward: {s}", .{msg}); From 827a058505295dc1ccb62a98504bb5b725eb56bb Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:53:04 +0800 Subject: [PATCH 65/84] docs: leave the llama.cpp baseline to card 232 --- ...nkling-2-mini-runs-whole-on-our-spark-g.md | 2 - .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 83 ------------------- 2 files changed, 85 deletions(-) delete mode 100755 docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index b37b9db11b9..650c64dcd8a 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -11,8 +11,6 @@ The recipe's README notes what RTX Spark (native Windows and WSL2) needs. - `tf-cuda-test kernel-contract "inkling2 loop"` checks the served `loop.cu` message mix and three gate launches against FP64 references, with planted controls (an aliased block, a gate reading the wrong role plane). -- `llama-cpp-baseline.sh` serves Unsloth's UD-Q4_K_M GGUF with llama.cpp CUDA on TOP at the same settings, for - size, speed and greedy agreement with the float64 reference. - Metal Mini admission budgets a target state for every stream, so concurrent full-window requests no longer run out of state; the Metal checkpoint check reads the first logprob row after the first token, and an expired token handle (more than 4,096 draws old) is refused instead of reading a newer token. diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh deleted file mode 100755 index 9a87ae351b6..00000000000 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/bin/sh -# llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10. -# swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh -# The job has no network: the Desk staged Mainline_Support/Inkling-2-Mini-UD-Q4_K_M.gguf_file (renamed .gguf) in the -# pilot folder's inkling-gguf, and llama.cpp b12611 (690b87d88, ggml-org #32704's merge) with CMake 3.31.6's -# linux-aarch64 archive in inkling-llamacpp. -set -eu -pilot=/assets/drama3-pilot -llama=$pilot/inkling-llamacpp -staged=$pilot/cuda-build-toolchain -gcc=arm-gnu-toolchain-14.3.rel1-aarch64-aarch64-none-linux-gnu -cmake=cmake-3.31.6-linux-aarch64 -gguf=$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf -out=/work/out/inkling2-llama -sha256sum -c --quiet </dev/null -/work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null -rm -rf "$out" -mkdir -p "$out" -mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } -mem "before the server" -# run-script.sh's settings: 4 streams of 8,192 positions each -/work/llama-build/bin/llama-server -m "$gguf" --jinja -ngl 99 -c 32768 --parallel 4 --host 127.0.0.1 --port 8189 \ - --no-webui >"$out/server.log" 2>&1 & -server=$! -trap 'kill $server 2>/dev/null || :' EXIT -python3 - "$server" "$out/server.log" <<'EOF' -import sys, time, urllib.request -pid, log = sys.argv[1:] -for _ in range(600): - try: - urllib.request.urlopen("http://127.0.0.1:8189/health", timeout=5) - raise SystemExit(0) - except OSError: - if open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()[0] == "Z": - break - time.sleep(1) -raise SystemExit("llama-server exited or did not answer /health in 10 min:\n" + open(log).read()[-4000:]) -EOF -mem "server loaded" -for level in 1 4; do - python3 tools/bench_concurrent.py http://127.0.0.1:8189 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ - --temperatures 0 --label "llama-$level" --output "$out/streams-$level.json" - mem "after $level streams" -done -python3 - "$out" <<'EOF' -import json, sys, urllib.request -out = sys.argv[1] -def post(path, body): - req = urllib.request.Request(f"http://127.0.0.1:8189{path}", json.dumps(body).encode(), {"Content-Type": "application/json"}) - return json.load(urllib.request.urlopen(req, timeout=300)) -agg = {} -for level in (1, 4): - cells = json.load(open(f"{out}/streams-{level}.json"))["cells"] - if any(c.get("failed") for c in cells): - raise SystemExit(f"{level} streams: a request failed") - agg[level] = max(c["aggregate_tps"] for c in cells) - for c in cells: - r = c["request"] - print(f"RESULT llama.cpp q4_k_m gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") -print(f"RESULT llama.cpp q4_k_m gb10 aggregate decode: 1 stream {agg[1]:.1f} tok/s, 4 streams {agg[4]:.1f} tok/s ({agg[4] / agg[1]:.2f}x)") -# run-script.sh's float64 reference continuation of this prompt (job top-16bffb6ca094: TensorFold equals it on all 32) -prompt = "The three laws of thermodynamics, explained for a curious student:" -want = "\n\n 1. Energy cannot be created or destroyed, only transformed.\n 2. Entropy (disorder) in a closed system always increases." -got = post("/completion", {"prompt": prompt, "n_predict": 32, "temperature": 0, "cache_prompt": False})["content"] -ids = lambda s: post("/tokenize", {"content": s})["tokens"] -w, g = ids(want), ids(got) -same = next((i for i, (a, b) in enumerate(zip(w, g)) if a != b), min(len(w), len(g))) -print(f"RESULT llama.cpp q4_k_m greedy vs float64 reference: first {same} of {len(w)} tokens equal: {got!r}") -EOF From c624b5fb25e14f4718abde7115f3cbdfa5ffba6e Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:53:04 +0800 Subject: [PATCH 66/84] docs: Inkling 2 Mini job bounded by timeout 600, server ready in 3 min; 4-stream receipt names its identical prompts --- docs/recipes/inkling-2-mini-cuda/README.md | 3 ++- docs/recipes/inkling-2-mini-cuda/run-script.sh | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 94fcb82f741..18a73187fe7 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -23,7 +23,8 @@ these settings, not a benchmark. | 1 | 0.076 s / 0.036 s | 196.8 tok/s | 32.9 / 32.8 tok/s | 32.9 / 32.8 tok/s | 0 | | 4 | 0.189 s / 0.090 s | 82.3 tok/s | 29.9 / 30.2 tok/s | 118.7 / 120.1 tok/s | 0 | -The 4-stream gate takes each level's better prompt: 120.1 over 32.9 tok/s, 3.65x. +The 4-stream gate takes each level's better prompt: 120.1 over 32.9 tok/s, 3.65x. Every stream sends the same prompt, +so the four streams route to the same experts; mixed traffic may give a lower 4-stream rate. Checks in the same job: the CUDA engine matched the host reference token for token, fresh and resumed prompts gave identical logits and tokens, and two lanes in shared rounds kept their tokens; 0 of 32 greedy tokens differed from diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh index 8450321a0a3..03a0e4cc6f9 100755 --- a/docs/recipes/inkling-2-mini-cuda/run-script.sh +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -4,6 +4,8 @@ # The job has no network: the Desk put the checkpoint in the pilot folder as Inkling-2-Mini, and the toolchain # archives of ../minimax-h3-cuda/toolchain-stage.sh beside it. Logs and the 1/4-stream receipt land in /work/out/inkling2. set -eu +# TOP's GPU slot is 10 minutes: the whole job, build included, runs under timeout and exits with its status +[ -n "${INKLING2_TIMED:-}" ] || INKLING2_TIMED=1 exec timeout 600 sh "$0" "$@" pilot=/assets/drama3-pilot staged=$pilot/cuda-build-toolchain zig=zig-aarch64-linux-0.17.0 @@ -50,13 +52,13 @@ server=$! trap 'kill $server 2>/dev/null || :' EXIT python3 - <<'EOF' import time, urllib.request -for _ in range(900): +for _ in range(180): try: urllib.request.urlopen("http://127.0.0.1:8188/v1/models", timeout=5) raise SystemExit(0) except OSError: time.sleep(1) -raise SystemExit("server did not answer /v1/models in 15 min") +raise SystemExit("server did not answer /v1/models in 3 min") EOF mem "server loaded" for level in 1 4; do From 4f55babbf04cf67f8a79b48ed4a13b01550340cd Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:49:06 +0800 Subject: [PATCH 67/84] docs: Inkling 2 Mini job bounds its measurement, not the cold build, by timeout 600 --- .../recipes/inkling-2-mini-cuda/run-script.sh | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh index 03a0e4cc6f9..1765a5eeb53 100755 --- a/docs/recipes/inkling-2-mini-cuda/run-script.sh +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -4,8 +4,6 @@ # The job has no network: the Desk put the checkpoint in the pilot folder as Inkling-2-Mini, and the toolchain # archives of ../minimax-h3-cuda/toolchain-stage.sh beside it. Logs and the 1/4-stream receipt land in /work/out/inkling2. set -eu -# TOP's GPU slot is 10 minutes: the whole job, build included, runs under timeout and exits with its status -[ -n "${INKLING2_TIMED:-}" ] || INKLING2_TIMED=1 exec timeout 600 sh "$0" "$@" pilot=/assets/drama3-pilot staged=$pilot/cuda-build-toolchain zig=zig-aarch64-linux-0.17.0 @@ -20,20 +18,24 @@ if [ -z "$model" ]; then find /assets -maxdepth 5 -name config.json -exec grep -l '"inkling2' {} + >&2 || true exit 1 fi -[ -d "$staged" ] || { echo "missing $staged: run ../minimax-h3-cuda/toolchain-stage.sh" >&2; exit 1; } -(cd "$staged" && sha256sum -c --quiet) <&2; exit 1; } + (cd "$staged" && sha256sum -c --quiet) < Date: Tue, 24 Nov 2026 07:55:50 +0800 Subject: [PATCH 68/84] docs: llama.cpp baseline runs llama-server on the staged toolchain's glibc 2.40 loader, not the job image's 2.36 (GLIBC_2.38, GLIBCXX_3.4.32 missing) --- docs/recipes/inkling-2-mini-cuda/compare.sh | 3 ++- .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 5 ++--- .../inkling-2-mini-cuda/llama-cpp-build.sh | 15 +++++++++++++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/compare.sh b/docs/recipes/inkling-2-mini-cuda/compare.sh index b55848479b7..fc97d418bc4 100755 --- a/docs/recipes/inkling-2-mini-cuda/compare.sh +++ b/docs/recipes/inkling-2-mini-cuda/compare.sh @@ -14,5 +14,6 @@ start=$(date +%s) sh "$here/llama-cpp-build.sh" echo "build: $(($(date +%s) - start)) s" start=$(date +%s) -timeout 600 python3 "$here/peak-memory.py" llama-server sh "$here/llama-cpp-baseline.sh" +# llama-server runs as the toolchain's loader (llama-cpp-build.sh), so that is the program peak-memory.py watches +timeout 600 python3 "$here/peak-memory.py" ld-linux-aarch64.so.1 sh "$here/llama-cpp-baseline.sh" echo "measure: $(($(date +%s) - start)) s" diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index 7f807d8aeb2..2f9682f37a9 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -1,17 +1,16 @@ #!/bin/sh # llama.cpp CUDA baseline for run-script.sh's receipt: Unsloth's 16.6 GB UD-Q4_K_M GGUF on TOP's GB10, served by the -# llama-server llama-cpp-build.sh left in /work/llama-build. compare.sh runs both. +# llama-server llama-cpp-build.sh left in /work/llama-build, on the staged toolchain's loader. compare.sh runs both. set -eu pilot=/assets/drama3-pilot gguf=$pilot/inkling-gguf/Inkling-2-Mini-UD-Q4_K_M.gguf out=/work/out/inkling2-llama -export LD_LIBRARY_PATH=/usr/local/cuda/targets/sbsa-linux/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} rm -rf "$out" mkdir -p "$out" mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } mem "before the server" # run-script.sh's settings: 4 streams of 8,192 positions each -/work/llama-build/bin/llama-server -m "$gguf" --jinja -ngl 99 -c 32768 --parallel 4 --host 127.0.0.1 --port 8189 \ +sh /work/llama-build/llama-server.sh -m "$gguf" --jinja -ngl 99 -c 32768 --parallel 4 --host 127.0.0.1 --port 8189 \ --no-webui >"$out/server.log" 2>&1 & server=$! trap 'status=$?; kill $server 2>/dev/null || :; [ $status = 0 ] || { echo "llama-server log, last 60 lines:"; tail -n 60 "$out/server.log"; }' EXIT diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh index 9aa1b82f5a6..5c0abc3d180 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh @@ -24,5 +24,16 @@ cuda_lib=/usr/local/cuda/targets/sbsa-linux/lib -DCMAKE_EXE_LINKER_FLAGS="-Wl,-rpath-link,$cuda_lib:$cuda_lib/stubs:/usr/lib/aarch64-linux-gnu" \ -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_EXAMPLES=OFF >/dev/null /work/$cmake/bin/cmake --build /work/llama-build -j "$(nproc)" --target llama-server >/dev/null -# loads every shared library the server needs: a loader error shows here, before the measured part -LD_LIBRARY_PATH=$cuda_lib /work/llama-build/bin/llama-server --version +# The staged gcc links against its own glibc 2.40 and libstdc++, newer than the job image's (GLIBC_2.38 and +# GLIBCXX_3.4.32 missing), so the server runs on the toolchain's loader. --library-path, unlike LD_LIBRARY_PATH, reaches +# only this process and wins over the driver libraries' RUNPATH, so librt (GLIBC_PRIVATE) matches its libc; the image's +# directory comes last, for libcuda and what else only the driver ships. +rt=/work/$gcc/aarch64-none-linux-gnu/libc +loader="$rt/lib/ld-linux-aarch64.so.1 --library-path $rt/lib64:$rt/usr/lib64:/work/llama-build/bin:$cuda_lib:/usr/lib/aarch64-linux-gnu" +echo "exec $loader /work/llama-build/bin/llama-server \"\$@\"" >/work/llama-build/llama-server.sh +# a loader error, or a glibc or libstdc++ library resolved from the image, shows here, before the measured part +if $loader --list /work/llama-build/bin/llama-server | grep -E '^\s*lib(c|m|rt|dl|pthread|stdc\+\+|gcc_s|gomp)\.so' | grep -v "$rt/"; then + echo "the libraries above resolved outside the toolchain's $rt" >&2 + exit 1 +fi +sh /work/llama-build/llama-server.sh --version From d2a07760da227589e66c4463ea36e21e75f1179d Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:09:29 +0800 Subject: [PATCH 69/84] docs: Inkling 2 Mini README names the 18.2 GiB text shard and upstream's closing of #4441 --- docs/recipes/inkling-2-mini-cuda/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 18a73187fe7..b42e7ddfce9 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -6,6 +6,8 @@ GPU door. The job has no network, so the checkpoint must already sit in the pilo The server is jschmied's #4441 engine (`inkling2.native`, model type `inkling2_loop`, on his #4364 and #4365): graphs, fused input projections and one batched forward for every stream's rows in a round. #4387's checks run against it. +Upstream, jschmied closed #4441 on 23 Nov as superseded: Mini on CUDA goes through #4387's engine there (#4640, then +#4697, #4718, #4728 and #4729 for speed). This branch is local; an upstream claim must move to that stack first. The script fails on any of: `tf-cuda-test kernel-contract "inkling2 loop"` (the served message and gate kernels against FP64 references, with their planted controls), `tf-cuda-test inkling2-serving` (#4387's checks), `tf-cuda-test inkling2-mini-ref` (32 greedy tokens equal to the float64 host reference), that reference's planted control staying green, a failed stream @@ -51,6 +53,7 @@ Linux route. From #1010 (`5b1f10812`) and #2107: - Under WSL2 `/proc/meminfo` is WSL's RAM (about 30 GiB of 128 GB), not the GPU's 96 GB WDDM pool; with `WSL_DISTRO_NAME` set, admission reads the CUDA pool instead (`TENSORFOLD_UNIFIED_HOST_COUNTS` overrides it). - For Mini on native Windows, I need the Inkling CUDA kernels compiled with MSVC as nvcc's host front end (only gcc 14 - has built them so far) and one load of the 18.9 GiB single-shard checkpoint through Windows' threaded reads. + has built them so far) and one load of the 18.2 GiB text shard (`model-00001-of-00001.safetensors`) through Windows' + threaded reads. - For Mini under WSL2, I need neither: it is the Linux build with gcc 14. Only the pool reading above differs. - Either way, the GB10's exactness checks must be repeated on the N1X. No N1X run of Mini exists yet. From b65744605897da5035ba95c01312123074f4495b Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:33:01 +0800 Subject: [PATCH 70/84] docs: Inkling 2 Mini compare.sh names where TensorFold's side of the comparison comes from --- docs/recipes/inkling-2-mini-cuda/compare.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/recipes/inkling-2-mini-cuda/compare.sh b/docs/recipes/inkling-2-mini-cuda/compare.sh index fc97d418bc4..5673a61eb46 100755 --- a/docs/recipes/inkling-2-mini-cuda/compare.sh +++ b/docs/recipes/inkling-2-mini-cuda/compare.sh @@ -3,7 +3,7 @@ # swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/compare.sh # Prints the bytes of the weights each engine loads, builds llama-server, then measures it under peak-memory.py with # the measured part capped at 10 minutes. TensorFold's side is run-script.sh's own job (its float64 reference alone -# takes over 4 minutes), under the same peak-memory.py. +# takes over 4 minutes); the README sets the two side by side. set -eu here=docs/recipes/inkling-2-mini-cuda pilot=/assets/drama3-pilot From 4a5089e702ea2dbcebc7727eaa7d6de1bcfc9b6b Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:33:56 +0800 Subject: [PATCH 71/84] docs: Inkling 2 Mini job runs the reference's planted control beside it, so the measurement fits 600 s --- docs/recipes/inkling-2-mini-cuda/run-script.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/recipes/inkling-2-mini-cuda/run-script.sh b/docs/recipes/inkling-2-mini-cuda/run-script.sh index 1765a5eeb53..ce07595f5c4 100755 --- a/docs/recipes/inkling-2-mini-cuda/run-script.sh +++ b/docs/recipes/inkling-2-mini-cuda/run-script.sh @@ -44,8 +44,13 @@ mkdir -p "$out" python3 -c 'import random; r = random.Random(4387); print(" ".join(str(r.randrange(1000, 199000)) for _ in range(4200)))' >"$out/ids.txt" "$bin/tf-cuda-test" inkling2-serving "$model" "$out/ids.txt" text="The three laws of thermodynamics, explained for a curious student:" +# the float64 reference runs on one host core: its planted control runs beside it, and each must exit 0 +INKLING2_REF_PLANT=1 "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" >"$out/planted.log" 2>&1 & +planted=$! +trap 'kill $planted 2>/dev/null || :' EXIT "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" -INKLING2_REF_PLANT=1 "$bin/tf-cuda-test" inkling2-mini-ref "$model" 32 "$text" +wait $planted || { cat "$out/planted.log"; exit 1; } +cat "$out/planted.log" mem() { echo "$1: host $(awk '/^MemTotal:/ {t = $2} /^MemAvailable:/ {a = $2} END {printf "used %d MiB, available %d MiB", (t - a) / 1024, a / 1024}' /proc/meminfo); GPU $(nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader | tr '\n' ' ')"; } mem "before the server" /work/sm121/native/bin/tensorfold-native serve "$model" --backend cuda --host 127.0.0.1 --port 8188 \ From cf8985f7b057427900854c2b434e5df5ebdfbdf9 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:52:38 +0800 Subject: [PATCH 72/84] docs: Inkling 2 Mini README sets llama.cpp's UD-Q4_K_M GGUF beside TensorFold on TOP's GB10 (job top-b77911768550) --- ...nkling-2-mini-on-our-spark-size-speed-a.md | 7 ++++++ docs/recipes/inkling-2-mini-cuda/README.md | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md diff --git a/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md new file mode 100644 index 00000000000..86b4387c4f5 --- /dev/null +++ b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md @@ -0,0 +1,7 @@ +# Inkling 2 Mini against llama.cpp on TOP's GB10 + +- `docs/recipes/inkling-2-mini-cuda/compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged + sources and serves Unsloth's UD-Q4_K_M GGUF at the CUDA receipt's settings, with each engine's file bytes, + `peak-memory.py`'s server peak, and greedy and teacher-forced agreement with the float64 reference. +- The recipe README sets it beside TensorFold (job `top-b77911768550`): 39.1 against 32.9 tok/s at one stream, + 87.6 against 120.1 at four, 15.47 against 18.78 GiB of weights; both reproduce the reference's 32 greedy tokens. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index b42e7ddfce9..90266840c49 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -41,6 +41,29 @@ Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 p whole unembedding), so 273 GB/s caps one stream near 49 tok/s; 32.9 tok/s is 67% of it. #4387's own engine, removed here, gave 5.7 tok/s at one stream and 9.4 at four on the same GB10 (job `top-0759755a0515`). +## Against llama.cpp: Unsloth's UD-Q4_K_M GGUF on the same GB10 + +`compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged sources, checks the GGUF's sha256 +(`78fcedcf…34ae`) and serves it at the receipt's settings (4 slots of 8,192 positions, all layers on the GPU, +greedy, 256 tokens, 3 reps, medians). Job `top-b77911768550` at `b65744605`; TensorFold's column is the receipt above. + +| | TensorFold (bf16 safetensors) | llama.cpp (UD-Q4_K_M) | +|---|---|---| +| Weights on disk | 20,161,820,584 bytes (18.78 GiB) | 16,610,544,608 bytes (15.47 GiB) | +| Decode, 1 stream (code / chat) | 32.9 / 32.8 tok/s | 38.8 / 39.1 tok/s | +| Decode total, 4 streams (code / chat) | 118.7 / 120.1 tok/s | 85.9 / 87.6 tok/s | +| 4 streams over 1 | 3.65x | 2.24x | +| First token, 1 stream (code / chat) | 0.076 s / 0.036 s | 0.067 s / 0.130 s | +| Prompt, 4 streams (code) | 82.3 tok/s | 43.0 tok/s | +| Memory, server loaded | 20.0 GiB GPU (`nvidia-smi`) | 18.1 GiB GPU (`nvidia-smi`); peak 20.57 GiB: 18.18 GPU + 2.38 resident | +| Greedy vs the float64 reference, 32 tokens | 32 of 32 | 32 of 32 free-running; 31 of 32 teacher-forced (differs at 5) | + +llama.cpp's one-stream prompt speed is blank: `bench_concurrent.py` recorded none for it at that level. llama.cpp +decodes one stream 18% faster from 18% fewer weight bytes; at 4 streams TensorFold's total is 37% higher. +TensorFold's memory is a sample after loading, not `peak-memory.py`'s process peak. Quality: both engines reproduce +the float64 reference's 32 greedy tokens; teacher-forced on the reference's prefix, the GGUF picks another token once +(position 5), where TensorFold picks none. + ## RTX Spark (N1X): what differs and what must change I see the same chip and memory model as the GB10: sm_121 and one unified pool, so the `-Dsm=121` kernel images are From 898b8ea6c1a38487f97ce3ce30709261685ff172 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:47:26 +0800 Subject: [PATCH 73/84] docs: Inkling 2 Mini GB10 receipt from top-0b05213c9f06 at 4a5089e70: every check inside timeout 600, 32.9 tok/s at one stream, 118.8 at four --- ...188-inkling-2-mini-runs-whole-on-our-spark-g.md | 1 + docs/recipes/inkling-2-mini-cuda/README.md | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index 650c64dcd8a..55db8dce52e 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -8,6 +8,7 @@ - `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: the serving checks, the float64 reference and its planted control, then first-token time, prompt speed, decode speed, memory (`/proc/meminfo`) and the bandwidth limit at 1 and 4 streams; 4 streams must give 1.5 times one stream's total. + After the build, every check and both levels run inside `timeout 600`. The recipe's README notes what RTX Spark (native Windows and WSL2) needs. - `tf-cuda-test kernel-contract "inkling2 loop"` checks the served `loop.cu` message mix and three gate launches against FP64 references, with planted controls (an aliased block, a gate reading the wrong role plane). diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index b42e7ddfce9..9b5f4af5711 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -17,15 +17,15 @@ checkpoint's headers) over 273 GB/s. ## Receipt: TOP's GB10, one capped run -Job `top-bde5d508e589` at `fbbd43cbe`, `--context 8192`, greedy, 256 tokens, 3 reps, medians. This is one run with -these settings, not a benchmark. +Job `top-0b05213c9f06` at `4a5089e70`, `--context 8192`, greedy, 256 tokens, 3 reps, medians; the build ran first, then +every check and both levels inside `timeout 600`. This is one run with these settings, not a benchmark. | Streams | First token (code / chat) | Prompt (code) | Decode a stream (code / chat) | Total decode (code / chat) | Failed | |---|---|---|---|---|---| -| 1 | 0.076 s / 0.036 s | 196.8 tok/s | 32.9 / 32.8 tok/s | 32.9 / 32.8 tok/s | 0 | -| 4 | 0.189 s / 0.090 s | 82.3 tok/s | 29.9 / 30.2 tok/s | 118.7 / 120.1 tok/s | 0 | +| 1 | 0.075 s / 0.037 s | 199.4 tok/s | 32.9 / 32.8 tok/s | 32.9 / 32.8 tok/s | 0 | +| 4 | 0.186 s / 0.091 s | 83.7 tok/s | 29.8 / 29.8 tok/s | 117.9 / 118.8 tok/s | 0 | -The 4-stream gate takes each level's better prompt: 120.1 over 32.9 tok/s, 3.65x. Every stream sends the same prompt, +The 4-stream gate takes each level's better prompt: 118.8 over 32.9 tok/s, 3.61x. Every stream sends the same prompt, so the four streams route to the same experts; mixed traffic may give a lower 4-stream rate. Checks in the same job: the CUDA engine matched the host reference token for token, fresh and resumed prompts gave @@ -33,8 +33,8 @@ identical logits and tokens, and two lanes in shared rounds kept their tokens; 0 the float64 reference (smallest reference margin 0.11), and its planted control (no messages) differed at 6. The kernel contract passed gates 1-4 on all 5 loop kernels with both planted controls red. -Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 10.4 GiB before the server, -30.7 GiB with Mini loaded for 4 streams, and the same after both levels; the server held 20.0 GiB of GPU memory +Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 11.1 GiB before the server, +31.8 GiB with Mini loaded for 4 streams and 32.2 GiB after both levels; the server held 20.0 GiB of GPU memory (`nvidia-smi`). Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the From 941dbadae48facb4ffadc9b70915185dcfba1e8e Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:48:37 +0800 Subject: [PATCH 74/84] docs: llama.cpp baseline times the code prompt uncached at one stream, labels the free run as text, pins the b12611 source tree and gcc archive --- .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 15 +++++++++++++-- .../inkling-2-mini-cuda/llama-cpp-build.sh | 8 ++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index 2f9682f37a9..b5a9592709e 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -31,7 +31,9 @@ for level in 1 4; do mem "after $level streams" done python3 - "$out" <<'EOF' -import json, sys, urllib.request +import json, statistics, sys, time, urllib.request +sys.path.insert(0, "tools") +from bench_concurrent import PROMPTS out = sys.argv[1] def post(path, body): req = urllib.request.Request(f"http://127.0.0.1:8189{path}", json.dumps(body).encode(), {"Content-Type": "application/json"}) @@ -46,6 +48,15 @@ for level in (1, 4): r = c["request"] print(f"RESULT llama.cpp q4_k_m gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") print(f"RESULT llama.cpp q4_k_m gb10 aggregate decode: 1 stream {agg[1]:.1f} tok/s, 4 streams {agg[4]:.1f} tok/s ({agg[4] / agg[1]:.2f}x)") +# bench_concurrent.py's warm-up sends the measured prompt first, so llama.cpp's slot cache answers every 1-stream +# request from it and prompt_ttft_tps (cold requests only) stays null; this times the code prompt uncached, alone. +code = next(p["prompt"] for p in PROMPTS if p["name"] == "code") +cold = [] +for _ in range(3): + t = time.perf_counter() + n = post("/completion", {"prompt": code, "n_predict": 1, "temperature": 0, "cache_prompt": False})["timings"]["prompt_n"] + cold.append(n / (time.perf_counter() - t)) +print(f"RESULT llama.cpp q4_k_m gb10 1 stream code prompt, uncached: {n} tokens, median {statistics.median(cold):.1f} tok/s (prompt tokens over the one-token reply's time)") # run-script.sh's float64 reference continuation of this prompt (job top-16bffb6ca094: TensorFold equals it on all 32) prompt = "The three laws of thermodynamics, explained for a curious student:" want = "\n\n 1. Energy cannot be created or destroyed, only transformed.\n 2. Entropy (disorder) in a closed system always increases." @@ -53,7 +64,7 @@ got = post("/completion", {"prompt": prompt, "n_predict": 32, "temperature": 0, ids = lambda s: post("/tokenize", {"content": s})["tokens"] w, g = ids(want), ids(got) same = next((i for i, (a, b) in enumerate(zip(w, g)) if a != b), min(len(w), len(g))) -print(f"RESULT llama.cpp q4_k_m greedy vs float64 reference: first {same} of {len(w)} tokens equal: {got!r}") +print(f"RESULT llama.cpp q4_k_m greedy vs float64 reference, as text (re-tokenized): first {same} of {len(w)} tokens equal: {got!r}") # teacher-forced, as tf-cuda-test inkling2-mini-ref scores TensorFold: after the reference's own prefix, is llama.cpp's # next pick the reference's token? A free run says nothing past its first difference. start = post("/tokenize", {"content": prompt, "add_special": True})["tokens"] diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh index 5c0abc3d180..8e26397946d 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-build.sh @@ -12,7 +12,15 @@ cmake=cmake-3.31.6-linux-aarch64 sha256sum -c --quiet <&2 + exit 1 +} tar -C /work -xJf "$staged/$gcc.tar.xz" tar -C /work -xzf "$llama/$cmake.tar.gz" cc=/work/$gcc/bin/aarch64-none-linux-gnu From 5bd99a73774c8ea36f571a0dc0ba1bfcab7417c0 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:37:56 +0800 Subject: [PATCH 75/84] docs: record uncached prompt receipt and stop baseline on timeout --- ...nkling-2-mini-on-our-spark-size-speed-a.md | 6 ++-- docs/recipes/inkling-2-mini-cuda/README.md | 24 +++++++++------ .../inkling-2-mini-cuda/llama-cpp-baseline.sh | 29 +++++++++++-------- .../inkling-2-mini-cuda/peak-memory.py | 13 +++++++-- 4 files changed, 47 insertions(+), 25 deletions(-) diff --git a/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md index 86b4387c4f5..e00b1efa9c6 100644 --- a/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md +++ b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md @@ -3,5 +3,7 @@ - `docs/recipes/inkling-2-mini-cuda/compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged sources and serves Unsloth's UD-Q4_K_M GGUF at the CUDA receipt's settings, with each engine's file bytes, `peak-memory.py`'s server peak, and greedy and teacher-forced agreement with the float64 reference. -- The recipe README sets it beside TensorFold (job `top-b77911768550`): 39.1 against 32.9 tok/s at one stream, - 87.6 against 120.1 at four, 15.47 against 18.78 GiB of weights; both reproduce the reference's 32 greedy tokens. +- The recipe README sets it beside TensorFold (jobs `top-b77911768550`, `top-c0075bd36227`): 39.1 against 32.9 tok/s + at one stream, 87.6 against 120.1 at four, 15.47 against 18.78 GiB of weights, and 106.4 against 196.8 tok/s + uncached at one-stream prompt processing. llama.cpp's free-running text matches the reference continuation when + re-tokenized, but its teacher-forced picks match 31 of 32 reference tokens; TensorFold matches 32 of 32. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 90266840c49..db7ea771866 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -44,8 +44,10 @@ here, gave 5.7 tok/s at one stream and 9.4 at four on the same GB10 (job `top-07 ## Against llama.cpp: Unsloth's UD-Q4_K_M GGUF on the same GB10 `compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged sources, checks the GGUF's sha256 -(`78fcedcf…34ae`) and serves it at the receipt's settings (4 slots of 8,192 positions, all layers on the GPU, -greedy, 256 tokens, 3 reps, medians). Job `top-b77911768550` at `b65744605`; TensorFold's column is the receipt above. +(`78fcedcf…34ae`), the gcc archive and the b12611 source tree, and serves it at the receipt's settings (4 slots of +8,192 positions, all layers on the GPU, greedy, 256 tokens, 3 reps, medians). Job `top-b77911768550` at `b65744605`; +the uncached one-stream prompt and source pin were checked by job `top-c0075bd36227` at `941dbada`. TensorFold's column +is the receipt above. | | TensorFold (bf16 safetensors) | llama.cpp (UD-Q4_K_M) | |---|---|---| @@ -54,15 +56,19 @@ greedy, 256 tokens, 3 reps, medians). Job `top-b77911768550` at `b65744605`; Ten | Decode total, 4 streams (code / chat) | 118.7 / 120.1 tok/s | 85.9 / 87.6 tok/s | | 4 streams over 1 | 3.65x | 2.24x | | First token, 1 stream (code / chat) | 0.076 s / 0.036 s | 0.067 s / 0.130 s | +| Prompt, 1 stream (code, uncached) | 196.8 tok/s | 106.4 tok/s (15 tokens / one-token response time; median of 3) | | Prompt, 4 streams (code) | 82.3 tok/s | 43.0 tok/s | | Memory, server loaded | 20.0 GiB GPU (`nvidia-smi`) | 18.1 GiB GPU (`nvidia-smi`); peak 20.57 GiB: 18.18 GPU + 2.38 resident | -| Greedy vs the float64 reference, 32 tokens | 32 of 32 | 32 of 32 free-running; 31 of 32 teacher-forced (differs at 5) | - -llama.cpp's one-stream prompt speed is blank: `bench_concurrent.py` recorded none for it at that level. llama.cpp -decodes one stream 18% faster from 18% fewer weight bytes; at 4 streams TensorFold's total is 37% higher. -TensorFold's memory is a sample after loading, not `peak-memory.py`'s process peak. Quality: both engines reproduce -the float64 reference's 32 greedy tokens; teacher-forced on the reference's prefix, the GGUF picks another token once -(position 5), where TensorFold picks none. +| Continuation text / teacher-forced tokens vs float64 reference | 32 of 32 token picks | Same free-running text when re-tokenized / 31 of 32 token picks (differs at 5) | + +`bench_concurrent.py` warms up with the same code prompt before measuring: llama.cpp's slot cache answers every +one-stream request, so `prompt_ttft_tps` is null (only cold requests qualify). The separate uncached `/completion` +measurement above supplies the missing one-stream comparison; it times the full one-token response rather than first +streamed token, so its client latency includes that token's transfer. llama.cpp decodes one stream 18% faster from 18% +fewer weight bytes; at 4 streams TensorFold's total is 37% higher. TensorFold's memory is a sample after loading, not +`peak-memory.py`'s process peak. Quality: llama.cpp's free-running text matches the 32-token reference continuation +when re-tokenized, but its teacher-forced token picks agree at 31 of 32 positions (different at position 5); +TensorFold's token picks agree at all 32 positions. ## RTX Spark (N1X): what differs and what must change diff --git a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh index b5a9592709e..cc4406a8da3 100755 --- a/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh +++ b/docs/recipes/inkling-2-mini-cuda/llama-cpp-baseline.sh @@ -25,15 +25,29 @@ done mem "server loaded" # the receipt names what the server did with -c and -ngl grep -m 2 -E 'n_ctx_slot|offloaded' "$out/server.log" || : +# The bench warm-up fills llama.cpp's slot cache; measure the code prompt cold before it. +python3 - <<'EOF' +import json, statistics, sys, time, urllib.request +sys.path.insert(0, "tools") +from bench_concurrent import PROMPTS +prompt = next(p["prompt"] for p in PROMPTS if p["name"] == "code") +rates = [] +for _ in range(3): + body = json.dumps({"prompt": prompt, "n_predict": 1, "temperature": 0, "cache_prompt": False}).encode() + request = urllib.request.Request("http://127.0.0.1:8189/completion", body, {"Content-Type": "application/json"}) + start = time.perf_counter() + with urllib.request.urlopen(request, timeout=300) as response: + tokens = json.load(response)["timings"]["prompt_n"] + rates.append(tokens / (time.perf_counter() - start)) +print(f"RESULT llama.cpp q4_k_m gb10 1 stream code prompt, uncached: {tokens} tokens, median {statistics.median(rates):.1f} tok/s (prompt tokens over the one-token reply's time)") +EOF for level in 1 4; do python3 tools/bench_concurrent.py http://127.0.0.1:8189 inkling-2-mini --levels "$level" --tokens 256 --reps 3 \ --temperatures 0 --label "llama-$level" --output "$out/streams-$level.json" mem "after $level streams" done python3 - "$out" <<'EOF' -import json, statistics, sys, time, urllib.request -sys.path.insert(0, "tools") -from bench_concurrent import PROMPTS +import json, sys, urllib.request out = sys.argv[1] def post(path, body): req = urllib.request.Request(f"http://127.0.0.1:8189{path}", json.dumps(body).encode(), {"Content-Type": "application/json"}) @@ -48,15 +62,6 @@ for level in (1, 4): r = c["request"] print(f"RESULT llama.cpp q4_k_m gb10 {level} stream(s) {c['prompt']}: first token {r['ttft_s']} s, prompt {r['prompt_ttft_tps']} tok/s, decode {c['per_stream_tps']} tok/s a stream, {c['aggregate_tps']} total") print(f"RESULT llama.cpp q4_k_m gb10 aggregate decode: 1 stream {agg[1]:.1f} tok/s, 4 streams {agg[4]:.1f} tok/s ({agg[4] / agg[1]:.2f}x)") -# bench_concurrent.py's warm-up sends the measured prompt first, so llama.cpp's slot cache answers every 1-stream -# request from it and prompt_ttft_tps (cold requests only) stays null; this times the code prompt uncached, alone. -code = next(p["prompt"] for p in PROMPTS if p["name"] == "code") -cold = [] -for _ in range(3): - t = time.perf_counter() - n = post("/completion", {"prompt": code, "n_predict": 1, "temperature": 0, "cache_prompt": False})["timings"]["prompt_n"] - cold.append(n / (time.perf_counter() - t)) -print(f"RESULT llama.cpp q4_k_m gb10 1 stream code prompt, uncached: {n} tokens, median {statistics.median(cold):.1f} tok/s (prompt tokens over the one-token reply's time)") # run-script.sh's float64 reference continuation of this prompt (job top-16bffb6ca094: TensorFold equals it on all 32) prompt = "The three laws of thermodynamics, explained for a curious student:" want = "\n\n 1. Energy cannot be created or destroyed, only transformed.\n 2. Entropy (disorder) in a closed system always increases." diff --git a/docs/recipes/inkling-2-mini-cuda/peak-memory.py b/docs/recipes/inkling-2-mini-cuda/peak-memory.py index dafdaf9f9b9..3b6796a8a42 100755 --- a/docs/recipes/inkling-2-mini-cuda/peak-memory.py +++ b/docs/recipes/inkling-2-mini-cuda/peak-memory.py @@ -7,7 +7,7 @@ (printed beside the peak) counts them. The fall in MemAvailable since the last sample before the server counts every byte once, with whatever else the job held meanwhile. """ -import glob, os, subprocess, sys, time +import glob, os, signal, subprocess, sys, time name, command = sys.argv[1], sys.argv[2:] @@ -35,7 +35,16 @@ def gpu_kib() -> int: return 1024 * sum(int(mib) for mib in rows) -job = subprocess.Popen(command) +job = subprocess.Popen(command, start_new_session=True) + + +def stop(_signum, _frame): + os.killpg(job.pid, signal.SIGTERM) + job.wait() + sys.exit(124) + + +signal.signal(signal.SIGTERM, stop) before = kib("/proc/meminfo")["MemAvailable"] peak, hwm, fall, seen = (0, 0, 0), 0, 0, False while job.poll() is None: From bac1a2691627daa82418ce617044b330a0bf4aea Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:49:58 +0800 Subject: [PATCH 76/84] docs: Inkling 2 Mini comparison takes 188's merged head receipt, marks llama.cpp's cached and cold-only cells, pairs like figures --- ...nkling-2-mini-on-our-spark-size-speed-a.md | 9 ++++---- docs/recipes/inkling-2-mini-cuda/README.md | 23 +++++++++++-------- docs/recipes/inkling-2-mini-cuda/compare.sh | 7 +++--- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md index e00b1efa9c6..4d9d93b752a 100644 --- a/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md +++ b/changelog.d/232-inkling-2-mini-on-our-spark-size-speed-a.md @@ -3,7 +3,8 @@ - `docs/recipes/inkling-2-mini-cuda/compare.sh` builds llama.cpp b12611's CUDA `llama-server` from the Desk's staged sources and serves Unsloth's UD-Q4_K_M GGUF at the CUDA receipt's settings, with each engine's file bytes, `peak-memory.py`'s server peak, and greedy and teacher-forced agreement with the float64 reference. -- The recipe README sets it beside TensorFold (jobs `top-b77911768550`, `top-c0075bd36227`): 39.1 against 32.9 tok/s - at one stream, 87.6 against 120.1 at four, 15.47 against 18.78 GiB of weights, and 106.4 against 196.8 tok/s - uncached at one-stream prompt processing. llama.cpp's free-running text matches the reference continuation when - re-tokenized, but its teacher-forced picks match 31 of 32 reference tokens; TensorFold matches 32 of 32. +- The recipe README sets it beside TensorFold's receipt from 188 (jobs `top-b77911768550`, `top-c0075bd36227` + against `top-0b05213c9f06`): 38.8 against 32.9 tok/s at one stream, 85.9 against 117.9 at four, 15.47 against + 18.78 GiB of weights, and 106.4 against 199.4 tok/s uncached at one-stream prompt processing. llama.cpp's + free-running text matches the reference continuation when re-tokenized, but its teacher-forced picks match 31 of 32 + reference tokens; TensorFold matches 32 of 32. diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 49a41177b61..3ce3cb1dbfe 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -51,21 +51,24 @@ is the receipt above. | | TensorFold (bf16 safetensors) | llama.cpp (UD-Q4_K_M) | |---|---|---| -| Weights on disk | 20,161,820,584 bytes (18.78 GiB) | 16,610,544,608 bytes (15.47 GiB) | +| Weights on disk | 20,161,820,584 bytes (18.78 GiB, with the 635,801,416-byte draft head `mtp.safetensors`) | 16,610,544,608 bytes (15.47 GiB) | | Decode, 1 stream (code / chat) | 32.9 / 32.8 tok/s | 38.8 / 39.1 tok/s | -| Decode total, 4 streams (code / chat) | 118.7 / 120.1 tok/s | 85.9 / 87.6 tok/s | -| 4 streams over 1 | 3.65x | 2.24x | -| First token, 1 stream (code / chat) | 0.076 s / 0.036 s | 0.067 s / 0.130 s | -| Prompt, 1 stream (code, uncached) | 196.8 tok/s | 106.4 tok/s (15 tokens / one-token response time; median of 3) | -| Prompt, 4 streams (code) | 82.3 tok/s | 43.0 tok/s | +| Decode total, 4 streams (code / chat) | 117.9 / 118.8 tok/s | 85.9 / 87.6 tok/s | +| 4 streams over 1 | 3.61x | 2.24x | +| First token, 1 stream (code / chat) | 0.075 s / 0.037 s | 0.067 s (slot cache hit) / 0.130 s | +| Prompt, 1 stream (code, uncached) | 199.4 tok/s | 106.4 tok/s (15 tokens / one-token response time; median of 3) | +| Prompt, 4 streams (code) | 83.7 tok/s | 43.0 tok/s (cold requests only) | | Memory, server loaded | 20.0 GiB GPU (`nvidia-smi`) | 18.1 GiB GPU (`nvidia-smi`); peak 20.57 GiB: 18.18 GPU + 2.38 resident | | Continuation text / teacher-forced tokens vs float64 reference | 32 of 32 token picks | Same free-running text when re-tokenized / 31 of 32 token picks (differs at 5) | `bench_concurrent.py` warms up with the same code prompt before measuring: llama.cpp's slot cache answers every -one-stream request, so `prompt_ttft_tps` is null (only cold requests qualify). The separate uncached `/completion` -measurement above supplies the missing one-stream comparison; it times the full one-token response rather than first -streamed token, so its client latency includes that token's transfer. llama.cpp decodes one stream 18% faster from 18% -fewer weight bytes; at 4 streams TensorFold's total is 37% higher. TensorFold's memory is a sample after loading, not +one-stream request, so its code first token is a cache hit and `prompt_ttft_tps` is null (only cold requests +qualify). The separate uncached `/completion` measurement above supplies the missing one-stream comparison; it times +the full one-token response (0.14 s) rather than first streamed token, so its client latency includes that token's +transfer. At 4 streams the prompt figure is likewise the median of cold requests only; later rounds likely reuse the +slots the first filled, so it is about one round's requests rather than a median of 3. llama.cpp decodes one stream +18% faster from 18% fewer weight bytes on disk (15% fewer without the draft head, which `serve` does not load); at 4 +streams TensorFold's total is 37% higher. TensorFold's memory is a sample after loading, not `peak-memory.py`'s process peak. Quality: llama.cpp's free-running text matches the 32-token reference continuation when re-tokenized, but its teacher-forced token picks agree at 31 of 32 positions (different at position 5); TensorFold's token picks agree at all 32 positions. diff --git a/docs/recipes/inkling-2-mini-cuda/compare.sh b/docs/recipes/inkling-2-mini-cuda/compare.sh index 5673a61eb46..0ddcf933869 100755 --- a/docs/recipes/inkling-2-mini-cuda/compare.sh +++ b/docs/recipes/inkling-2-mini-cuda/compare.sh @@ -1,9 +1,10 @@ #!/bin/sh # Inkling 2 Mini on TOP's GB10, llama.cpp's side of the README's comparison: # swarm gpu-run plotarmordev/TensorFold SHA docs/recipes/inkling-2-mini-cuda/compare.sh -# Prints the bytes of the weights each engine loads, builds llama-server, then measures it under peak-memory.py with -# the measured part capped at 10 minutes. TensorFold's side is run-script.sh's own job (its float64 reference alone -# takes over 4 minutes); the README sets the two side by side. +# Prints each engine's weight files on disk (TensorFold's include the draft head mtp.safetensors, which serve does not +# load), builds llama-server, then measures it under peak-memory.py with the measured part capped at 10 minutes. +# TensorFold's side is run-script.sh's own job (its float64 reference alone takes over 4 minutes); the README sets the +# two side by side. set -eu here=docs/recipes/inkling-2-mini-cuda pilot=/assets/drama3-pilot From 0ecea666455c27768bdff736d019de2dc94aff30 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:18 +0800 Subject: [PATCH 77/84] inkling2 metal: keep main's padded-vocabulary mask stride and its refusal through the merge Restores Seth For Privacy's 7a5c0da9f (via b7faf6dab), which the merge of origin/main dropped. --- zig/src/families/inkling2/metal/backend.zig | 26 +++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index 417523dfb80..268b02d7da9 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -301,7 +301,7 @@ pub const Metal = struct { fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { const self = cast(ptr); - const words = (self.vocab() + 31) / 32; + const words = maskWords(self.model.config.text.vocab); if (windows.len != out.len or windows.len > st.batch_rows) return error.InvalidInklingWindows; var segments: [st.batch_rows]fwd.Segment = undefined; var ids: [st.batch_rows]u32 = undefined; @@ -311,6 +311,7 @@ pub const Metal = struct { for (windows, out, 0..) |w, o, i| { const rows = w.rows(); if (rows == 0 or rows > st.window_rows or total + rows > st.batch_rows or w.parents != null or w.held != 0 or o.sampled.len != rows or o.drafts.len != rows - 1 or w.positions.len != rows) return error.UnsupportedInklingWindow; + if (w.masks.len != 0 and w.masks.len != rows * words) return error.InvalidInklingMasks; const cache = try self.cacheOf(w.stream); if (cache.pending != null) return error.InklingWindowAlreadyOpen; for (w.positions, 0..) |p, r| if (p != cache.len + r + 1) return error.InvalidInklingPosition; @@ -333,7 +334,7 @@ pub const Metal = struct { @memcpy(o.drafts, w.tokens); for (0..seg.rows) |r| { const l = all[(base + r) * self.vocab() ..][0..self.vocab()]; - const mask = if (w.masks.len >= (r + 1) * words) w.masks[r * words ..][0..words] else &.{}; + const mask = maskRow(w.masks, words, r); o.sampled[r] = try self.draw(l, w.stream.sampling, w.positions[r], mask); if (o.rows.len == seg.rows) o.rows[r] = logprobRow(l, o.sampled[r], w.stream.logprobs orelse 0); } @@ -400,6 +401,27 @@ pub const Metal = struct { } }; +/// A grammar mask's words a row: a bit a token of the tokenizer's vocabulary, padding included. +fn maskWords(vocab: u32) usize { + return (@as(usize, vocab) + 31) / 32; +} + +/// Row `r` of a window's masks, or none where the window has none. +fn maskRow(masks: []const u32, words: usize, r: usize) []const u32 { + return if (masks.len == 0) &.{} else masks[r * words ..][0..words]; +} + +test "a window's masks step by the padded vocabulary's words" { + const words = maskWords(201024); + try std.testing.expectEqual(@as(usize, 6282), words); + var masks: [3 * 6282]u32 = @splat(0); + masks[2 * 6282] = 1; + try std.testing.expectEqual(@as(usize, 0), maskRow(&.{}, words, 2).len); + try std.testing.expectEqual(@as(u32, 0), maskRow(&masks, words, 1)[0]); + try std.testing.expect(lanes.grammar.allows(maskRow(&masks, words, 2), 0)); + try std.testing.expect(!lanes.grammar.allows(maskRow(&masks, words, 1), 0)); +} + fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } From 90c2b6fab3c4d92451caf7c77e0a0c9624e0dd54 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:18 +0800 Subject: [PATCH 78/84] inkling2 metal: keep main's per-head snapshot rows and their cross-capacity test through the merge Restores Seth For Privacy's 7a0732118 (via 14bbdf429 and f12f0fe2a), which the merge of origin/main dropped. --- .../families/inkling2/metal/runtime_test.zig | 50 +++++++++++++++++++ zig/src/families/inkling2/metal/snapshot.zig | 15 +++--- 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig index 5085c52eda9..5b5499dcb1d 100644 --- a/zig/src/families/inkling2/metal/runtime_test.zig +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -1,5 +1,7 @@ //! Host-only schedule, cache-layout, accepted-history and compact-snapshot checks. const std = @import("std"); +const mtl = @import("metal"); +const ap = @import("attention_plan.zig"); const cfg = @import("../config.zig"); const layer_plan = @import("../plan.zig"); const state = @import("state.zig"); @@ -174,3 +176,51 @@ test "prepare_features requires exactly Mini's checkpoint tap list" { c.mtp = null; try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); } + +/// Every head's first `rows` rows of every slot's keys and values, then the convolution states, to or from `flat`. +fn moveLive(queue: mtl.Queue, cache: *const state.Cache, flat: mtl.Buffer, rows: usize, into: bool) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + const n = rows * ap.head_dim * 2; + var at: usize = 0; + for (0..state.visit_slots) |slot| for ([_]usize{ cache.key_at[slot], cache.value_at[slot] }) |base| for (0..state.kv_width / ap.head_dim) |h| { + const off = base + h * cache.ring(slot) * ap.head_dim * 2; + if (into) e.copy(flat, at, cache.kv, off, n) else e.copy(cache.kv, off, flat, at, n); + at += n; + }; + if (into) e.copy(flat, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, flat, at, state.conv_bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; +} + +test "A snapshot restores each head's live rows into a cache of another capacity" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const queue = try device.queue(); + defer queue.deinit(); + const p = schedule(); + const rows = 100; + var from = try state.Cache.init(device, 200, &p); + defer from.deinit(); + var to = try state.Cache.init(device, 500, &p); + defer to.deinit(); + try std.testing.expect(from.ring(5) != to.ring(5) and from.globals[5] and rows < from.ring(0)); + const size = state.visit_slots * 2 * state.kv_width * 2 * rows + state.conv_bytes; + const want = try device.buffer(size, mtl.ResourceOptions.shared); + defer want.deinit(); + const got = try device.buffer(size, mtl.ResourceOptions.shared); + defer got.deinit(); + var prng = std.Random.DefaultPrng.init(7); + prng.random().bytes(want.slice(u8, size)); + try moveLive(queue, &from, want, rows, true); + from.len = rows; + var snap = try snapshot.save(device, queue, &from); + defer snap.deinit(); + try snapshot.restore(&to, queue, &snap); + try std.testing.expectEqual(@as(usize, rows), to.len); + try moveLive(queue, &to, got, rows, false); + try std.testing.expect(std.mem.eql(u8, want.slice(u8, size), got.slice(u8, size))); +} diff --git a/zig/src/families/inkling2/metal/snapshot.zig b/zig/src/families/inkling2/metal/snapshot.zig index 4004e4dce88..14bbdf42977 100644 --- a/zig/src/families/inkling2/metal/snapshot.zig +++ b/zig/src/families/inkling2/metal/snapshot.zig @@ -2,6 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const state = @import("state.zig"); +const ap = @import("attention_plan.zig"); /// Eight global layers retain [0,at); forty sliding layers retain ring prefixes, with independent K/V pieces per visit. pub fn bytes(at: usize) u64 { @@ -45,17 +46,13 @@ fn encode(queue: mtl.Queue, cache: *const state.Cache, snap_buf: mtl.Buffer, sna const len = if (snap) |image| image.at else cache.len; for (0..state.visit_slots) |slot| { const live = if (cache.globals[slot]) len else @min(len, cache.ring(slot)); - const n = live * state.kv_width * 2; - if (n != 0) if (snap) |image| { - e.copy(image.buf, at, cache.kv, cache.key_at[slot], n); + // A slot holds its heads one after another, each the ring's rows: a head's live rows are its first `live`. + const n = live * ap.head_dim * 2; + const head = cache.ring(slot) * ap.head_dim * 2; + if (n != 0) for ([_]usize{ cache.key_at[slot], cache.value_at[slot] }) |base| for (0..state.kv_width / ap.head_dim) |h| { + if (snap) |image| e.copy(image.buf, at, cache.kv, base + h * head, n) else e.copy(cache.kv, base + h * head, snap_buf, at, n); at += n; - e.copy(image.buf, at, cache.kv, cache.value_at[slot], n); - } else { - e.copy(cache.kv, cache.key_at[slot], snap_buf, at, n); - at += n; - e.copy(cache.kv, cache.value_at[slot], snap_buf, at, n); }; - at += n; } if (snap) |image| e.copy(image.buf, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, snap_buf, at, state.conv_bytes); e.end(); From ee3d93fb5c7144558cb2c9e3d9f0ab7fceedd885 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:18 +0800 Subject: [PATCH 79/84] inkling2 metal: keep main's norm binding and relative-row stride through the merge Restores Seth For Privacy's 1ba8d16a8 and 369711412, which the merge of origin/main dropped. --- zig/src/families/inkling2/metal/forward.zig | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index 7dd3e0c49ae..5fe3fb18778 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -82,8 +82,10 @@ fn widen(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usiz fn norm(m: *const Model, e: mtl.ComputeEncoder, input: Ref, weight: ck.Tensor, out: Ref, rows: usize) void { e.setPipeline(m.norm); - inline for (.{ input, r(weight), out }, 0..) |v, i| e.setBuffer(v.buf, v.off, i); - e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 3); + e.setBuffer(input.buf, input.off, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 2); + e.setBuffer(out.buf, out.off, 3); e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } @@ -188,8 +190,8 @@ fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: const kv = attention.Cache{ .k = a(cache.keys(v.of(.conv).?)), .v = a(cache.values(v.of(.conv).?)) }; try convInputForAttention(m, e, s, cache, v, base, rows, true); try convInputForAttention(m, e, s, cache, v, base, rows, false); - attention.prep(&m.attention, e, rr, layer, prep, meta, .{ 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)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * 24 * ap.extent * 2)), kv); - attention.relTable(&m.attention, e, rr, a(at(s.rel_prep, base * 24 * ap.extent * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.rel_tab, base * 24 * ap.extent * 2))); + attention.prep(&m.attention, e, rr, layer, prep, meta, .{ 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)) }, .{ a(r(m.weights.layers[v.layer].attn.q_scale)), a(r(m.weights.layers[v.layer].attn.rel_scale)) }, a(at(s.q_prep, base * state.query_width * 2)), a(at(s.rel_prep, base * state.rel_width * 2)), kv); + attention.relTable(&m.attention, e, rr, a(at(s.rel_prep, base * state.rel_width * 2)), a(r(m.weights.layers[v.layer].attn.rel_projection)), a(at(s.rel_tab, base * 24 * ap.extent * 2))); try attention.attend(&m.attention, e, rr, layer, state.max_attention_stride, 0, meta, a(at(s.q_prep, base * state.query_width * 2)), kv, a(at(s.rel_tab, base * 24 * ap.extent * 2)), a(at(s.part_o, base * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, base * 24 * state.max_attention_stride * 8)), a(at(s.sink, base * 24 * 2)), a(at(s.gate, base * state.query_width * 2)), a(at(s.att, base * state.query_width * 2))); base += rows; } From ac50aab5de5188e82ce662521c2b618faa1fdb98 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:18 +0800 Subject: [PATCH 80/84] inkling2 metal: keep main's real-checkpoint serving test order and fresh turn through the merge Restores Seth For Privacy's 25dc1aca8, which the merge of origin/main dropped. --- .../families/inkling2/metal/serving_test.zig | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig index 5b9328faed9..eb761e0fecd 100644 --- a/zig/src/families/inkling2/metal/serving_test.zig +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -11,7 +11,9 @@ const dspark = @import("dspark.zig"); const gpa = std.testing.allocator; const io = std.testing.io; -const context = 256; +/// A history the prompt cache can end a state on: the family's chunk grid. +const history = st.prompt_rows; +const context = 4 * history; const made = 24; const taps = [_]u32{ 5, 23, 41, 48 }; @@ -235,7 +237,7 @@ fn transactions(dir: []const u8, drafter_dir: []const u8, ids: []const u32, want const path = [_]u32{ 0, 1, 2, 3, 4, 5, 6 }; var partial_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; try b.verify(&partial, &partial_out); - try std.testing.expectEqualSlices(u32, want.tokens[9..17], &sampled); + try std.testing.expectEqualSlices(u32, want.tokens[9..16], sampled[0..7]); try b.keep(&partial, &.{&path}); try std.testing.expectEqualSlices(u8, &want.partial_tap, &(try featureRow(target_b, &s, ids.len + 14))); try b.draft(&.{.{ .stream = &s, .follow = want.tokens[9..16], .rows = &path, .start = ids.len + 8, .position = ids.len + 16, .depth = 7 }}); @@ -246,10 +248,10 @@ fn transactions(dir: []const u8, drafter_dir: []const u8, ids: []const u32, want test "Mini Metal serving matches the host reference token for token" { const dir = try checkpoint(); - const ids = prompt(64, 1); - var turn: [80]u32 = undefined; - @memcpy(turn[0..64], &ids); - @memcpy(turn[64..], &prompt(16, 2)); + const ids = prompt(history, 1); + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], &ids); + @memcpy(turn[history..], &prompt(16, 2)); const refs = try withReference(dir, &ids, &turn); var tap_nonzero = false; for (refs.first.tap) |byte| tap_nonzero = tap_nonzero or byte != 0; @@ -263,7 +265,11 @@ test "Mini Metal serving matches the host reference token for token" { var first = try serve(opened_once, 1, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); defer first.deinit(); try expectTokens(&refs.first, &first); - var restored = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + var fresh = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer fresh.deinit(); + try std.testing.expectEqual(@as(?u32, 0), fresh.cached); + try expectTokens(&refs.second.?, &fresh); + var restored = try serve(opened_once, 3, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); defer restored.deinit(); try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); try expectTokens(&refs.second.?, &restored); @@ -272,10 +278,10 @@ test "Mini Metal serving matches the host reference token for token" { test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back exactly" { const dir = try checkpoint(); const drafter = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; - const ids = prompt(64, 3); - var turn: [80]u32 = undefined; - @memcpy(turn[0..64], &ids); - @memcpy(turn[64..], &prompt(16, 2)); + const ids = prompt(history, 3); + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], &ids); + @memcpy(turn[history..], &prompt(16, 2)); const refs = try withReference(dir, &ids, &turn); try transactions(dir, drafter, &ids, &refs.first); @@ -290,7 +296,11 @@ test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back e try expectTokens(&refs.first, &drafted); try std.testing.expect(drafted.drafted > 0); try std.testing.expect(drafted.accepted > 0); - var restored = try serve(opened_once, 12, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + var fresh = try serve(opened_once, 12, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer fresh.deinit(); + try std.testing.expectEqual(@as(?u32, 0), fresh.cached); + try expectTokens(&refs.second.?, &fresh); + var restored = try serve(opened_once, 13, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); defer restored.deinit(); try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); try expectTokens(&refs.second.?, &restored); From e9589596149fbd5b204b10c23750df6dba3b8f76 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:19 +0800 Subject: [PATCH 81/84] inkling2 cuda: drop #4387's loop engine again, which the merge of origin/main brought back unreachable #4441's engine serves inkling2_loop here (as 9f542e6fa decided); the merge re-added cuda_native, loop_* and the loop_math image and contract tests without wiring them. --- THIRD_PARTY_NOTICES.md | 4 +- zig/build/cuda_kernels.zig | 1 - zig/kernels/cuda/inkling2/loop_math.cu | 285 --------- .../contract/inkling2_experts_records.zig | 5 - zig/src/cuda/kernels.zig | 1 - zig/src/families/inkling2/cuda_native.zig | 220 ------- zig/src/families/inkling2/loop_backend.zig | 346 ---------- zig/src/families/inkling2/loop_engine.zig | 591 ------------------ zig/src/families/inkling2/loop_math_cuda.zig | 158 ----- zig/src/families/inkling2/loop_model.zig | 464 -------------- zig/src/families/inkling2/loop_model_test.zig | 214 ------- zig/src/families/inkling2/loop_weights.zig | 228 ------- .../cuda/contract_inkling2_loop_math.zig | 479 -------------- .../contract_inkling2_loop_math_extra.zig | 426 ------------- zig/tests/cuda/contract_limits.zig | 2 +- 15 files changed, 3 insertions(+), 3421 deletions(-) delete mode 100644 zig/kernels/cuda/inkling2/loop_math.cu delete mode 100644 zig/src/families/inkling2/cuda_native.zig delete mode 100644 zig/src/families/inkling2/loop_backend.zig delete mode 100644 zig/src/families/inkling2/loop_engine.zig delete mode 100644 zig/src/families/inkling2/loop_math_cuda.zig delete mode 100644 zig/src/families/inkling2/loop_model.zig delete mode 100644 zig/src/families/inkling2/loop_model_test.zig delete mode 100644 zig/src/families/inkling2/loop_weights.zig delete mode 100644 zig/tests/cuda/contract_inkling2_loop_math.zig delete mode 100644 zig/tests/cuda/contract_inkling2_loop_math_extra.zig diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e78c64b2b7e..589ecc68454 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -579,8 +579,8 @@ extracted headers, with the same revision annotation. No revision was derived fr `release_chat_template.jinja` and `release_tokenizer_config.json` in the same folder are byte-identical copies of that revision's `chat_template.jinja` and `tokenizer_config.json`, under the same license. -The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, -`loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and +The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, the CUDA and Metal loop kernels +and the stored-expert implementations in `modelopt.zig` and `zig/kernels/cuda/inkling2/modelopt.cu` are independent TensorFold implementations of the supplied math-only Mini specification. Its primary reference is huggingface/transformers PR #51050 at head `6173a2f6`: the Mini configuration and forward pass in `models/inkling2_loop/modular_inkling2_loop.py` and `modeling_inkling2_loop.py`, with the temporary diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 76b139c41a1..6b48b7e02c4 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -172,7 +172,6 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention .{ .name = "inkling2_loop", .src = "inkling2/loop", .flags = glue }, // Inkling 2 Mini: loop messages, gates - .{ .name = "inkling2_loop_math", .src = "inkling2/loop_math", .flags = &.{"-O3"} }, // Mini residuals, cross-pass messages, gates and split QKV .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family .{ .name = "exl3_linear", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/linear.cu's device code, tensorfold_exl3_linear_v5 .{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu deleted file mode 100644 index 824ec095042..00000000000 --- a/zig/kernels/cuda/inkling2/loop_math.cu +++ /dev/null @@ -1,285 +0,0 @@ -// Inkling 2 Mini: raw block residuals, two-bank messages, rank-64 gates and three-input QKV projection. -#include -#include - -namespace ink2l { - -constexpr int kRank = 64; -constexpr int kMaxBlocks = 8; -constexpr int kMaxQueries = 3; - -__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } -__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } -__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } - -__device__ __forceinline__ float warpSum(float v) { - for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); - return v; -} - -// Every call has the same reduction tree: lanes' strided chains, each warp's butterfly, then warp 0 over partials. -template -__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { - const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; - for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); - __syncthreads(); - if (lane == 0) - for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; - __syncthreads(); - for (int i = 0; i < N; ++i) { - const float t = lane < nw ? sh[i * 32 + lane] : 0.0f; - v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); - } -} - -// A14(a): Mini's queried residual and message dot products scale after the dot, by binary32(1 / 48). -__device__ __forceinline__ float queryScale(int c) { - return c == 2304 ? 1.0f / 48.0f : rsqrtf(static_cast(c)); -} - -__device__ __forceinline__ void softmax2(float l0, float l1, float* w) { - const float m = fmaxf(l0, l1); - const float e0 = expf(l0 - m), e1 = expf(l1 - m); - const float d = __fadd_rn(e0, e1); - w[0] = __fdiv_rn(e0, d); - w[1] = __fdiv_rn(e1, d); -} - -struct ArArgs { - const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C], one completed state a pointer - const void* partial; // the final source, BF16 or FP32 according to partial_bf16 - const float* query; // fp32 [nq, C] - float* out; // fp32 [nq, rows, C], deliberately neither normalized nor rounded - int n_blocks, partial_bf16, nq, rows, C; - float eps; -}; - -// The AR half of Small's residual mix, without its fused RMSNorm. Needed before Mini's controller, not just after it. -__device__ void ar(const ArArgs a) { - __shared__ float sh[32 * (1 + kMaxQueries)]; - __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; - __shared__ float rr[kMaxBlocks + 1]; - const size_t row = blockIdx.x; - const int n = a.n_blocks + 1; - auto entry = [&](int j, int c) -> float { - if (j < a.n_blocks) return bf(a.blocks[j][row * a.C + c]); - return a.partial_bf16 ? bf(static_cast(a.partial)[row * a.C + c]) - : static_cast(a.partial)[row * a.C + c]; - }; - for (int j = 0; j < n; ++j) { - float ss[1] = {0.0f}; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - const float x = entry(j, c); - ss[0] = __fmaf_rn(x, x, ss[0]); - } - blockSums<1>(ss, sh); - if (threadIdx.x == 0) rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(a.C)), a.eps)); - } - __syncthreads(); - for (int j = 0; j < n; ++j) { - float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - const float normalized = __fmul_rn(entry(j, c), rr[j]); - for (int q = 0; q < a.nq; ++q) - dots[q] = __fmaf_rn(a.query[static_cast(q) * a.C + c], normalized, dots[q]); - } - blockSums(dots, sh); - if (threadIdx.x == 0) - for (int q = 0; q < a.nq; ++q) wts[q][j] = __fmul_rn(dots[q], queryScale(a.C)); - } - __syncthreads(); - if (threadIdx.x < a.nq) { - float* l = wts[threadIdx.x]; - float m = -INFINITY, d = 0.0f; - for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); - for (int j = 0; j < n; ++j) d = __fadd_rn(d, expf(l[j] - m)); - for (int j = 0; j < n; ++j) l[j] = __fdiv_rn(expf(l[j] - m), d); - } - __syncthreads(); - for (int q = 0; q < a.nq; ++q) { - float* out = a.out + (static_cast(q) * a.rows + row) * a.C; - for (int c = threadIdx.x; c < a.C; c += blockDim.x) { - float h = 0.0f; - for (int j = 0; j < n; ++j) { - const float z = __fmul_rn(entry(j, c), rr[j]); - h = __fmaf_rn(wts[q][j], z, h); - } - out[c] = h; - } - } -} - -} // namespace ink2l - -extern "C" __global__ void __launch_bounds__(512) tf_ink2_loop_ar(const ink2l::ArArgs a) { - ink2l::ar(a); -} - -namespace ink2l { - -// One block handles one token and role, sharing each bank's normalization across all 12 core queries. -__device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, - const float* __restrict__ qm, const float* __restrict__ qkv, - float* __restrict__ out, int rows, int core_layers, int c, float eps) { - __shared__ float sh[2 * 32]; - __shared__ float inv[2], w[2]; - const size_t row = blockIdx.x; - const int role = blockIdx.y; // q, k, v, mlp - const uint16_t* banks[2] = {bank0 + row * c, bank1 + row * c}; - const float* role_queries = role == 0 || role == 3 ? qm : qkv; - const int odd = role == 3 || role == 2; - float ss[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float x0 = bf(banks[0][i]), x1 = bf(banks[1][i]); - ss[0] = __fmaf_rn(x0, x0, ss[0]); - ss[1] = __fmaf_rn(x1, x1, ss[1]); - } - blockSums<2>(ss, sh); - if (threadIdx.x == 0) { - inv[0] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); - inv[1] = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); - } - __syncthreads(); - for (int j = 0; j < core_layers; ++j) { - const float* query = role_queries + static_cast(2 * j + odd) * c; - float dots[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float q = query[i]; - const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); - const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); - dots[0] = __fmaf_rn(q, b0, dots[0]); - dots[1] = __fmaf_rn(q, b1, dots[1]); - } - blockSums<2>(dots, sh); - if (threadIdx.x == 0) - softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); - __syncthreads(); - // Plane-major [core][role][rows][c]: the gates read each role's rows as one contiguous plane. - float* dst = out + ((static_cast(j) * 4 + role) * rows + row) * static_cast(c); - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); - const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); - const float m0 = __fmul_rn(w[0], b0), m1 = __fmul_rn(w[1], b1); - dst[i] = __fadd_rn(m0, m1); - } - } -} - -// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). -__device__ void gate(const float* __restrict__ h, const float* __restrict__ m, - const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, - const uint16_t* __restrict__ gain, float* __restrict__ out, - int c, float eps) { - __shared__ float sh[2 * 32]; - __shared__ float inv_h, inv_m; - __shared__ uint16_t zeta[kRank]; - const size_t row = blockIdx.x; - const float* hr = h + row * c; - const float* mr = m + row * c; - float ss[2] = {0.0f, 0.0f}; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); - ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); - } - blockSums<2>(ss, sh); - if (threadIdx.x == 0) { - inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); - inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); - } - __syncthreads(); - // Pair ranks to reuse each normalized input, but keep every dot's 256-thread chains and two-level reduction tree. - for (int r = 0; r < kRank; r += 2) { - float acc[2] = {0.0f, 0.0f}; - const uint16_t* d0 = down + static_cast(r) * (2 * c); - const uint16_t* d1 = d0 + 2 * c; - for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { - const bool message = i >= c; - const float x = message ? mr[i - c] : hr[i]; - const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); - acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); - acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); - } - blockSums<2>(acc, sh); - if (threadIdx.x == 0) { - zeta[r] = tobf(acc[0]); - zeta[r + 1] = tobf(acc[1]); - } - } - __syncthreads(); - float* dst = out + row * c; - for (int i = threadIdx.x; i < c; i += blockDim.x) { - const uint16_t* f = forget + static_cast(i) * kRank; - const uint16_t* g = gain + static_cast(i) * kRank; - float sf = 0.0f, sg = 0.0f; - for (int r = 0; r < kRank; ++r) { - const float z = bf(zeta[r]); - sf = __fmaf_rn(bf(f[r]), z, sf); - sg = __fmaf_rn(bf(g[r]), z, sg); - } - const float fg = tanhf(sf), gg = tanhf(sg); - // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. - const float keep = __fsub_rn(1.0f, fg); - const float old = __fmul_rn(keep, hr[i]); - const float added = __fmul_rn(gg, mr[i]); - dst[i] = __fadd_rn(old, added); - } -} - -} // namespace ink2l - -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, - const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, - int rows, int core_layers, int c, float eps) { - ink2l::messages(bank0, bank1, qm, qkv, out, rows, core_layers, c, eps); -} - -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, - const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, - int rows, int c, float eps) { - (void)rows; - ink2l::gate(h, m, down, forget, gain, out, c, eps); -} - -// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, - const uint16_t* __restrict__ uv, const uint16_t* __restrict__ wq, - const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wv, - uint16_t* __restrict__ raw_q, uint16_t* __restrict__ raw_k, - uint16_t* __restrict__ raw_v, int rows, int c, int q_width, int kv_width) { - constexpr int kRows = 16, kOutputs = 16, kSlice = 32; - __shared__ uint16_t sx[kRows * kSlice], sw[kOutputs * kSlice]; - const int role = blockIdx.z; // q=0, k=1, v=2 - const int width = role == 0 ? q_width : kv_width; - const int row0 = static_cast(blockIdx.x) * kRows; - const int j0 = static_cast(blockIdx.y) * kOutputs; - if (j0 >= width) return; - const uint16_t* x = role == 0 ? uq : role == 1 ? uk : uv; - const uint16_t* w = role == 0 ? wq : role == 1 ? wk : wv; - const int tr = threadIdx.x / kOutputs, tj = threadIdx.x % kOutputs; - const int row = row0 + tr, j = j0 + tj; - float sum = 0.0f; - // A block reuses each normalized tile for 16 outputs and each weight tile for 16 prompt rows. - for (int k0 = 0; k0 < c; k0 += kSlice) { - for (int e = threadIdx.x; e < kRows * kSlice; e += blockDim.x) { - const int r = e / kSlice, k = k0 + e % kSlice; - sx[e] = row0 + r < rows && k < c ? x[static_cast(row0 + r) * c + k] : 0; - sw[e] = j0 + r < width && k < c ? w[static_cast(j0 + r) * c + k] : 0; - } - __syncthreads(); - for (int k = 0; k < kSlice && k0 + k < c; ++k) - sum = __fmaf_rn(ink2l::bf(sx[tr * kSlice + k]), ink2l::bf(sw[tj * kSlice + k]), sum); - __syncthreads(); - } - uint16_t* out = role == 0 ? raw_q : role == 1 ? raw_k : raw_v; - if (row < rows && j < width) out[static_cast(row) * width + j] = ink2l::tobf(sum); -} - -// Global dynamic taps: dot in FP32, store as BF16, and widen to FP32 before the convolution. -extern "C" __global__ void __launch_bounds__(256) - tf_ink2_loop_round_bf16(const float* __restrict__ in, float* __restrict__ out, long long n) { - const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; - if (i < n) out[i] = ink2l::bf(ink2l::tobf(in[i])); -} diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index ea84a0e906a..89bb1ba5820 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -22,11 +22,6 @@ pub const pending = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 32, .static = 272, .bound = 256 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, }; /// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. pub const cuda_132 = [_]registry.Override{}; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index e5891dd15a9..9e48cafa58e 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -122,7 +122,6 @@ pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_e pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const inkling2_loop: []const u8 = if (available) &Blob("fatbin_inkling2_loop").bytes else &.{}; -pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig deleted file mode 100644 index 6bb3b8d7fe0..00000000000 --- a/zig/src/families/inkling2/cuda_native.zig +++ /dev/null @@ -1,220 +0,0 @@ -//! Inkling 2 Mini's complete one-rank, text-only CUDA engine and checkpoint/snapshot admission. -const std = @import("std"); -const cuda = @import("cuda"); -const lanes = @import("lanes"); -const core = @import("core"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -const loop = @import("loop.zig"); -const engine = @import("loop_engine.zig"); -const backend = @import("loop_backend.zig"); - -pub const model_type = "inkling2_loop"; -pub const formats: []const []const u8 = &.{"modelopt-mixed"}; -pub const default_context: i64 = 1_048_576; -pub const max_segments: u32 = 1; -pub const prompt_rows: u32 = engine.prompt_rows; -pub const window_rows: u32 = engine.window_rows; -pub const explains_open = true; - -pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; -pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; -pub const Options = struct { - context: usize, - drafts: bool, - segments: usize = 1, - slide: bool = false, - vision: ?VisionOptions = null, - precision: ?enum { full } = null, - room: ?Room = null, - drafter: ?[]const u8 = null, - tp: usize = 1, - rank: usize = 0, - master: ?[]const u8 = null, - master_port: u16 = 29551, -}; - -pub const Owned = struct { - gpa: std.mem.Allocator, - admission: loop.Admission, - kernels: engine.Kernels, - stream: cuda.Stream, - weights: @import("loop_weights.zig").Weights, - model: engine.Model, - backend: backend.Backend, -}; - -pub const Loaded = struct { - backend: lanes.backend.Backend, - facts: lanes.Model, - rows: u32, - stream_bytes: usize, - free_streams: u32 = 1, - ctx: *anyopaque, - deinit: *const fn (*anyopaque) void, - reserve: *const fn (*anyopaque, u32) anyerror!void = reserve, - target: *Owned, -}; - -fn own(ptr: *anyopaque) *Owned { - return @ptrCast(@alignCast(ptr)); -} - -fn release(p: *anyopaque) void { - const o = own(p); - o.stream.synchronize() catch {}; - o.backend.deinit(); - o.stream.deinit(); - o.model.deinit(); - o.kernels.deinit(); - o.weights.deinit(); - const gpa = o.gpa; - gpa.destroy(o); -} - -/// The server's stream count: a cache slot each, past the one allocated at load. -fn reserve(p: *anyopaque, streams: u32) anyerror!void { - return own(p).backend.reserve(streams); -} - -pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { - const o: *const Owned = @ptrCast(@alignCast(p)); - return o.admission.fits(prompt, max_tokens) and o.backend.admits(prompt, max_tokens); -} - -pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { - if (kernels != null) return error.Inkling2CapturedKernels; - if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; - if (o.vision != null) return error.Inkling2LoopTextOnly; - if (o.drafter != null) return error.Inkling2DSparkPending; - const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); - defer gpa.free(path); - const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); - defer gpa.free(bytes); - var why: config.Why = .{}; - const c = config.parse(gpa, bytes, &why) catch |err| { - std.log.err("Inkling 2 Mini config refused: {s}", .{why.text()}); - return err; - }; - try loop.validateLoad(&c, 1, false); - if (o.context == 0 or o.context > c.text.max_context or o.context > std.math.maxInt(u32)) return error.BadLoopCache; - var ck = try core.Checkpoint.openModel(gpa, io, dir); - defer ck.close(); - try ck.skip("model.visual."); // The checkpoint carries Small's tower; text-only Mini never loads or executes it. - var precisions: [config.max_layers]plan_.Precision = undefined; - @memset(&precisions, .nvfp4); - var header_arena = std.heap.ArenaAllocator.init(gpa); - defer header_arena.deinit(); - var merged: core.safetensors.Header = .empty; - for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); - try @import("names.zig").precisions(merged, c.text.layers, &precisions); - const p = try plan_.build(&c.text, precisions[0..c.text.layers]); - var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); - errdefer w.deinit(); - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - ck.release(); - var k = try engine.Kernels.load(ctx); - errdefer k.deinit(); - var stream = try cuda.Stream.init(ctx.d, true); - errdefer stream.deinit(); - var m = try engine.Model.init(gpa, ctx.d, stream, &w, o.context); - errdefer m.deinit(); - var be = try backend.Backend.init(gpa, ctx.d, &m, &k, stream); - errdefer be.deinit(); - const out = try gpa.create(Owned); - errdefer gpa.destroy(out); - out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; - // The value copies above own pointers to their old stack homes; retarget the live model/backend now. - out.model.w = &out.weights; - out.backend.m = &out.model; - out.backend.k = &out.kernels; - return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = backend.streamBytes(&out.model), .ctx = out, .deinit = release, .target = out }; -} - -pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { - return own(ptr).model.snapshotBytes(at); -} - -pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { - return @ptrCast(try own(ptr).backend.saveState(owner, at)); -} - -pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { - return own(ptr).backend.restoreState(owner, @ptrCast(@alignCast(saved))); -} - -pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { - own(ptr).backend.dropState(@ptrCast(@alignCast(saved))); -} - -pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { - return switch (err) { - error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", - error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", - error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", - error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", - error.Inkling2TooManyStreams => "Inkling 2 Mini on CUDA holds at most 16 streams: lower --parallel", - error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", - else => null, - }; -} - -test "Mini native registration and refusal wording are explicit" { - try std.testing.expectEqualStrings("inkling2_loop", model_type); - try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); - try std.testing.expectEqual(16, engine.max_slots); // the stream cap explain() names - for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels, error.Inkling2TooManyStreams }) |err| { - try std.testing.expect(explain(null, err) != null); - } -} - -test "the complete prompt snapshot hooks match the store vtable" { - const pc: struct { - bytes: *const fn (*anyopaque, u32) u64, - save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, - restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, - drop: *const fn (*anyopaque, *anyopaque) void, - } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; - try std.testing.expect(@intFromPtr(pc.save) != 0); -} - -test "stream_bytes is what an extra stream's slot and lane buffers allocate, 806,408 bytes past the cache on Mini" { - const Record = struct { // a DeviceBuffer hook that hands out addresses and sums what is asked - bytes: usize = 0, - next: u64 = 1 << 32, - fn alloc(ctx: *anyopaque, len: usize) ?u64 { - const r: *@This() = @ptrCast(@alignCast(ctx)); - r.bytes += len; - r.next += std.mem.alignForward(u64, len, 512); - return r.next; - } - fn free(_: *anyopaque, _: u64) bool { - return true; - } - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var why: config.Why = .{}; - var w: @import("loop_weights.zig").Weights = undefined; - w.c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); - var precisions: [24]plan_.Precision = @splat(.nvfp4); - w.p = try plan_.build(&w.c.text, &precisions); - var m: engine.Model = undefined; - m.d = @ptrFromInt(0x1000); // never called: the hook answers every allocation - m.w = &w; - m.layout = try loop.CacheLayout.init(&w.c.text, &w.p, 8192); - var b: backend.Backend = undefined; - b.d = m.d; - b.m = &m; - b.held = 1; - var rec: Record = .{}; - const before = cuda.memory.currentHook(); - cuda.memory.setHook(.{ .ctx = &rec, .alloc = Record.alloc, .free = Record.free }); - defer cuda.memory.setHook(before); - var slot = try m.newSlot(); - defer for ([2]*cuda.DeviceBuffer{ &slot.cache, &slot.sites }) |x| x.free(); - try b.slotBuffers(2); // the second stream's lane buffers; the first already holds its own - defer for (&b.slot[1]) |*x| x.free(); - try std.testing.expectEqual(@as(u64, rec.bytes), backend.streamBytes(&m)); - try std.testing.expectEqual(@as(u64, 48 * 4 * 32 + 200_058 * 4 + 32), backend.streamBytes(&m) - m.layout.bytes); -} diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig deleted file mode 100644 index 4834266e850..00000000000 --- a/zig/src/families/inkling2/loop_backend.zig +++ /dev/null @@ -1,346 +0,0 @@ -//! Inkling 2 Mini lane execution and snapshot adapter. -const std = @import("std"); -const cuda = @import("cuda"); -const lanes = @import("lanes"); -const engine = @import("loop_engine.zig"); -const ops = @import("ops.zig"); - -const Model = engine.Model; -const Kernels = engine.Kernels; -const prompt_rows = engine.prompt_rows; -const window_rows = engine.window_rows; -const token_ring = 1024; - -const Lane = struct { - len: usize = 0, - fill: ?usize = null, - base: usize = 0, - rows: std.ArrayList(u32) = .empty, - last: u64, - rule: u64, - sampled: bool = false, -}; - -/// The bytes a slot's lane buffers ask for: a vocabulary row of last logits and a sampling rule. -pub fn laneAllocs(vocab: u32) [2]usize { - return .{ @as(usize, vocab) * 4, @sizeOf(cuda.sample.Rule) }; -} - -/// The device bytes each served stream holds: its model slot (engine.slotAllocs) and its lane buffers. -pub fn streamBytes(m: *const Model) u64 { - const slot = engine.slotAllocs(&m.layout, m.w.p.n_visits); - const lane = laneAllocs(m.w.c.text.unpadded_vocab); - return slot[0] + slot[1] + lane[0] + lane[1]; -} - -pub const Backend = struct { - gpa: std.mem.Allocator, - d: *const cuda.Driver, - m: *Model, - k: *const Kernels, - s: cuda.Stream, - lanes_: [engine.max_slots]?Lane = @splat(null), - streams: [engine.max_slots]?*lanes.Stream = @splat(null), // the stream each model slot holds - tokens: cuda.DeviceBuffer, - logits16: cuda.DeviceBuffer, - meta: cuda.DeviceBuffer, - slot: [engine.max_slots][2]cuda.DeviceBuffer = undefined, // each slot's last prompt logits and sampling rule - next: u64 = 0, - held: usize = 0, // slots with buffers - - const be = lanes.backend; - - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *Model, k: *const Kernels, s: cuda.Stream) !Backend { - const v = m.w.c.text.unpadded_vocab; - var tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + window_rows) * 4); - errdefer tokens.free(); - var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); - errdefer logits16.free(); - var meta = try cuda.DeviceBuffer.alloc(d, 16); - errdefer meta.free(); - var b: Backend = .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .tokens = tokens, .logits16 = logits16, .meta = meta }; - try b.slotBuffers(m.n_slots); - return b; - } - - /// Each model slot's own last-logits and rule buffers, up to `n`. - pub fn slotBuffers(b: *Backend, n: usize) !void { - const sizes = laneAllocs(b.m.w.c.text.unpadded_vocab); - for (0..n) |i| { - if (i < b.held) continue; - var last = try cuda.DeviceBuffer.alloc(b.d, sizes[0]); - errdefer last.free(); - b.slot[i] = .{ last, try cuda.DeviceBuffer.alloc(b.d, sizes[1]) }; - b.held = i + 1; - } - } - - /// The server's stream count: one model slot and its buffers per stream. - pub fn reserve(b: *Backend, streams: u32) !void { - if (streams > engine.max_slots) return error.Inkling2TooManyStreams; - try b.m.addSlots(b.s, streams); - try b.slotBuffers(streams); - } - - pub fn deinit(b: *Backend) void { - for (&b.lanes_) |*x| if (x.*) |*l| l.rows.deinit(b.gpa); - for (b.slot[0..b.held]) |*pair| for (pair) |*x| x.free(); - b.meta.free(); - b.logits16.free(); - b.tokens.free(); - b.* = undefined; - } - - pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &vtable }; - } - - pub fn facts(_: *const Backend) lanes.Model { - return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = 1, .streams_exact = true }; - } - - pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { - return b.freeSlot() != null and prompt <= b.m.context and max_new <= b.m.context - prompt; - } - - fn freeSlot(b: *const Backend) ?usize { - for (b.streams[0..@min(b.m.n_slots, b.held)], 0..) |x, i| if (x == null) return i; - return null; - } - - fn slotOf(b: *const Backend, s: *const lanes.Stream) ?usize { - for (b.streams, 0..) |x, i| if (x == s) return i; - return null; - } - - /// The device buffer holding `s`'s last prompt logits. - pub fn lastOf(b: *const Backend, s: *const lanes.Stream) !u64 { - const i = b.slotOf(s) orelse return error.UnknownStream; - return b.lanes_[i].?.last; - } - - fn self(ptr: *anyopaque) *Backend { - return @ptrCast(@alignCast(ptr)); - } - - fn upload(b: *Backend, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(b.d, dst, bytes, b.s); - } - - /// `s`'s lane, its model slot selected for the calls that follow. - fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { - const i = b.slotOf(s) orelse return error.UnknownStream; - if (i >= b.m.n_slots) return error.UnknownStream; - b.m.slot = i; - return if (b.lanes_[i]) |*l| l else error.UnknownStream; - } - - fn resumeSaved(b: *Backend, s: *lanes.Stream) usize { - const saved = s.reuse.saved orelse return 0; - const k: *const Model.Saved = @ptrCast(@alignCast(saved)); - if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { - s.reuse_failed = true; - return 0; - } - b.m.restore(b.s, k) catch { - s.reuse_failed = true; - return 0; - }; - s.cached = k.at; - return k.at; - } - - fn opening(b: *Backend, s: *lanes.Stream) !*Lane { - const prompt = s.prompt(); - if (prompt.len == 0) return error.EmptyPrompt; - if (prompt.len > b.m.context or s.max_new > b.m.context - prompt.len) return error.PastContext; - if (b.slotOf(s) == null) { - const i = b.freeSlot() orelse return error.NoFreeSlot; - b.lanes_[i] = .{ .last = b.slot[i][0].ptr, .rule = b.slot[i][1].ptr }; - b.streams[i] = s; - } - const l = try b.laneOf(s); - l.sampled = false; - if (cuda.sample.ruleFor(s.sampling)) |r| { - try b.upload(l.rule, std.mem.asBytes(&r)); - l.sampled = true; - } - l.len = 0; - try b.m.reset(b.s); - const at = b.resumeSaved(s); - l.len = at; - l.fill = at; - s.fill_at.store(@intCast(at), .monotonic); - return l; - } - - fn chunk(b: *Backend, s: *lanes.Stream, l: *Lane) !bool { - const prompt = s.prompt(); - const at = l.fill.?; - if (s.isCancelled()) return error.Cancelled; - var end = @min(prompt.len, (at / prompt_rows + 1) * prompt_rows); - for (s.reuse.marks) |mark| { - if (mark > at and mark < end) end = mark; - } - const done = end == prompt.len; - try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); - if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); - l.len = end; - l.fill = if (done) null else end; - s.fill_at.store(@intCast(end), .monotonic); - if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) - hook.at(hook.ptr, s, @intCast(end)); - return done; - } - - fn handle(b: *Backend) usize { - const h = b.next; - b.next += 1; - return @intCast(h % token_ring); - } - - fn drawRows(b: *Backend, l: *const Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { - const v = b.m.w.c.text.unpadded_vocab; - if (!l.sampled) return ops.top1(&b.k.glue, b.s, logits, rows, v, v, 0, b.m.s.t + at * 4, b.tokens.ptr + at * 4); - try ops.tobf(&b.k.glue, b.s, logits, rows, v, v, b.logits16.ptr, v, 0, v); - const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; - try b.upload(b.meta.ptr, std.mem.asBytes(&metadata)); - try b.k.draws.draw(b.s, b.logits16.ptr, v, l.rule, b.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); - } - - fn read(ptr: *anyopaque, h: u64) anyerror!u32 { - const b = self(ptr); - if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; - var out: [1]u32 = undefined; - try b.s.synchronize(); - try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); - return out[0]; - } - - const vtable: be.Backend.VTable = .{ - .prefill = prefill, - .prefill_step = prefillStep, - .first = first, - .first_masked = firstMasked, - .queue = queue, - .read = read, - .verify = verify, - .keep = keep, - .draft = draft, - .release = release, - .reports_fill = true, - }; - - fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { - const b = self(ptr); - const l = try b.opening(s); - errdefer release(ptr, s); - while (!try b.chunk(s, l)) {} - } - - fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { - const b = self(ptr); - const going = if (b.slotOf(s)) |i| b.lanes_[i].?.fill != null else false; - const l = if (going) try b.laneOf(s) else try b.opening(s); - errdefer release(ptr, s); - return b.chunk(s, l); - } - - fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { - const b = self(ptr); - const l = try b.laneOf(s); - if (position != l.len or l.fill != null) return error.PositionMismatch; - const h = b.next; - try b.drawRows(l, l.last, 1, position, b.handle()); - return h; - } - - fn firstMasked(_: *anyopaque, _: *lanes.Stream, _: u64, _: []const u32) anyerror!u64 { - return error.StructuresUnsupported; - } - - fn feed(b: *Backend, value: be.Feed) !u32 { - return switch (value) { - .value => |v| v, - .handle => |h| read(b, h), - }; - } - - fn queue(ptr: *anyopaque, s: *lanes.Stream, value: be.Feed, position: u64) anyerror!u64 { - const b = self(ptr); - const l = try b.laneOf(s); - const token = try b.feed(value); - if (position != l.len + 1) return error.PositionMismatch; - try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); - l.len += 1; - const h = b.next; - try b.drawRows(l, b.m.s.logits, 1, position, b.handle()); - return h; - } - - fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { - const b = self(ptr); - if (windows.len != 1 or out.len != 1) return error.OneStreamOnly; - const w = windows[0]; - if (w.held != 0) return error.NoHeldDrafts; - if (w.parents != null) return error.ChainsOnly; - if (w.masks.len != 0) return error.StructuresUnsupported; - const l = try b.laneOf(w.stream); - const n = w.rows(); - if (n == 0 or n > window_rows) return error.WindowTooWide; - l.base = l.len; - l.rows.clearRetainingCapacity(); - try l.rows.append(b.gpa, w.pending); - try l.rows.appendSlice(b.gpa, w.tokens); - for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; - try b.m.forward(b.k, b.s, l.rows.items, l.base, 0, n, true); - try b.drawRows(l, b.m.s.logits, n, w.positions[0], token_ring); - var got: [window_rows]u32 = undefined; - try b.s.synchronize(); - try b.tokens.download(token_ring * 4, std.mem.sliceAsBytes(got[0..n])); - @memcpy(out[0].sampled[0..n], got[0..n]); - @memcpy(out[0].drafts[0 .. n - 1], l.rows.items[1..n]); - l.len = l.base + n; - } - - fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { - const b = self(ptr); - if (windows.len != 1 or paths.len != 1) return error.OneStreamOnly; - const l = try b.laneOf(windows[0].stream); - const path = paths[0]; - if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; - for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; - try b.m.rewind(b.k, b.s, path.len); - l.len = l.base + path.len; - } - - fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { - for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; - } - - pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const l = try b.laneOf(s); - if ((l.fill orelse l.len) != at) return error.NotAtMark; - return b.m.save(b.s, at); - } - - pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); - const l = try b.laneOf(s); - try b.m.restore(b.s, saved); - l.len = saved.at; - } - - pub fn dropState(b: *Backend, saved: *Model.Saved) void { - b.m.drop(b.s, saved); - } - - fn release(ptr: *anyopaque, s: *lanes.Stream) void { - const b = self(ptr); - const i = b.slotOf(s) orelse return; - if (b.lanes_[i]) |*l| l.rows.deinit(b.gpa); - b.lanes_[i] = null; - b.streams[i] = null; - } -}; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig deleted file mode 100644 index c04446872e6..00000000000 --- a/zig/src/families/inkling2/loop_engine.zig +++ /dev/null @@ -1,591 +0,0 @@ -//! One-rank, text-only Inkling 2 Mini: the complete 48-visit CUDA forward. -const std = @import("std"); -const cuda = @import("cuda"); -const config = @import("config.zig"); -const loop = @import("loop.zig"); -const weights_ = @import("loop_weights.zig"); -const ops = @import("ops.zig"); -const attention = @import("kernels.zig"); -const modelopt = @import("modelopt.zig"); -const loop_math = @import("loop_math_cuda.zig"); - -pub const prompt_rows: usize = 2048; -pub const window_rows: usize = 16; - -pub const Kernels = struct { - glue: ops.Kernels, - attn: attention.Kernels, - moe: modelopt.Kernels, - loop: loop_math.Kernels, - sample_mod: cuda.Module, - draws: cuda.sample.Draws, - - pub fn load(ctx: *const cuda.Context) !Kernels { - const d = ctx.d; - var glue = try ops.Kernels.load(d); - errdefer glue.unload(); - var attn = try attention.Kernels.load(d); - errdefer attn.unload(); - const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); - var moe = try modelopt.Kernels.load(d, sms); - errdefer moe.unload(); - var lm = try loop_math.Kernels.load(d); - errdefer lm.unload(); - var sample_mod = try cuda.Module.load(d, cuda.kernels.sample); - errdefer sample_mod.unload(); - return .{ - .glue = glue, - .attn = attn, - .moe = moe, - .loop = lm, - .sample_mod = sample_mod, - .draws = try cuda.sample.Draws.resolve(sample_mod), - }; - } - - pub fn deinit(k: *Kernels) void { - k.sample_mod.unload(); - k.loop.unload(); - k.moe.unload(); - k.attn.unload(); - k.glue.unload(); - k.* = undefined; - } -}; - -const Scratch = struct { - ids: u64, - pos: u64, - seg_of: u64, - segs: u64, - tiles: u64, - blocks: [ops.max_blocks]u64 = @splat(0), - partial_a: u64, - partial_b: u64, - prelude: u64, - bank0: u64, - bank1: u64, - raw: u64, // three FP32 AR/gate rows per token - messages: u64, // four FP32 message rows per token - normalized: u64, // three BF16 rows per token - t: u64, - q_raw: u64, - rel_raw: u64, - sink: u64, - gate: u64, - k_raw: u64, - v_raw: u64, - k_conv: u64, - v_conv: u64, - k_dynamic: u64, - v_dynamic: u64, - q_prepared: u64, - rel_prepared: u64, - rel_table: u64, - part_o: u64, - part_ml: u64, - attn_heads: u64, - attn_out: u64, - route_scores: u64, - route_pick: u64, - route_weights: u64, - moe_out: u64, - moe_scratch: u64, - hidden: u64, - logits: u64, - backup: u64, - hist: u64, -}; - -/// A stream's state (every visit's K/V rows and conv states, its rewind sites); at most `max_slots`, one in use. -const Slot = struct { cache: cuda.DeviceBuffer, sites: cuda.DeviceBuffer }; -pub const max_slots = 16; - -/// The bytes a slot's allocations ask for: the cache layout and four rewind sites a visit. -pub fn slotAllocs(layout: *const loop.CacheLayout, n_visits: u32) [2]usize { - return .{ @intCast(layout.bytes), @as(usize, n_visits) * 4 * @sizeOf(ops.RewindSite) }; -} - -pub const Model = struct { - gpa: std.mem.Allocator, - d: *const cuda.Driver, - w: *const weights_.Weights, - context: usize, - layout: loop.CacheLayout, - slots: [max_slots]Slot = undefined, - n_slots: usize = 0, - slot: usize = 0, // the slot forwards, snapshots and rewinds use; forwards share the scratch - recorded: ?usize = null, // the slot whose window `backup` and `hist` hold - s: Scratch = undefined, - buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, - - fn slotBase(m: *const Model) u64 { - return m.slots[m.slot].cache.ptr; - } - - /// Allocates slots until `n` exist, each with zeroed conv states and its own rewind sites. - pub fn addSlots(m: *Model, s: cuda.Stream, n: usize) !void { - if (n > max_slots) return error.TooManySlots; - const keep = m.slot; - defer m.slot = keep; - const kv: usize = @as(usize, m.w.c.text.local.kv) * m.w.c.text.local.dim; - var sites: [config.max_visits * 4]ops.RewindSite = undefined; - while (m.n_slots < n) { - var slot = try m.newSlot(); - errdefer for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); - m.slots[m.n_slots] = slot; - m.slot = m.n_slots; - for (0..m.w.p.n_visits) |v| for (0..4) |site| { - const c = if (site < 2) kv else m.w.c.text.hidden; - const hist = m.histOf(@intCast(v), site) - m.s.hist; - sites[v * 4 + site] = .{ .state = m.convOf(@intCast(v), site), .hist = @intCast(hist), .backup = @intCast(m.backupOf(@intCast(v), site)), .c = @intCast(c) }; - }; - try m.upload(s, slot.sites.ptr, std.mem.sliceAsBytes(sites[0 .. m.w.p.n_visits * 4])); - try m.reset(s); - try s.synchronize(); - m.n_slots += 1; - } - } - - /// A slot's two allocations, sized by slotAllocs: its cache and its rewind-site table. - pub fn newSlot(m: *const Model) !Slot { - const sizes = slotAllocs(&m.layout, m.w.p.n_visits); - var cache = try cuda.DeviceBuffer.alloc(m.d, sizes[0]); - errdefer cache.free(); - return .{ .cache = cache, .sites = try cuda.DeviceBuffer.alloc(m.d, sizes[1]) }; - } - - fn alloc(m: *Model, bytes: usize) !u64 { - var b = try cuda.DeviceBuffer.alloc(m.d, @max(bytes, 256)); - errdefer b.free(); - try m.buffers.append(m.gpa, b); - return b.ptr; - } - - fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { - try cuda.copy_source.enqueue(m.d, dst, bytes, s); - } - - fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { - try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); - } - - fn zeros(m: *const Model, s: cuda.Stream, ptr: u64, bytes: usize) !void { - try m.d.check(m.d.api.cuMemsetD8Async(ptr, 0, bytes, s.handle), "cuMemsetD8Async"); - } - - fn layerGeometry(m: *const Model, layer: u32) attention.Layer { - return if (config.isGlobal(layer)) - attention.Layer.global(@intCast(m.context)) - else - attention.Layer.sliding(m.w.c.text.window, @intCast(@min(prompt_rows, m.context))); - } - - fn cacheOf(m: *const Model, visit: u32) attention.Cache { - const slot = m.layout.at(visit); - const base = m.slotBase() + slot.kv_offset; - return .{ .k = base, .v = base + slot.kv_bytes / 2 }; - } - - fn convOf(m: *const Model, visit: u32, site: usize) u64 { - const c = m.w.c.text; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const h: usize = c.hidden; - const widths = [4]usize{ kv, kv, h, h }; - var at = m.slotBase() + m.layout.at(visit).conv_offset; - for (0..site) |i| at += 3 * widths[i] * 4; - return at; - } - - fn histOf(m: *const Model, visit: u32, site: usize) u64 { - const c = m.w.c.text; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const h: usize = c.hidden; - const widths = [4]usize{ kv, kv, h, h }; - var at = m.s.hist + visit * window_rows * (2 * kv + 2 * h) * 4; - for (0..site) |i| at += window_rows * widths[i] * 4; - return at; - } - - fn backupOf(m: *const Model, visit: u32, site: usize) usize { - return m.convOf(visit, site) - (m.slotBase() + m.layout.at(0).conv_offset); - } - - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const weights_.Weights, context: usize) !Model { - const layout = try loop.CacheLayout.init(&w.c.text, &w.p, @intCast(context)); - var m: Model = .{ - .gpa = gpa, - .d = d, - .w = w, - .context = context, - .layout = layout, - }; - errdefer m.deinitBuffers(); - const c = w.c.text; - const h: usize = c.hidden; - const q: usize = @as(usize, c.global.q) * c.global.dim; - const kv: usize = @as(usize, c.local.kv) * c.local.dim; - const rows = prompt_rows; - const rel_rows = rows * c.global.q * attention.extent; - const local = attention.Layer.sliding(c.window, @intCast(@min(prompt_rows, context))); - const global = attention.Layer.global(@intCast(context)); - const local_slots = attention.slotsFor(local, context); - const global_slots = attention.slotsFor(global, context); - const part_slots = @max(rows * c.local.q * local_slots, rows * c.global.q * global_slots); - const hist_values = @as(usize, w.p.n_visits) * (2 * kv + 2 * h) * window_rows; - m.s = .{ - .ids = try m.alloc(rows * 4), - .pos = try m.alloc(rows * 4), - .seg_of = try m.alloc(rows * 4), - .segs = try m.alloc(@sizeOf(attention.Seg)), - .tiles = try m.alloc(128 * @sizeOf(attention.Tile)), - .partial_a = try m.alloc(rows * h * 2), - .partial_b = try m.alloc(rows * h * 2), - .prelude = try m.alloc(rows * h * 2), - .bank0 = try m.alloc(rows * h * 2), - .bank1 = try m.alloc(rows * h * 2), - .raw = try m.alloc(3 * rows * h * 4), - .messages = try m.alloc(4 * rows * h * 4), - .normalized = try m.alloc(3 * rows * h * 2), - .t = try m.alloc(rows * h * 4), - .q_raw = try m.alloc(rows * q * 2), - .rel_raw = try m.alloc(rows * c.global.q * c.d_rel * 2), - .sink = try m.alloc(rows * c.global.q * 2), - .gate = try m.alloc(rows * q * 2), - .k_raw = try m.alloc(rows * kv * 2), - .v_raw = try m.alloc(rows * kv * 2), - .k_conv = try m.alloc(rows * kv * 2), - .v_conv = try m.alloc(rows * kv * 2), - .k_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), - .v_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), - .q_prepared = try m.alloc(rows * q * 2), - .rel_prepared = try m.alloc(rows * c.global.q * c.d_rel * 2), - .rel_table = try m.alloc(rel_rows * 2), - .part_o = try m.alloc(part_slots * attention.head_dim * 4), - .part_ml = try m.alloc(part_slots * 8), - .attn_heads = try m.alloc(rows * q * 2), - .attn_out = try m.alloc(rows * h * 2), - .route_scores = try m.alloc(rows * c.experts * 4), - .route_pick = try m.alloc(rows * c.experts * 4), - .route_weights = try m.alloc(rows * c.experts * 4), - .moe_out = try m.alloc(rows * h * 2), - .moe_scratch = try m.alloc(try modelopt.scratchBytes(rows, c.topk, h, c.expert_inter)), - .hidden = try m.alloc(rows * h * 2), - .logits = try m.alloc(window_rows * c.unpadded_vocab * 4), - .backup = try m.alloc(layout.bytes - layout.at(0).conv_offset), - .hist = try m.alloc(hist_values * 4), - }; - for (0..ops.max_blocks) |i| m.s.blocks[i] = try m.alloc(rows * h * 2); - try m.addSlots(s, 1); - return m; - } - - fn deinitBuffers(m: *Model) void { - for (m.buffers.items) |*b| b.free(); - m.buffers.deinit(m.gpa); - } - - pub fn deinit(m: *Model) void { - m.deinitBuffers(); - for (m.slots[0..m.n_slots]) |*slot| for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); - m.* = undefined; - } - - pub fn reset(m: *const Model, s: cuda.Stream) !void { - try m.zeros(s, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); - } - - pub fn rewind(m: *const Model, k: *const Kernels, s: cuda.Stream, kept: usize) !void { - if (kept > window_rows) return error.WindowTooWide; - if (m.recorded != m.slot) return error.RewindOfAnotherSlot; - try ops.rewind(&k.glue, s, m.slots[m.slot].sites.ptr, m.w.p.n_visits * 4, m.w.c.text.hidden, m.s.backup, m.s.hist, 0, 0, kept); - } - - fn arBlocks(m: *const Model, blocks: []const u64, partial: u64, query: u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) loop_math.ArArgs { - var a: loop_math.ArArgs = .{ - .partial = partial, - .query = query, - .out = out, - .n_blocks = @intCast(blocks.len), - .partial_bf16 = @intFromBool(partial_bf16), - .nq = @intCast(nq), - .rows = @intCast(rows), - .c = @intCast(m.w.c.text.hidden), - .eps = m.w.c.text.eps, - }; - for (blocks, 0..) |b, i| a.blocks[i] = b; - return a; - } - - fn mixArgs(m: *const Model, blocks: []const u64, partial: u64, query: u64, norms: [3]u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) ops.MixArgs { - var a: ops.MixArgs = .{ - .partial = partial, - .query = query, - .out = out, - .n_blocks = @intCast(blocks.len), - .partial_bf16 = @intFromBool(partial_bf16), - .nq = @intCast(nq), - .rows = @intCast(rows), - .c = @intCast(m.w.c.text.hidden), - .eps = m.w.c.text.eps, - }; - for (blocks, 0..) |b, i| a.blocks[i] = b; - a.norm = norms; - return a; - } - - /// One prompt chunk or one decode window. `record` retains every convolution input for exact prefix rollback. - pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, tokens: []const u32, p0: usize, head0: usize, heads: usize, record: bool) !void { - const c = m.w.c.text; - const rows = tokens.len; - const h: usize = c.hidden; - if (rows == 0 or rows > prompt_rows or p0 + rows > m.context or (!record and heads > window_rows) or head0 + heads > rows) - return error.BadLoopRows; - if (record and rows > window_rows) return error.WindowTooWide; - var ids: [prompt_rows]i32 = undefined; - var pos: [prompt_rows]i32 = undefined; - var seg_of: [prompt_rows]i32 = @splat(0); - for (tokens, 0..) |token, i| { - ids[i] = @intCast(token); - pos[i] = @intCast(p0 + i); - } - try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ids[0..rows])); - try m.upload(s, m.s.pos, std.mem.sliceAsBytes(pos[0..rows])); - try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(seg_of[0..rows])); - const seg: attention.Seg = .{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p0), .off = 0 }; - try m.upload(s, m.s.segs, std.mem.asBytes(&seg)); - m.recorded = if (record) m.slot else null; - if (record) try m.copy(s, m.s.backup, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); - - try ops.embed(&k.glue, s, m.s.ids, rows, m.w.embed, m.w.embed_norm, m.s.partial_a, h, c.eps); - var partial = m.s.partial_a; - var next = m.s.partial_b; - var n_blocks: usize = 0; - const lp = c.loop.?; - - for (m.w.p.visits[0..m.w.p.n_visits]) |visit| { - const layer = m.w.p.at(visit.layer); - const lw = &m.w.layers[visit.layer]; - if (visit.pass >= 2 and visit.layer == lp.core_start) { - try m.copy(s, partial, m.s.prelude, rows * h * 2); - n_blocks = 1; // block zero is the embedding; later passes never inherit completed blocks - } - const messages = visit.hasMessages(); - if (messages) { - const core_j = visit.layer - lp.core_start; - try loop_math.messages(&k.loop, s, m.s.bank0, m.s.bank1, m.w.cross_qm + 2 * core_j * h * 4, m.w.cross_kv + 2 * core_j * h * 4, m.s.messages, rows, 1, h, c.eps); - } - const nq: usize = if (layer.kind == .global) 3 else 1; - const query = m.w.attn_queries[visit.layer]; - const blocks = m.s.blocks[0..n_blocks]; - const raw_stride = rows * h * 4; - const norm_stride = rows * h * 2; - if (messages) { - if (nq == 3) { - try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw, 3, true, rows)); - } else { - // A sliding layer stores one query; each gated role gets its own AR result from that query. - for (0..3) |role| try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw + role * raw_stride, 1, true, rows)); - } - for (0..3) |role| { - const ctl = lw.controllers[role]; - try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); - const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; - try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); - } - } else { - try ops.mix(&k.glue, s, m.mixArgs(blocks, partial, query, lw.attn.norms, m.s.normalized, nq, true, rows)); - } - const u_q = m.s.normalized; - const u_k = if (layer.kind == .global or messages) m.s.normalized + norm_stride else u_q; - const u_v = if (layer.kind == .global or messages) m.s.normalized + 2 * norm_stride else u_q; - const q_width: usize = @as(usize, layer.heads.q) * layer.heads.dim; - const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; - try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); - try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, false); - try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, false); - - const geometry = m.layerGeometry(visit.layer); - const cache = m.cacheOf(visit.cache_slot); - const dynamic = layer.kind == .global; - for (0..2) |kind| { - const input = if (kind == 0) u_k else u_v; - const dyn_out = if (kind == 0) m.s.k_dynamic else m.s.v_dynamic; - if (dynamic) { - try ops.rowdot(&k.glue, s, input, if (kind == 0) lw.attn.k_dynamic else lw.attn.v_dynamic, dyn_out, rows, layer.heads.kv * config.conv_taps, h, false, false); - try loop_math.roundBf16(&k.loop, s, dyn_out, dyn_out, rows * layer.heads.kv * config.conv_taps); - } - try ops.conv(&k.glue, s, .{ - .x = if (kind == 0) m.s.k_raw else m.s.v_raw, - .state = m.convOf(visit.cache_slot, kind), - .w = if (kind == 0) lw.attn.k_conv else lw.attn.v_conv, - .dyn = if (dynamic) dyn_out else 0, - .out = if (kind == 0) m.s.k_conv else m.s.v_conv, - .hist = if (record) m.histOf(visit.cache_slot, kind) else 0, - .x_bf16 = 1, - .heads = @intCast(layer.heads.kv), - .c = @intCast(kv_width), - .rows = @intCast(rows), - .mode = 0, - }, 1); - } - var tiles: [128]attention.Tile = undefined; - const n_tiles = try attention.tiles(&.{seg}, layer.heads.q / layer.heads.kv, &tiles); - try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); - const stride = attention.slotsFor(geometry, m.context); - const part_capacity = prompt_rows * layer.heads.q * stride; - const r: attention.Rows = .{ - .rows = @intCast(rows), - .heads = layer.heads.q, - .kv_heads = layer.heads.kv, - .pos = m.s.pos, - .seg_of = m.s.seg_of, - .segs = m.s.segs, - .tiles = m.s.tiles, - .n_tiles = @intCast(n_tiles), - .last_pos = @intCast(p0 + rows - 1), - }; - const prep: attention.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = @floatFromInt(c.log_floor), .alpha = c.log_alpha, .eps = c.eps }; - try attention.prep(&k.attn, s, r, geometry, prep, .{ m.s.q_raw, m.s.k_conv, m.s.v_conv, m.s.rel_raw }, .{ lw.attn.q_scale, lw.attn.rel_scale }, m.s.q_prepared, m.s.rel_prepared, cache); - try attention.relTable(&k.attn, s, r, m.s.rel_prepared, lw.attn.rel_proj, m.s.rel_table); - try attention.attend(&k.attn, s, r, geometry, stride, part_capacity, m.s.q_prepared, cache, m.s.rel_table, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.attn_heads); - try ops.rowdot(&k.glue, s, m.s.attn_heads, lw.attn.wo, m.s.attn_out, rows, h, q_width, true, false); - - if (layer.boundary) { - try m.copy(s, m.s.blocks[n_blocks], partial, rows * h * 2); - n_blocks += 1; - } - try ops.conv(&k.glue, s, .{ - .x = m.s.attn_out, - .state = m.convOf(visit.cache_slot, 2), - .w = lw.attn_conv, - .base = if (layer.boundary) 0 else partial, - .resid = m.s.t, - .hist = if (record) m.histOf(visit.cache_slot, 2) else 0, - .x_bf16 = 1, - .c = @intCast(h), - .rows = @intCast(rows), - .mode = 1, - }, 1); - - const mlp_query = m.w.mlp_queries[visit.layer]; - const mlp_blocks = m.s.blocks[0..n_blocks]; - if (messages) { - try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); - const ctl = lw.controllers[3]; - try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); - try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); - } else { - try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); - } - try ops.rowdot(&k.glue, s, m.s.normalized, lw.router, m.s.route_scores, rows, c.experts, h, false, true); - try ops.topk(&k.glue, s, m.s.route_scores, lw.router_bias, m.s.route_pick, m.s.route_weights, rows, c.experts, c.topk, c.route_scale); - try modelopt.run(&k.moe, s, lw.experts, .{ .gate = c.gate_cap, .up = c.up_cap }, m.s.normalized, h, m.s.route_pick, m.s.route_weights, rows, c.topk, m.s.moe_out, m.s.moe_scratch); - try ops.conv(&k.glue, s, .{ - .x = m.s.moe_out, - .state = m.convOf(visit.cache_slot, 3), - .w = lw.mlp_conv, - .resid = m.s.t, - .out = next, - .hist = if (record) m.histOf(visit.cache_slot, 3) else 0, - .x_bf16 = 1, - .c = @intCast(h), - .rows = @intCast(rows), - .mode = 2, - }, 1); - std.mem.swap(u64, &partial, &next); - - if (visit.layer + 1 == lp.core_start) try m.copy(s, m.s.prelude, partial, rows * h * 2); - if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) { - try m.copy(s, m.s.bank0, m.s.blocks[n_blocks - 1], rows * h * 2); - try m.copy(s, m.s.bank1, partial, rows * h * 2); - } - } - - if (heads == 0) return; - try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); - try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); - try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); - try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); - } - - pub const Saved = struct { - at: u32, - visits: u32, - passes: u32, - hidden: u32, - buf: cuda.DeviceBuffer, - }; - - /// Compact bytes for all valid K/V rows and every convolution state of all 48 visits. - pub fn snapshotBytes(m: *const Model, at: usize) u64 { - var bytes = m.layout.bytes - m.layout.at(0).conv_offset; - for (0..m.w.p.n_visits) |v| { - const layer = m.w.p.at(m.w.p.visits[v].layer); - const global = layer.kind == .global; - const count = if (global) at else @min(at, m.w.c.text.window - 1); - const row = @as(u64, layer.heads.kv) * layer.heads.dim * 2; - bytes += 2 * count * row; - } - return bytes; - } - - fn copyState(m: *const Model, s: cuda.Stream, saved: *const Saved, out: bool) !void { - const at: usize = saved.at; - var off: usize = 0; - for (0..m.w.p.n_visits) |v| { - const visit = m.w.p.visits[v]; - const layer = m.w.p.at(visit.layer); - const geometry = m.layerGeometry(visit.layer); - const rb = @as(usize, layer.heads.dim) * 2; // the caches are head-major: [kv head][ring][dim] - const global = layer.kind == .global; - const count = if (global) at else @min(at, m.w.c.text.window - 1); - const first = at - count; - const cache = m.cacheOf(visit.cache_slot); - for ([2]u64{ cache.k, cache.v }) |k_or_v| for (0..layer.heads.kv) |head| { - const base = k_or_v + head * geometry.ring * rb; - var pos = first; - while (pos < at) { - const row = pos % geometry.ring; - const n = @min(at - pos, geometry.ring - row); - const dev = base + row * rb; - const src = if (out) dev else saved.buf.ptr + off; - const dst = if (out) saved.buf.ptr + off else dev; - try m.copy(s, dst, src, n * rb); - off += n * rb; - pos += n; - } - }; - } - const conv = m.slotBase() + m.layout.at(0).conv_offset; - const bytes = m.layout.bytes - m.layout.at(0).conv_offset; - try m.copy(s, if (out) saved.buf.ptr + off else conv, if (out) conv else saved.buf.ptr + off, bytes); - } - - pub fn save(m: *const Model, s: cuda.Stream, at: u32) !*Saved { - if (at == 0 or at > m.context) return error.NotAtMark; - const gpa = m.gpa; - const saved = try gpa.create(Saved); - errdefer gpa.destroy(saved); - const lp = m.w.c.text.loop.?; - saved.* = .{ .at = at, .visits = m.w.p.n_visits, .passes = lp.passes, .hidden = m.w.c.text.hidden, .buf = try cuda.DeviceBuffer.alloc(m.d, @intCast(@max(snapshotBytes(m, at), 256))) }; - errdefer saved.buf.free(); - try m.copyState(s, saved, true); - return saved; - } - - pub fn restore(m: *const Model, s: cuda.Stream, saved: *const Saved) !void { - const lp = m.w.c.text.loop.?; - if (saved.visits != m.w.p.n_visits or saved.passes != lp.passes or saved.hidden != m.w.c.text.hidden) - return error.StateOfAnotherModel; - if (saved.at == 0 or saved.at > m.context or saved.buf.len < snapshotBytes(m, saved.at)) return error.BadLoopSnapshot; - try m.copyState(s, saved, false); - } - - pub fn drop(m: *const Model, s: cuda.Stream, saved: *Saved) void { - s.synchronize() catch {}; - saved.buf.free(); - m.gpa.destroy(saved); - } -}; diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig deleted file mode 100644 index 9a0d4cc4b63..00000000000 --- a/zig/src/families/inkling2/loop_math_cuda.zig +++ /dev/null @@ -1,158 +0,0 @@ -//! Inkling 2 Mini loop math (inkling2/loop_math.cu): raw AR, two-bank messages, rank-64 gates and split QKV inputs. -const std = @import("std"); -const cuda = @import("cuda"); - -pub const rank = 64; -pub const max_blocks = 8; -pub const max_queries = 3; - -/// loop_math.cu's ArArgs, field for field. `out[q][row][c]` is FP32 AR output before any controller or RMSNorm. -pub const ArArgs = extern struct { - blocks: [max_blocks]u64 = @splat(0), // BF16 [rows][c], each a completed block state - partial: u64, // BF16 when partial_bf16 != 0, otherwise FP32; always the final AR source - query: u64, // FP32 [nq][c] - out: u64, // FP32 [nq][rows][c] - n_blocks: i32, - partial_bf16: i32, - nq: i32, - rows: i32, - c: i32, - eps: f32, -}; - -pub const Kernels = struct { - mod: cuda.Module, - ar_fn: cuda.Function, - messages_fn: cuda.Function, - gate_fn: cuda.Function, - project_qkv_fn: cuda.Function, - round_bf16_fn: cuda.Function, - - pub fn load(d: *const cuda.Driver) !Kernels { - if (!cuda.kernels.available) return error.BuiltWithoutKernels; - var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop_math); - errdefer mod.unload(); - return .{ - .mod = mod, - .ar_fn = try mod.function("tf_ink2_loop_ar"), - .messages_fn = try mod.function("tf_ink2_loop_messages"), - .gate_fn = try mod.function("tf_ink2_loop_gate"), - .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), - .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), - }; - } - - pub fn unload(k: *Kernels) void { - k.mod.unload(); - k.* = undefined; - } -}; - -fn int(x: anytype) i32 { - return @intCast(x); -} - -fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { - try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); -} - -/// Unnormalized block attention residual. No scratch; nq <= 3 and at most 8 completed blocks plus `partial`. -pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { - if (a.n_blocks < 0 or a.n_blocks > max_blocks or a.nq <= 0 or a.nq > max_queries or a.rows <= 0 or a.c <= 0) - return error.Inkling2LoopArShape; - var args: cuda.Args = .{}; - args.add(a); - try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); -} - -/// Messages: BF16 banks, even/odd qm/kv FP32 queries/output; row-local q/k/v/mlp, no scratch/position/mask/cache. -pub fn messages( - k: *const Kernels, - s: cuda.Stream, - bank0_bf16: u64, - bank1_bf16: u64, - queries_qm_f32: u64, - queries_kv_f32: u64, - out_f32: u64, - rows: usize, - core_layers: usize, - c: usize, - eps: f32, -) !void { - if (rows == 0 or core_layers == 0 or c == 0) return error.Inkling2LoopMessageShape; - var a: cuda.Args = .{}; - for ([_]u64{ bank0_bf16, bank1_bf16, queries_qm_f32, queries_kv_f32, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(core_layers), int(c) }) |v| a.add(v); - a.add(eps); - try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); -} - -/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. -pub fn gate( - k: *const Kernels, - s: cuda.Stream, - state_f32: u64, - message_f32: u64, - down_bf16: u64, - forget_bf16: u64, - gain_bf16: u64, - out_f32: u64, - rows: usize, - c: usize, - eps: f32, -) !void { - if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; - var a: cuda.Args = .{}; - for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(c) }) |v| a.add(v); - a.add(eps); - try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); -} - -/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. -pub fn projectQkv( - k: *const Kernels, - s: cuda.Stream, - u_q: u64, - u_k: u64, - u_v: u64, - wq: u64, - wk: u64, - wv: u64, - raw_q: u64, - raw_k: u64, - raw_v: u64, - rows: usize, - c: usize, - q_width: usize, - kv_width: usize, -) !void { - if (rows == 0 or c == 0 or q_width == 0 or kv_width == 0) return error.Inkling2LoopQkvShape; - var a: cuda.Args = .{}; - for ([_]u64{ u_q, u_k, u_v, wq, wk, wv, raw_q, raw_k, raw_v }) |v| a.add(v); - for ([_]i32{ int(rows), int(c), int(q_width), int(kv_width) }) |v| a.add(v); - try go(k.project_qkv_fn, s, .{ .x = @intCast((rows + 15) / 16), .y = @intCast((@max(q_width, kv_width) + 15) / 16), .z = 3 }, 256, &a); -} - -/// BF16-round FP32 then widen, preserving section 6.3 unlike rowdot(false); in/out may alias, no scratch, n=0 no-op. -pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n: usize) !void { - if (n == 0) return; - var a: cuda.Args = .{}; - for ([_]u64{ in_f32, out_f32 }) |v| a.add(v); - a.add(@as(i64, @intCast(n))); - try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); -} - -test "loop math argument ABI and message role offsets" { - try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); - const c = 2304; - const j = 7; - const row = 3; - const core_layers = 12; - const base = ((row * core_layers + j) * 4) * c; - for ([_]usize{ 0, 1, 2, 3 }, 0..) |role, i| { - const at = base + role * c; - const queries = @as(usize, 2 * j + @as(usize, @intFromBool(i == 2 or i == 3))) * c; - try std.testing.expect(at >= base and queries < 24 * c); - } -} diff --git a/zig/src/families/inkling2/loop_model.zig b/zig/src/families/inkling2/loop_model.zig deleted file mode 100644 index c56b1ce7a2e..00000000000 --- a/zig/src/families/inkling2/loop_model.zig +++ /dev/null @@ -1,464 +0,0 @@ -//! f64 Mini: f32 sums/combine ascend (A12), bf16 experts/acts (A1/A2), f32 F/G (A7), postdot scale (A14); casts round. -const std = @import("std"); -const bf = @import("bf16_round"); - -pub const hidden_size = 2304; -pub const gate_rank = 64; -pub const physical_layers = 24; -pub const core_start = 6; -pub const core_end = 18; -pub const core_layers = core_end - core_start; -pub const num_passes = 3; -pub const visit_count = 48; -pub const message_roles = 4; -pub const rms_eps = 1e-6; - -pub const ShapeError = error{BadShape}; -pub const VisitError = error{BadVisit}; -pub const DriverError = error{ BadShape, BadVisit, BadDriverState, BadSequence }; - -fn narrow32(v: f64) f32 { - return @floatCast(v); -} - -fn widen32(v: f32) f64 { - return @floatCast(v); -} - -/// One round to nearest-even bf16; the returned f64 is exactly that bf16 value. -pub fn bf16(v: f64) f64 { - return bf.bf16(v); -} - -/// rho(x), with an f32 ordered sum of squares and the specified f32 mean/rsqrt/multiply. -pub fn rms(x: []const f64, eps: f64, out: []f64) ShapeError!void { - if (x.len == 0 or out.len != x.len or !std.math.isFinite(eps) or eps < 0) return error.BadShape; - var squares: f32 = 0; - for (x) |v| { - const a = narrow32(v); - squares += a * a; - } - const mean = squares / @as(f32, @floatFromInt(x.len)); - const inverse: f32 = 1 / @sqrt(mean + narrow32(eps)); - for (x, out) |v, *o| o.* = widen32(narrow32(v) * inverse); -} - -/// N_w(x): no bf16 rounding between rho and the weight product, one bf16 rounding at the end. -pub fn weightedRms(x: []const f64, weight: []const f64, eps: f64, out: []f64, scratch: []f64) ShapeError!void { - if (weight.len != x.len or scratch.len != x.len) return error.BadShape; - try rms(x, eps, scratch); - for (scratch, weight, out) |v, w, *o| o.* = bf16(widen32(narrow32(w) * narrow32(v))); -} - -/// binary32(1/sqrt(H)); in particular Mini's value is binary32(1/48), not a double scale. -pub fn residualScale(hidden: usize) ShapeError!f32 { - if (hidden == 0) return error.BadShape; - return narrow32(1 / @sqrt(@as(f64, @floatFromInt(hidden)))); -} - -fn normalizeSources(states: []const f64, partial: []const f64, eps: f64, normalized: []f64) ShapeError!usize { - if (partial.len == 0 or states.len % partial.len != 0) return error.BadShape; - const h = partial.len; - const count = states.len / h + 1; - if (normalized.len != count * h) return error.BadShape; - for (0..count - 1) |i| try rms(states[i * h ..][0..h], eps, normalized[i * h ..][0..h]); - try rms(partial, eps, normalized[(count - 1) * h ..][0..h]); - return count; -} - -fn retrieve(normalized: []const f64, query: []const f64, out: []f64, weights: []f64) ShapeError!void { - if (query.len == 0 or out.len != query.len or normalized.len % query.len != 0) return error.BadShape; - const h = query.len; - const count = normalized.len / h; - if (count == 0 or weights.len != count) return error.BadShape; - const scale = try residualScale(h); - var top: f32 = -std.math.inf(f32); - for (0..count) |i| { - var dot: f32 = 0; - for (query, normalized[i * h ..][0..h]) |q, v| dot += narrow32(q) * narrow32(v); - const logit = dot * scale; - weights[i] = widen32(logit); - top = @max(top, logit); - } - var denominator: f32 = 0; - for (weights) |*w| { - const d = narrow32(w.* - widen32(top)); - const e = @exp(d); - w.* = widen32(e); - denominator += e; - } - @memset(out, 0); - for (0..count) |i| { - const weight = narrow32(weights[i]) / denominator; - for (out, normalized[i * h ..][0..h]) |*o, v| { - const a = narrow32(o.*); - o.* = widen32(a + weight * narrow32(v)); - } - } -} - -/// AR_Q(S,p): states[S][H], queries/out[Q][H] row-major; empty S okay, partial last, normalize before attention. -pub fn attentionResidual(gpa: std.mem.Allocator, states: []const f64, partial: []const f64, queries: []const f64, query_rows: usize, eps: f64, out: []f64) !void { - if (partial.len == 0 or query_rows == 0 or states.len % partial.len != 0) return error.BadShape; - const h = partial.len; - if (queries.len != query_rows * h or out.len != queries.len) return error.BadShape; - const count = states.len / h + 1; - const normalized = try gpa.alloc(f64, count * h); - defer gpa.free(normalized); - const weights = try gpa.alloc(f64, count); - defer gpa.free(weights); - _ = try normalizeSources(states, partial, eps, normalized); - for (0..query_rows) |q| try retrieve(normalized, queries[q * h ..][0..h], out[q * h ..][0..h], weights); -} - -pub const MessageRole = enum(u2) { q = 0, k = 1, v = 2, mlp = 3 }; - -/// The previous pass's B_12 and P_18. No embedding, prelude, or current-pass state is included. -pub const MessageBank = struct { - block: []const f64, - partial: []const f64, -}; - -/// Both checkpoint tensors in their stored row-major layouts: 24 rows by H. -pub const MessageQueries = struct { - q_mlp: []const f64, - kv: []const f64, - - /// Core j uses row 2j for q/k and row 2j+1 for mlp/v, in their respective tensors. - pub fn row(q: MessageQueries, core: usize, role: MessageRole, hidden: usize) ShapeError![]const f64 { - if (core >= core_layers or hidden == 0 or q.q_mlp.len != 2 * core_layers * hidden or q.kv.len != 2 * core_layers * hidden) return error.BadShape; - const odd: usize = @intFromBool(role == .mlp or role == .v); - const row_index = 2 * core + odd; - const source = if (role == .q or role == .mlp) q.q_mlp else q.kv; - return source[row_index * hidden ..][0..hidden]; - } -}; - -fn bankNormalized(gpa: std.mem.Allocator, bank: MessageBank, eps: f64) ![]f64 { - if (bank.block.len == 0 or bank.partial.len != bank.block.len) return error.BadShape; - const normalized = try gpa.alloc(f64, 2 * bank.block.len); - errdefer gpa.free(normalized); - try rms(bank.block, eps, normalized[0..bank.block.len]); - try rms(bank.partial, eps, normalized[bank.block.len..]); - return normalized; -} - -/// One of the 48 cross-pass messages. Its bank values and output are binary32 values held in f64. -pub fn crossPassMessage(gpa: std.mem.Allocator, bank: MessageBank, query: []const f64, eps: f64, out: []f64) !void { - if (query.len != bank.block.len or out.len != query.len) return error.BadShape; - const normalized = try bankNormalized(gpa, bank, eps); - defer gpa.free(normalized); - var weights: [2]f64 = undefined; - try retrieve(normalized, query, out, &weights); -} - -/// All messages in [core layer][q,k,v,mlp][H] order. Queries are shared by passes two and three. -pub fn crossPassMessages(gpa: std.mem.Allocator, bank: MessageBank, queries: MessageQueries, eps: f64, out: []f64) !void { - const h = bank.block.len; - if (h == 0 or bank.partial.len != h or out.len != core_layers * message_roles * h) return error.BadShape; - const normalized = try bankNormalized(gpa, bank, eps); - defer gpa.free(normalized); - var weights: [2]f64 = undefined; - const roles = [_]MessageRole{ .q, .k, .v, .mlp }; - for (0..core_layers) |j| for (roles, 0..) |role, r| { - const query = try queries.row(j, role, h); - const at = (j * message_roles + r) * h; - try retrieve(normalized, query, out[at..][0..h], &weights); - }; -} - -/// Mini's rank-64 controller, represented with smaller ranks too for inexpensive host probes. -pub const GateWeights = struct { - down: []const f64, // [rank][2H], with the h half before the message half - forget: []const f64, // [H][rank] - gain: []const f64, // [H][rank] - rank: usize, -}; - -fn gateDot(row: []const f64, values: []const f64) f32 { - var sum: f32 = 0; - for (row, values) |w, v| sum += narrow32(w) * narrow32(v); - return sum; -} - -/// G(h,m) = (1-f)*h + g*m. The joined norm and bottleneck are bf16; F/G stay f32 (A7). -pub fn messageGate(gpa: std.mem.Allocator, h: []const f64, m: []const f64, w: GateWeights, eps: f64, out: []f64) !void { - const width = h.len; - if (width == 0 or m.len != width or out.len != width or w.rank == 0) return error.BadShape; - if (w.down.len != w.rank * 2 * width or w.forget.len != width * w.rank or w.gain.len != width * w.rank) return error.BadShape; - const joined = try gpa.alloc(f64, 2 * width); - defer gpa.free(joined); - const zeta = try gpa.alloc(f64, w.rank); - defer gpa.free(zeta); - try rms(h, eps, joined[0..width]); - try rms(m, eps, joined[width..]); - for (joined) |*v| v.* = bf16(v.*); - for (0..w.rank) |r| zeta[r] = bf16(widen32(gateDot(w.down[r * 2 * width ..][0 .. 2 * width], joined))); - for (0..width) |i| { - const forget = std.math.tanh(gateDot(w.forget[i * w.rank ..][0..w.rank], zeta)); - const gain = std.math.tanh(gateDot(w.gain[i * w.rank ..][0..w.rank], zeta)); - const keep: f32 = 1 - forget; - const left = keep * narrow32(h[i]); - const right = gain * narrow32(m[i]); - out[i] = widen32(left + right); - } -} - -pub const AttentionKind = enum { sliding, global }; - -/// One row of the fixed 48-visit schedule. cache_slot is visit numbering; reference_slot is HF's. -pub const Visit = struct { - index: u8, - layer: u8, - pass: u8, // zero outside the core, one-based inside it - cache_slot: u8, - reference_slot: u8, - kind: AttentionKind, - boundary: bool, - has_messages: bool, - ar_queries: u8, - attention_sources: u8, - mlp_sources: u8, -}; - -pub fn visit(index: usize) VisitError!Visit { - if (index >= visit_count) return error.BadVisit; - const layer: u8 = if (index < core_start) - @intCast(index) - else if (index < 42) - @intCast(core_start + (index - core_start) % core_layers) - else - @intCast(index - 24); - const pass: u8 = if (index >= 18 and index < 42) @intCast(1 + (index - core_start) / core_layers) else if (index >= core_start and index < 18) 1 else 0; - const reference: u8 = if (pass >= 2) @intCast(24 + (@as(usize, pass) - 2) * core_layers + layer - core_start) else layer; - const global = (@as(usize, layer) + 1) % 6 == 0; - const boundary = layer % 6 == 0; - const blocks: u8 = (layer + 5) / 6; - return .{ - .index = @intCast(index), - .layer = layer, - .pass = pass, - .cache_slot = @intCast(index), - .reference_slot = reference, - .kind = if (global) .global else .sliding, - .boundary = boundary, - .has_messages = pass >= 2, - .ar_queries = if (layer == 0) 0 else if (global) 3 else 1, - .attention_sources = if (layer == 0) 0 else blocks + 1, - .mlp_sources = blocks + 1 + @intFromBool(boundary), - }; -} - -pub const Sources = struct { - blocks: []const f64, // [completed block][H] - partial: []const f64, // p before attention, or unrounded t before the MLP -}; - -/// Residual/block only; caller attention/conv/MoE. Visit: begin->attentionSources->afterAttention->mlpSources->finish. -pub const Driver = struct { - gpa: std.mem.Allocator, - hidden: usize, - storage: []f64, // blocks[4H], prelude snapshot[2H], bank[2H], p[H], t[H] - block_count: usize, - next: usize, - phase: enum { ready, attention, mlp }, - active: Visit, - have_snapshot: bool, - - pub fn init(gpa: std.mem.Allocator, embedding: []const f64) !Driver { - if (embedding.len == 0) return error.BadShape; - const h = embedding.len; - const storage = try gpa.alloc(f64, 10 * h); - @memset(storage, 0); - for (embedding, storage[8 * h .. 9 * h]) |v, *p| p.* = bf16(v); - return .{ .gpa = gpa, .hidden = h, .storage = storage, .block_count = 0, .next = 0, .phase = .ready, .active = undefined, .have_snapshot = false }; - } - - pub fn deinit(d: *Driver) void { - d.gpa.free(d.storage); - d.* = undefined; - } - - fn blocks(d: *Driver) []f64 { - return d.storage[0 .. d.block_count * d.hidden]; - } - - fn partial(d: *Driver) []f64 { - return d.storage[8 * d.hidden .. 9 * d.hidden]; - } - - fn work(d: *Driver) []f64 { - return d.storage[9 * d.hidden .. 10 * d.hidden]; - } - - /// Applies the pass reset before visits 18 and 30, after saving that previous pass's two bank states. - pub fn begin(d: *Driver, index: usize) DriverError!Visit { - if (index >= visit_count) return error.BadVisit; - if (d.phase != .ready or d.next != index) return error.BadSequence; - if (index == core_start) { - if (d.block_count != 1) return error.BadDriverState; - @memcpy(d.storage[4 * d.hidden .. 5 * d.hidden], d.partial()); - @memcpy(d.storage[5 * d.hidden .. 6 * d.hidden], d.blocks()); - d.have_snapshot = true; - } - if (index == 18 or index == 30) { - if (!d.have_snapshot or d.block_count != 3) return error.BadDriverState; - @memcpy(d.storage[6 * d.hidden .. 7 * d.hidden], d.storage[2 * d.hidden .. 3 * d.hidden]); - @memcpy(d.storage[7 * d.hidden .. 8 * d.hidden], d.partial()); - @memcpy(d.partial(), d.storage[4 * d.hidden .. 5 * d.hidden]); - @memcpy(d.storage[0..d.hidden], d.storage[5 * d.hidden .. 6 * d.hidden]); - d.block_count = 1; - } - d.active = visit(index) catch return error.BadVisit; - d.phase = .attention; - return d.active; - } - - pub fn attentionSources(d: *Driver) DriverError!Sources { - if (d.phase != .attention) return error.BadSequence; - return .{ .blocks = d.blocks(), .partial = d.partial() }; - } - - /// Saves p as a completed boundary block, then forms f32 t without rounding it to bf16. - pub fn afterAttention(d: *Driver, attention: []const f64) DriverError!void { - if (d.phase != .attention) return error.BadSequence; - if (attention.len != d.hidden) return error.BadShape; - if (d.active.boundary) { - if (d.block_count == 4) return error.BadDriverState; - @memcpy(d.storage[d.block_count * d.hidden ..][0..d.hidden], d.partial()); - d.block_count += 1; - for (d.work(), attention) |*t, a| t.* = widen32(narrow32(a)); - } else { - for (d.work(), d.partial(), attention) |*t, p, a| t.* = widen32(narrow32(p) + narrow32(a)); - } - d.phase = .mlp; - } - - /// AR's second call sees the extended block list and t, not bf16(t). - pub fn mlpSources(d: *Driver) DriverError!Sources { - if (d.phase != .mlp) return error.BadSequence; - return .{ .blocks = d.blocks(), .partial = d.work() }; - } - - /// p_out = bf16(t + f32(post-MLP-convolution output)); the residual itself is never gated. - pub fn finish(d: *Driver, mlp: []const f64) DriverError!void { - if (d.phase != .mlp) return error.BadSequence; - if (mlp.len != d.hidden) return error.BadShape; - for (d.partial(), d.work(), mlp) |*p, t, o| p.* = bf16(widen32(narrow32(t) + narrow32(o))); - d.phase = .ready; - d.next += 1; - } - - /// Raw B_12 and P_18 of the immediately previous pass; valid until the next pass reset. - pub fn messageBank(d: *Driver) DriverError!MessageBank { - if (d.phase == .ready or !d.active.has_messages) return error.BadDriverState; - return .{ .block = d.storage[6 * d.hidden .. 7 * d.hidden], .partial = d.storage[7 * d.hidden .. 8 * d.hidden] }; - } - - /// The five final AR sources after visit 47: four completed blocks and P_24. - pub fn finalSources(d: *Driver) DriverError!Sources { - if (d.phase != .ready or d.next != visit_count or d.block_count != 4) return error.BadDriverState; - return .{ .blocks = d.blocks(), .partial = d.partial() }; - } -}; - -pub fn e2m1(code: u8) f64 { - const table = [_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; - const magnitude = table[code & 7]; - return std.math.copysign(magnitude, if (code & 8 != 0) @as(f64, -1) else @as(f64, 1)); -} - -/// OCP E4M3FN, including its subnormals and sole NaN encodings. -pub fn e4m3(code: u8) f64 { - const negative = code & 0x80 != 0; - const exponent: u8 = (code >> 3) & 0xf; - const mantissa: u8 = code & 7; - if (exponent == 15 and mantissa == 7) return std.math.nan(f64); - const magnitude = if (exponent == 0) - std.math.ldexp(@as(f64, @floatFromInt(mantissa)), -9) - else - std.math.ldexp(1 + @as(f64, @floatFromInt(mantissa)) / 8, @as(i32, exponent) - 7); - return if (negative) -magnitude else magnitude; -} - -/// A2(a): both source f32 scalars are cast to bf16 before one binary32 division. -pub fn nvfp4OuterFactor(amax: f64, denominator: f64) f64 { - const a = narrow32(bf16(amax)); - const d = narrow32(bf16(denominator)); - return widen32(a / d); -} - -fn nvWeight(code: u8, scale: u8, factor: f32) f64 { - const inner = narrow32(e2m1(code) * e4m3(scale)); // the E2M1*E4M3 product is exact - return bf16(widen32(inner * factor)); -} - -pub fn nvfp4ReferenceWeight(code: u8, scale: u8, amax: f64, denominator: f64) f64 { - return nvWeight(code, scale, narrow32(nvfp4OuterFactor(amax, denominator))); -} - -/// Decode one packed NVFP4 row: low nibble is the even input, one E4M3 scale per 16 inputs. -pub fn nvfp4ReferenceRow(codes: []const u8, scales: []const u8, amax: f64, denominator: f64, out: []f64) ShapeError!void { - if (out.len == 0 or out.len % 16 != 0 or codes.len != out.len / 2 or scales.len != out.len / 16) return error.BadShape; - const factor = narrow32(nvfp4OuterFactor(amax, denominator)); - for (out, 0..) |*v, c| { - const packed_byte = codes[c / 2]; - const code = if (c % 2 == 0) packed_byte & 0xf else packed_byte >> 4; - v.* = nvWeight(code, scales[c / 16], factor); - } -} - -pub fn mxfp8Scale(scale: u8) f64 { - return std.math.ldexp(@as(f64, 1), @as(i32, scale) - 127); -} - -pub fn mxfp8ReferenceWeight(code: u8, scale: u8) f64 { - return bf16(e4m3(code) * mxfp8Scale(scale)); -} - -/// Decode one MXFP8 row using the stored per-row exponent for each group of 32 input columns (A4). -pub fn mxfp8ReferenceRow(codes: []const u8, scales: []const u8, out: []f64) ShapeError!void { - if (out.len == 0 or out.len % 32 != 0 or codes.len != out.len or scales.len != out.len / 32) return error.BadShape; - for (out, codes, 0..) |*v, code, c| v.* = mxfp8ReferenceWeight(code, scales[c / 32]); -} - -/// A bf16 reference GEMM output, with ascending f32 accumulation and no activation quantization. -pub fn expertProjection(weights: []const f64, x: []const f64, rows: usize, out: []f64) ShapeError!void { - if (rows == 0 or x.len == 0 or out.len != rows or weights.len != rows * x.len) return error.BadShape; - for (0..rows) |r| { - var sum: f32 = 0; - for (weights[r * x.len ..][0..x.len], x) |w, v| sum += narrow32(w) * narrow32(v); - out[r] = bf16(widen32(sum)); - } -} - -fn softcap32(x: f32, cap: f32) f32 { - return cap * std.math.tanh(x / cap); -} - -/// bf16(softcap4(g) * sigmoid(g) * softcap25(u)), evaluated left to right in f32. -pub fn expertActivation(gate: f64, up: f64) f64 { - const g = narrow32(gate); - const sigmoid: f32 = 1 / (1 + @exp(-g)); - const act = softcap32(g, 4) * sigmoid * softcap32(narrow32(up), 25); - return bf16(widen32(act)); -} - -/// Combine f32 from zero by ascending id, not route order (A12); expert_outputs [route][H], ids/route_weights [route]. -pub fn combineExperts(expert_count: usize, ids: []const u32, route_weights: []const f64, expert_outputs: []const f64, hidden: usize, out: []f64) ShapeError!void { - if (expert_count == 0 or hidden == 0 or ids.len != route_weights.len or expert_outputs.len != ids.len * hidden or out.len != hidden) return error.BadShape; - @memset(out, 0); - for (0..expert_count) |e| { - var found = false; - for (ids, 0..) |id, r| if (id == e) { - if (found) return error.BadShape; - found = true; - const weight = narrow32(route_weights[r]); - for (out, expert_outputs[r * hidden ..][0..hidden]) |*sum, value| { - const term = weight * narrow32(value); - sum.* = widen32(narrow32(sum.*) + term); - } - } else if (id >= expert_count) return error.BadShape; - } - for (out) |*v| v.* = bf16(v.*); -} diff --git a/zig/src/families/inkling2/loop_model_test.zig b/zig/src/families/inkling2/loop_model_test.zig deleted file mode 100644 index ee0bcf64dab..00000000000 --- a/zig/src/families/inkling2/loop_model_test.zig +++ /dev/null @@ -1,214 +0,0 @@ -const std = @import("std"); -const model = @import("loop_model.zig"); - -const Driver = model.Driver; -const GateWeights = model.GateWeights; -const MessageBank = model.MessageBank; -const MessageQueries = model.MessageQueries; -const attentionResidual = model.attentionResidual; -const bf16 = model.bf16; -const combineExperts = model.combineExperts; -const crossPassMessage = model.crossPassMessage; -const crossPassMessages = model.crossPassMessages; -const e2m1 = model.e2m1; -const e4m3 = model.e4m3; -const expertActivation = model.expertActivation; -const expertProjection = model.expertProjection; -const hidden_size = model.hidden_size; -const messageGate = model.messageGate; -const mxfp8ReferenceRow = model.mxfp8ReferenceRow; -const mxfp8ReferenceWeight = model.mxfp8ReferenceWeight; -const mxfp8Scale = model.mxfp8Scale; -const nvfp4OuterFactor = model.nvfp4OuterFactor; -const nvfp4ReferenceRow = model.nvfp4ReferenceRow; -const nvfp4ReferenceWeight = model.nvfp4ReferenceWeight; -const residualScale = model.residualScale; -const rms = model.rms; -const visit = model.visit; -const visit_count = model.visit_count; -const weightedRms = model.weightedRms; - -fn widen32(v: f32) f64 { - return @floatCast(v); -} - -fn expectClose(actual: f64, expected: f64, tolerance: f64) !void { - try std.testing.expectApproxEqAbs(expected, actual, tolerance); -} - -test "norm scale and weighted RMS's sole final bf16 rounding" { - const x = [_]f64{ 3, 4, 0, 0 }; - var out: [4]f64 = undefined; - var scratch: [4]f64 = undefined; - try rms(&x, 0, &out); - try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.2))), out[0]); - try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.6))), out[1]); - try weightedRms(&x, &.{ 2, 0.5, 1, 1 }, 0, &out, &scratch); - // Hand: rho=[1.2,1.6,0,0], then [2.4,0.8,0,0]. BF16(0.8) is 0.80078125. - try std.testing.expectEqualSlices(f64, &.{ 2.40625, 0.80078125, 0, 0 }, &out); -} - -test "attention residual normalizes values and applies binary32 inverse-root-H after its dot" { - const state = [_]f64{ 3, 4, 0, 0 }; - const partial = [_]f64{ 0, 10, 0, 0 }; - const query = [_]f64{ 1, 0, 0, 0 }; - var out: [4]f64 = undefined; - try attentionResidual(std.testing.allocator, &state, &partial, &query, 1, 0, &out); - // rho(S)=[1.2,1.6,0,0], rho(p)=[0,2,0,0], logits .6 and zero; w0=1/(1+exp(-.6)), output=w0*rho(S)+(1-w0)*rho(p). - const w0 = 1 / (1 + @exp(@as(f64, -0.6))); - try expectClose(out[0], 1.2 * w0, 2e-7); - try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); - try std.testing.expectEqual(@as(u32, 0x3caaaaab), @as(u32, @bitCast(try residualScale(hidden_size)))); -} - -test "message bank normalizes exactly its two states and checkpoint query rows are role-interleaved" { - const a = [_]f64{ 3, 4, 0, 0 }; - const p = [_]f64{ 0, 10, 0, 0 }; - var out: [4]f64 = undefined; - try crossPassMessage(std.testing.allocator, .{ .block = &a, .partial = &p }, &.{ 1, 0, 0, 0 }, 0, &out); - const w0 = 1 / (1 + @exp(@as(f64, -0.6))); - try expectClose(out[0], 1.2 * w0, 2e-7); - try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); - - var q_rows: [24]f64 = undefined; - var kv_rows: [24]f64 = undefined; - for (&q_rows, 0..) |*v, i| v.* = @floatFromInt(i); - for (&kv_rows, 0..) |*v, i| v.* = @floatFromInt(100 + i); - const queries: MessageQueries = .{ .q_mlp = &q_rows, .kv = &kv_rows }; - try std.testing.expectEqual(@as(f64, 4), (try queries.row(2, .q, 1))[0]); - try std.testing.expectEqual(@as(f64, 5), (try queries.row(2, .mlp, 1))[0]); - try std.testing.expectEqual(@as(f64, 104), (try queries.row(2, .k, 1))[0]); - try std.testing.expectEqual(@as(f64, 105), (try queries.row(2, .v, 1))[0]); - - var messages: [visit_count]f64 = undefined; - const one_bank: MessageBank = .{ .block = &.{3}, .partial = &.{4} }; - try crossPassMessages(std.testing.allocator, one_bank, queries, 0, &messages); - for (messages) |message| try std.testing.expectEqual(@as(f64, 1), message); -} - -test "rank gate rounds both joined norms and its down projection before f32 forget and gain" { - const h = [_]f64{ 3, 4, 0, 0 }; - const m = [_]f64{ 0, 10, 0, 0 }; - const weights: GateWeights = .{ - .down = &.{ 0.5, 1.5, 0, 0, 0.5, 1.0078125, 0, 0 }, - .forget = &.{ 1, 0, 0, 0 }, - .gain = &.{ 0, 1, 0, 0 }, - .rank = 1, - }; - var out: [4]f64 = undefined; - try messageGate(std.testing.allocator, &h, &m, weights, 0, &out); - // bf16 rho(h)=[1.203125,1.6015625,0,0], rho(m)=[0,2,0,0]; D*n=5.01953125 rounds to z=5.03125 (else 5.0). - const z: f32 = 5.03125; - const a: f32 = std.math.tanh(z); - const expected0: f32 = (1 - a) * 3; - const expected1: f32 = 4 + a * 10; - try std.testing.expectEqual(@as(f64, widen32(expected0)), out[0]); - try std.testing.expectEqual(@as(f64, widen32(expected1)), out[1]); - try std.testing.expectEqualSlices(f64, &.{ 0, 0 }, out[2..4]); -} - -test "48 visits reset from the prelude and bank B12 plus final partial of only the previous pass" { - var driver = try Driver.init(std.testing.allocator, &.{7}); - defer driver.deinit(); - const zero = [_]f64{0}; - for (0..visit_count) |v| { - _ = try driver.begin(v); - if (v == 6 or v == 18 or v == 30) { - const src = try driver.attentionSources(); - try std.testing.expectEqual(@as(usize, 1), src.blocks.len); - try std.testing.expectEqual(@as(f64, 7), src.blocks[0]); - try std.testing.expectEqual(@as(f64, 21), src.partial[0]); // sum of attention deltas 1...6 - } - if (v == 18) { - const bank = try driver.messageBank(); - try std.testing.expectEqual(@as(f64, 57), bank.block[0]); // sum 7...12 - try std.testing.expectEqual(@as(f64, 93), bank.partial[0]); // sum 13...18 - } else if (v == 30) { - const bank = try driver.messageBank(); - try std.testing.expectEqual(@as(f64, 129), bank.block[0]); // sum 19...24 - try std.testing.expectEqual(@as(f64, 165), bank.partial[0]); // sum 25...30 - } - const delta = [_]f64{@floatFromInt(v + 1)}; - try driver.afterAttention(&delta); - try driver.finish(&zero); - } - const final = try driver.finalSources(); - // Pass 3 supplies the last two core blocks. BF16 rounds the final exact sum 273 to even 272. - try std.testing.expectEqualSlices(f64, &.{ 7, 21, 201, 237 }, final.blocks); - try std.testing.expectEqual(@as(f64, 272), final.partial[0]); -} - -test "visit table preserves layer kinds, AR counts, private visit slots and reference slots" { - const expected = [_]struct { index: usize, layer: u8, pass: u8, reference: u8, messages: bool, ar: u8, attn: u8, mlp: u8 }{ - .{ .index = 0, .layer = 0, .pass = 0, .reference = 0, .messages = false, .ar = 0, .attn = 0, .mlp = 2 }, - .{ .index = 5, .layer = 5, .pass = 0, .reference = 5, .messages = false, .ar = 3, .attn = 2, .mlp = 2 }, - .{ .index = 6, .layer = 6, .pass = 1, .reference = 6, .messages = false, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 17, .layer = 17, .pass = 1, .reference = 17, .messages = false, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 18, .layer = 6, .pass = 2, .reference = 24, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 29, .layer = 17, .pass = 2, .reference = 35, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 30, .layer = 6, .pass = 3, .reference = 36, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, - .{ .index = 41, .layer = 17, .pass = 3, .reference = 47, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, - .{ .index = 42, .layer = 18, .pass = 0, .reference = 18, .messages = false, .ar = 1, .attn = 4, .mlp = 5 }, - .{ .index = 47, .layer = 23, .pass = 0, .reference = 23, .messages = false, .ar = 3, .attn = 5, .mlp = 5 }, - }; - for (expected) |e| { - const v = try visit(e.index); - try std.testing.expectEqual(e.layer, v.layer); - try std.testing.expectEqual(e.pass, v.pass); - try std.testing.expectEqual(e.reference, v.reference_slot); - try std.testing.expectEqual(@as(u8, @intCast(e.index)), v.cache_slot); - try std.testing.expectEqual(e.messages, v.has_messages); - try std.testing.expectEqual(e.ar, v.ar_queries); - try std.testing.expectEqual(e.attn, v.attention_sources); - try std.testing.expectEqual(e.mlp, v.mlp_sources); - } - try std.testing.expectError(error.BadVisit, visit(48)); -} - -test "NVFP4 uses bf16 amax and denominator and low nibble before high nibble" { - // 2689 rounds to bf16 2688, so the reference factor is exactly one rather than 2689/2688. - try std.testing.expectEqual(@as(f64, 1), nvfp4OuterFactor(2689, 2688)); - try std.testing.expectEqual(@as(f64, 1.5), nvfp4ReferenceWeight(3, 0x38, 2689, 2688)); - var row: [16]f64 = undefined; - var codes: [8]u8 = @splat(0); - codes[0] = 0xb3; - const scales = [_]u8{0x38}; - try nvfp4ReferenceRow(&codes, &scales, 2689, 2688, &row); - try std.testing.expectEqual(@as(f64, 1.5), row[0]); - try std.testing.expectEqual(@as(f64, -1.5), row[1]); - try std.testing.expectEqual(@as(f64, 0x1p-9), e4m3(1)); - try std.testing.expectEqual(@as(f64, -0.0), e2m1(8)); -} - -test "MXFP8 exponent is UE8M0 and each stored scale covers one row's 32 inputs" { - try std.testing.expectEqual(@as(f64, 8), mxfp8Scale(130)); - try std.testing.expectEqual(@as(f64, 12), mxfp8ReferenceWeight(0x3c, 130)); // 1.5 * 2^3 - var codes: [64]u8 = @splat(0); - codes[0] = 0x38; // one - codes[31] = 0x3c; // 1.5, still group zero - codes[32] = 0x3c; // group one - var out: [64]f64 = undefined; - try mxfp8ReferenceRow(&codes, &.{ 130, 129 }, &out); - try std.testing.expectEqual(@as(f64, 8), out[0]); - try std.testing.expectEqual(@as(f64, 12), out[31]); - try std.testing.expectEqual(@as(f64, 6), out[32]); -} - -test "expert projection and softcapped SwiGLU have no activation quantization" { - var projected: [2]f64 = undefined; - try expertProjection(&.{ 1, 2, -1, 0.5 }, &.{ 3, 4 }, 2, &projected); - try std.testing.expectEqualSlices(f64, &.{ 11, -1 }, &projected); - const g: f32 = 1; - const expected: f32 = 4 * std.math.tanh(g / 4) * (1 / (1 + @exp(-g))) * (25 * std.math.tanh(g / 25)); - try std.testing.expectEqual(@as(f64, bf16(widen32(expected))), expertActivation(1, 1)); -} - -test "expert sum is ascending id even when f32 route-order association gives another bf16 result" { - const ids = [_]u32{ 2, 1, 0 }; - const weights = [_]f64{ 1, 1, 1 }; - // Route order gives -1 + 2^-24 + 1 = 2^-24 in f32; ascending id gives (1 + 2^-24) - 1 = 0 by a tie to even. - const outputs = [_]f64{ -1, 0x1p-24, 1 }; - var out: [1]f64 = undefined; - try combineExperts(3, &ids, &weights, &outputs, 1, &out); - try std.testing.expectEqual(@as(f64, 0), out[0]); -} diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig deleted file mode 100644 index 7bc6263c0fa..00000000000 --- a/zig/src/families/inkling2/loop_weights.zig +++ /dev/null @@ -1,228 +0,0 @@ -//! Inkling 2 Mini's text checkpoint on one CUDA rank. Every scheduled visit shares these physical layer weights. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const config = @import("config.zig"); -const plan_ = @import("plan.zig"); -const modelopt = @import("modelopt.zig"); - -pub const Controller = struct { - down: u64, - forget: u64, - gain: u64, -}; - -pub const Attention = struct { - wq: u64, - wk: u64, - wv: u64, - wr: u64, - wo: u64, - gate: u64, - sink: u64, - q_scale: u64, - rel_scale: u64, - rel_proj: u64, - k_conv: u64, - v_conv: u64, - k_dynamic: u64 = 0, - v_dynamic: u64 = 0, - /// Sliding layers use entry zero for q, k and v. Global layers use the three separate norms. - norms: [3]u64, -}; - -/// Controller order is q, k, v and MLP, matching loop_math_cuda.messages' message layout. -pub const Layer = struct { - attn: Attention, - attn_conv: u64, - mlp_norm: u64, - mlp_conv: u64, - router: u64, - router_bias: u64, - experts: modelopt.Layer, - controllers: [4]Controller, -}; - -pub const Weights = struct { - gpa: std.mem.Allocator, - c: config.Config, - p: plan_.Plan, - embed: u64 = 0, - embed_norm: u64 = 0, - norm: u64 = 0, - unembed: u64 = 0, - output_query: u64 = 0, - attn_queries: []u64 = &.{}, - mlp_queries: []u64 = &.{}, - cross_qm: u64 = 0, - cross_kv: u64 = 0, - layers: []Layer = &.{}, - buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, - bytes: usize = 0, - - pub fn deinit(w: *Weights) void { - for (w.buffers.items) |*b| b.free(); - w.buffers.deinit(w.gpa); - w.gpa.free(w.layers); - w.gpa.free(w.attn_queries); - w.gpa.free(w.mlp_queries); - w.* = undefined; - } -}; - -/// All text tensors occupy one aligned device arena; expert uploads use this same bump allocator. -const Loader = struct { - w: *Weights, - arena: cuda.DeviceBuffer, - used: usize = 0, - - pub fn alloc(l: *Loader, len: usize) !u64 { - const at = std.mem.alignForward(usize, l.used, 256); - const end = try std.math.add(usize, at, len); - if (end > l.arena.len) return error.LoopWeightsOverflow; - l.used = end; - l.w.bytes += len; - return l.arena.ptr + at; - } - - fn put(l: *Loader, bytes: []const u8) !u64 { - const p = try l.alloc(bytes.len); - try l.arena.upload(p - l.arena.ptr, bytes); - return p; - } - - fn tensor(l: *Loader, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: core.safetensors.DType, dims: []const usize) !u64 { - var buf: [256]u8 = undefined; - const name = try std.fmt.bufPrint(&buf, fmt, args); - return l.put((try ck.expect(name, dtype, dims)).bytes); - } -}; - -fn checkpointBytes(ck: *const core.Checkpoint) !usize { - var total: usize = 0; - for (ck.files.items) |file| for (file.names.keys(), file.names.values()) |name, entry| { - if (!std.mem.startsWith(u8, name, "model.llm.")) continue; - const padded = std.mem.alignForward(usize, entry.end - entry.begin, 256); - total = try std.math.add(usize, total, padded); - }; - return total; -} - -fn controllers(l: *Loader, ck: *core.Checkpoint, c: *const config.Text, i: u32, rank: u32, out: *[4]Controller) !void { - const h: usize = c.hidden; - const names = [4][]const u8{ "attn", "k", "v", "mlp" }; - for (names, out) |role, *g| { - var prefix: [160]u8 = undefined; - const p = try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.controllers.{s}", .{ i, role }); - var down: [224]u8 = undefined; - var forget: [224]u8 = undefined; - var gain: [224]u8 = undefined; - g.* = .{ - .down = try l.put((try ck.expect(try std.fmt.bufPrint(&down, "{s}.down_weight", .{p}), .bf16, &.{ rank, 2 * h })).bytes), - .forget = try l.put((try ck.expect(try std.fmt.bufPrint(&forget, "{s}.forget_weight", .{p}), .bf16, &.{ h, rank })).bytes), - .gain = try l.put((try ck.expect(try std.fmt.bufPrint(&gain, "{s}.gain_weight", .{p}), .bf16, &.{ h, rank })).bytes), - }; - } -} - -/// Load every text tensor, including all four controller triplets and both cross-pass query matrices. -pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, c: *const config.Config, p: plan_.Plan) !Weights { - if (c.text.loop == null) return error.Inkling2LoopRequired; - var formats: [config.max_layers]modelopt.Format = undefined; - for (p.layers[0..c.text.layers], 0..) |layer, k| { - formats[k] = switch (layer.precision) { - .nvfp4 => .nvfp4, - .mxfp8 => .mxfp8, - }; - } - const total = try checkpointBytes(ck); - var arena = try cuda.DeviceBuffer.alloc(d, @max(total, 256)); - var w: Weights = .{ .gpa = gpa, .c = c.*, .p = p }; - errdefer w.deinit(); - w.buffers.append(gpa, arena) catch |err| { - arena.free(); - return err; - }; - w.layers = try gpa.alloc(Layer, c.text.layers); - w.attn_queries = try gpa.alloc(u64, c.text.layers); - w.mlp_queries = try gpa.alloc(u64, c.text.layers); - var l: Loader = .{ .w = &w, .arena = arena }; - const h: usize = c.text.hidden; - w.embed = try l.tensor(ck, "model.llm.embed.weight", .{}, .bf16, &.{ c.text.vocab, h }); - w.embed_norm = try l.tensor(ck, "model.llm.embed_norm.weight", .{}, .bf16, &.{h}); - w.norm = try l.tensor(ck, "model.llm.norm.weight", .{}, .bf16, &.{h}); - w.unembed = try l.tensor(ck, "model.llm.unembed.weight", .{}, .bf16, &.{ c.text.vocab, h }); - w.output_query = try l.tensor(ck, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); - w.cross_qm = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); - w.cross_kv = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); - - for (w.layers, 0..) |*layer, k| { - const i: u32 = @intCast(k); - const L = .{i}; - const hd = c.text.heads(i); - const q: usize = @as(usize, hd.q) * hd.dim; - const kv: usize = @as(usize, hd.kv) * hd.dim; - w.mlp_queries[k] = try l.tensor(ck, "model.llm.attn_res.mlp_queries.{d}", L, .f32, &.{h}); - if (i == 0) { - w.attn_queries[k] = 0; - } else if (config.isGlobal(i)) { - w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{ 3, h }); - } else { - w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{h}); - } - const A = struct { - fn put(loader: *Loader, checkpoint: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dims: []const usize) !u64 { - return loader.tensor(checkpoint, fmt, args, .bf16, dims); - } - }; - layer.attn = .{ - .wq = try A.put(&l, ck, "model.llm.layers.{d}.attn.wq_du.weight", L, &.{ q, h }), - .wk = try A.put(&l, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L, &.{ kv, h }), - .wv = try A.put(&l, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L, &.{ kv, h }), - .wr = try A.put(&l, ck, "model.llm.layers.{d}.attn.wr_du.weight", L, &.{ @as(usize, hd.q) * c.text.d_rel, h }), - .wo = try A.put(&l, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L, &.{ h, q }), - .gate = try A.put(&l, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L, &.{ q, h }), - .sink = try A.put(&l, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L, &.{ hd.q, h }), - .q_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L, &.{ hd.q, hd.dim }), - .rel_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L, &.{ hd.q, c.text.d_rel }), - .rel_proj = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L, &.{ c.text.d_rel, c.text.extent(i) }), - .k_conv = undefined, - .v_conv = undefined, - .norms = undefined, - }; - inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { - const conv = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) - else - try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight", L, &.{ kv, 1, config.conv_taps }); - if (j == 0) layer.attn.k_conv = conv else layer.attn.v_conv = conv; - if (config.isGlobal(i)) { - const dyn = try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight_proj", L, &.{ @as(usize, hd.kv) * config.conv_taps, h }); - if (j == 0) layer.attn.k_dynamic = dyn else layer.attn.v_dynamic = dyn; - } - const norm = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) - else if (j == 0) - try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}) - else - layer.attn.norms[1]; // a sliding layer's k and v share one attn_norm upload - layer.attn.norms[j + 1] = norm; - } - layer.attn.norms[0] = if (config.isGlobal(i)) - try A.put(&l, ck, "model.llm.layers.{d}.q_input_norm.weight", L, &.{h}) - else - layer.attn.norms[1]; - layer.attn_conv = try A.put(&l, ck, "model.llm.layers.{d}.attn_sconv.weight", L, &.{ h, 1, config.conv_taps }); - layer.mlp_norm = try A.put(&l, ck, "model.llm.layers.{d}.mlp_norm.weight", L, &.{h}); - layer.mlp_conv = try A.put(&l, ck, "model.llm.layers.{d}.mlp_sconv.weight", L, &.{ h, 1, config.conv_taps }); - layer.router = try A.put(&l, ck, "model.llm.layers.{d}.mlp.gate.weight", L, &.{ c.text.experts, h }); - layer.router_bias = try l.tensor(ck, "model.llm.layers.{d}.mlp.gate.bias", L, .f32, &.{c.text.experts}); - var prefix: [96]u8 = undefined; - layer.experts = try modelopt.load(&l, ck, try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.mlp.experts.", L), formats[k], c.text.experts, h, c.text.expert_inter); - @memset(&layer.controllers, .{ .down = 0, .forget = 0, .gain = 0 }); - const lp = c.text.loop.?; - if (i >= lp.core_start and i < lp.core_end) try controllers(&l, ck, &c.text, i, lp.gate_rank, &layer.controllers); - } - if (ck.unused() != 0) return error.UnusedCheckpointTensor; - return w; -} diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig deleted file mode 100644 index bef2f7d69ef..00000000000 --- a/zig/tests/cuda/contract_inkling2_loop_math.zig +++ /dev/null @@ -1,479 +0,0 @@ -//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. -const std = @import("std"); -const core = @import("core"); -const ink = @import("inkling2"); -const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_ops_ref.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; -const lm = ink.loop_math_cuda; -pub const eps = ref.eps; -pub const mini_h = 2304; - -/// Exact raw-output checks, with interval references and accumulator simulations for gate 4. -pub fn Checked(comptime T: type) type { - return struct { - const Self = @This(); - inner: ref.Gated(T), - rig: *rig_.Rig = undefined, - msg: [200]u8 = undefined, - - pub fn deinit(self: *Self) void { - self.inner.deinit(); - } - - pub fn kernel(self: *Self) g.Kernel { - self.rig = &self.inner.rig; - return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; - } - - const vt = g.hooks(Self); - - pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { - return self.inner.prepare(shape, fill, seed); - } - - pub fn run(self: *Self) !void { - try self.inner.run(); - } - - pub fn count(self: *Self) usize { - return self.inner.count(); - } - - pub fn reference(self: *Self, want: []f64, mag: []f64) !void { - try self.inner.reference(want, mag); - } - - pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { - try self.inner.bounds(want, mag, allow); - } - - pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { - try self.inner.simulate(acc, order, out); - } - - pub fn check(self: *Self, _: g.Gate) !?[]const u8 { - const a = self.rig.gpu.gpa; - const got = try a.dupe(u8, try self.rig.outputBytes()); - defer a.free(got); - return self.inner.k.check(a, got, &self.msg); - } - }; -} - -pub fn queryScale(cols: usize) ref.Iv { - return if (cols == mini_h) ref.Iv.of(scale(cols)) else ref.Iv.of(@floatFromInt(cols)).rsqrt(); -} - -pub fn softmax(logits: []ref.Iv) void { - var m = logits[0]; - for (logits[1..]) |v| m = .{ .m = @max(m.m, v.m), .lo = @max(m.lo, v.lo), .hi = @max(m.hi, v.hi) }; - var den = ref.Iv.of(0); - for (logits) |*v| { - v.* = v.sub(m).exp(); - den = den.add(v.*); - } - for (logits) |*v| v.* = v.div(den); -} - -/// Irregular integer squares stay exact in FP32 for gate 4, but overflow FP16 and round in every BF16 order. -fn stressBank(i: usize) f32 { - return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; -} - -/// Messages nearly cancel two normalized banks; the unmatched first tap keeps FP16 normalization overflow visible. -fn messageStressBank(bank: usize, col: usize, cols: usize) f32 { - if (bank == 0) return stressBank(col); - if (col == 0) return 0; - return -stressBank((col + 1) % cols); -} - -/// AR cyclically assigns [x, -x, 0] over its sources so zero-query outputs expose RMS-sum differences. -pub fn arStressSource(source: usize, col: usize) f32 { - if (source == 0 and col == 0) return 0; - const value = stressBank(col - col % 3); - return switch ((col + 2 * source) % 3) { - 0 => value, - 1 => -value, - 2 => 0, - else => unreachable, - }; -} - -pub fn close(got: f32, want: f32) bool { - if (std.math.isNan(want)) return std.math.isNan(got); - if (!std.math.isFinite(want)) return got == want; - if (!std.math.isFinite(got)) return false; - const tolerance = 1e-4 * (1.0 + @abs(want)); - return @abs(got - want) <= tolerance; -} - -pub fn bf(x: u16) f32 { - return @floatCast(ref.bf(x)); -} - -pub fn bfRound(x: f32) f32 { - return bf(c.toBf16(x)); -} -pub fn cudaMax(a: f32, b: f32) f32 { - if (std.math.isNan(a)) return b; - if (std.math.isNan(b)) return a; - return @max(a, b); -} - -pub fn sameBf(got: u16, want: u16) bool { - if ((want & 0x7fff) > 0x7f80) return (got & 0x7fff) > 0x7f80; // NaN payload is not part of the math rule - return got == want; -} - -pub fn scale(cols: usize) f32 { - return if (cols == mini_h) 1.0 / 48.0 else 1.0 / @sqrt(@as(f32, @floatFromInt(cols))); -} - -fn warp(v: *[32]f32) f32 { - var offset: usize = 16; - while (offset != 0) : (offset >>= 1) { - const old = v.*; - for (0..32) |lane| v.*[lane] = old[lane] + old[lane ^ offset]; - } - return v.*[0]; -} - -/// The exact lane chains and butterfly tree of loop_math.cu. Terms are fused into each lane's accumulator. -pub fn reduce(a: []const f32, b: []const f32, threads: usize) f32 { - var partial: [32]f32 = @splat(0); - for (0..threads / 32) |w| { - var lanes: [32]f32 = undefined; - for (0..32) |lane| { - const tid = w * 32 + lane; - var sum: f32 = 0; - var i = tid; - while (i < a.len) : (i += threads) sum = @mulAdd(f32, a[i], b[i], sum); - lanes[lane] = sum; - } - partial[w] = warp(&lanes); - } - return warp(&partial); -} - -pub fn fail(msg: []u8, comptime fmt: []const u8, args: anytype) !?[]const u8 { - return try std.fmt.bufPrint(msg, fmt, args); -} - -const message_shapes = [_]c.Shape{ - .{ .rows = 1, .n = 4 * 12 * mini_h, .k = mini_h }, - .{ .rows = 16, .n = 4 * 128, .k = 128 }, - .{ .rows = 2048, .n = 4 * 128, .k = 128 }, -}; - -/// Two normalized banks and the checkpoint's even/odd q,mlp and k,v queries, compared element by element. -pub const Messages = struct { - kern: *const lm.Kernels, - aliased: bool = false, - shape: c.Shape = undefined, - banks: [2][]u16 = .{ &.{}, &.{} }, - queries: [2][]f32 = .{ &.{}, &.{} }, - dev: [5]u64 = @splat(0), - out: u64 = 0, - - pub fn spec(self: *const Messages) c.Spec { - return .{ .name = if (self.aliased) "control: inkling2 loop messages with both previous-pass inputs wired to bank zero" else "inkling2 loop tf_ink2_loop_messages (two normalized banks, post-dot 1/48, four roles)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) message_shapes[0..2] else &message_shapes }; - } - - fn depth(s: c.Shape) usize { - return 2 * ((s.k + 255) / 256 + 10); - } - - pub fn control(self: *const Messages) ?g.Gate { - return if (self.aliased) .shapes else null; - } - - pub fn free(self: *Messages, a: std.mem.Allocator) void { - for (&self.banks) |*x| a.free(x.*); - for (&self.queries) |*x| a.free(x.*); - self.banks = .{ &.{}, &.{} }; - self.queries = .{ &.{}, &.{} }; - } - - pub fn prepare(self: *Messages, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.k == 0 or shape.n % (4 * shape.k) != 0) return false; - self.free(a); - self.shape = shape; - const cols = shape.k; - const layers = shape.n / (4 * cols); - for (&self.banks, 0..) |*x, bank| { - x.* = try a.alloc(u16, shape.rows * cols); - if (fill == .stress) { - for (x.*, 0..) |*v, i| v.* = c.toBf16(messageStressBank(bank, i % cols, cols)); - } else for (x.*) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); - } - for (&self.queries) |*x| { - x.* = try ref.f32s(a, rng, 2 * layers * cols, -0.25, 0.25); - if (fill == .stress) @memset(x.*, 0); - } - if (fill == .nonfinite) { - ref.plant(u16, self.banks[0], shape.rows, cols, ref.asBf); - ref.plant(u16, self.banks[1], shape.rows, cols, ref.asBf); - } - for (self.banks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - for (self.queries, 0..) |x, i| self.dev[2 + i] = try ref.input(rig, x); - self.out = try rig.output(shape.rows * shape.n * 4); - return true; - } - - pub fn run(self: *Messages, rig: *rig_.Rig) !void { - const b1 = if (self.aliased) self.dev[0] else self.dev[1]; - const layers = self.shape.n / (4 * self.shape.k); - try lm.messages(self.kern, rig.s, self.dev[0], b1, self.dev[2], self.dev[3], self.out, self.shape.rows, layers, self.shape.k, eps); - } - - pub fn count(self: *const Messages) usize { - return self.shape.rows * self.shape.n; - } - - pub fn solve(self: *const Messages, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.k; - const layers = self.shape.n / (4 * cols); - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - const later = ref.later(s); - for (0..self.shape.rows) |row| { - var inv: [2]ref.Iv = undefined; - for (0..2) |b| { - for (terms, self.banks[b][row * cols ..][0..cols]) |*t, v| { - const x = ref.Iv.of(ref.bf(v)); - t.* = x.mul(x); - } - inv[b] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); - } - for (0..layers) |j| for (0..4) |role| { - const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; - var logits: [2]ref.Iv = undefined; - for (0..2) |b| { - for (terms, query, self.banks[b][row * cols ..][0..cols]) |*t, q, v| t.* = ref.Iv.of(q).mul(ref.Iv.of(ref.bf(v)).mul(inv[b])); - logits[b] = later.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); - } - softmax(&logits); - for (0..cols) |i| { - var value = ref.Iv.of(0); - for (0..2) |b| { - const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); - value = value.add(logits[b].mul(beta)); - } - const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; - out[at] = value; - } - }; - } - } - - pub fn check(self: *const Messages, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.k; - const layers = self.shape.n / (4 * cols); - const raw0 = try a.alloc(f32, cols); - defer a.free(raw0); - const raw1 = try a.alloc(f32, cols); - defer a.free(raw1); - const beta0 = try a.alloc(f32, cols); - defer a.free(beta0); - const beta1 = try a.alloc(f32, cols); - defer a.free(beta1); - for (0..self.shape.rows) |row| { - for (raw0, self.banks[0][row * cols ..][0..cols]) |*x, v| x.* = bf(v); - for (raw1, self.banks[1][row * cols ..][0..cols]) |*x, v| x.* = bf(v); - const inv0 = 1.0 / @sqrt(reduce(raw0, raw0, 256) / @as(f32, @floatFromInt(cols)) + eps); - const inv1 = 1.0 / @sqrt(reduce(raw1, raw1, 256) / @as(f32, @floatFromInt(cols)) + eps); - for (beta0, raw0) |*x, v| x.* = v * inv0; - for (beta1, raw1) |*x, v| x.* = v * inv1; - for (0..layers) |j| for (0..4) |role| { - const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; - const l0 = reduce(query, beta0, 256) * scale(cols); - const l1 = reduce(query, beta1, 256) * scale(cols); - const m = cudaMax(l0, l1); - const e0 = @exp(l0 - m); - const e1 = @exp(l1 - m); - const den = e0 + e1; - const w0 = e0 / den; - const w1 = e1 / den; - for (0..cols) |i| { - const want = w0 * beta0[i] + w1 * beta1[i]; - const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; - const value = ref.readF32(got, at); - if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); - } - }; - } - return null; - } -}; - -const gate_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 2 * mini_h }, - .{ .rows = 16, .n = mini_h, .k = 2 * mini_h }, - .{ .rows = 2048, .n = 128, .k = 256 }, -}; - -/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. -pub const Gate = struct { - kern: *const lm.Kernels, - wrong_gain: bool = false, - shape: c.Shape = undefined, - h: []f32 = &.{}, - m: []f32 = &.{}, - d: []u16 = &.{}, - f: []u16 = &.{}, - gain: []u16 = &.{}, - dev: [5]u64 = @splat(0), - out: u64 = 0, - - pub fn spec(self: *const Gate) c.Spec { - return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; - } - - fn depth(s: c.Shape) usize { - return (s.k + 255) / 256 + 10 + lm.rank; - } - - pub fn control(self: *const Gate) ?g.Gate { - return if (self.wrong_gain) .shapes else null; - } - - pub fn free(self: *Gate, a: std.mem.Allocator) void { - a.free(self.h); - a.free(self.m); - a.free(self.d); - a.free(self.f); - a.free(self.gain); - self.h = &.{}; - self.m = &.{}; - self.d = &.{}; - self.f = &.{}; - self.gain = &.{}; - } - - pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.k != 2 * shape.n) return false; - self.free(a); - self.shape = shape; - const cols = shape.n; - self.h = try ref.f32s(a, rng, shape.rows * cols, -1, 1); - self.m = try ref.f32s(a, rng, shape.rows * cols, -1, 1); - self.d = try ref.bfs(a, rng, lm.rank * 2 * cols, -0.1, 0.1); - self.f = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); - self.gain = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); - if (fill == .stress) { - for (self.h, 0..) |*v, i| v.* = stressBank(i % cols); - for (self.m, 0..) |*v, i| v.* = stressBank(i % cols); - for (self.d) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - for (self.f) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); - } - if (fill == .nonfinite) { - ref.plant(f32, self.h, shape.rows, cols, ref.asF32); - ref.plant(f32, self.m, shape.rows, cols, ref.asF32); - } - self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; - self.out = try rig.output(shape.rows * cols * 4); - return true; - } - - pub fn run(self: *Gate, rig: *rig_.Rig) !void { - try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); - } - - pub fn count(self: *const Gate) usize { - return self.shape.rows * self.shape.n; - } - - pub fn solve(self: *const Gate, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.n; - const n = try a.alloc(ref.Iv, 2 * cols); - defer a.free(n); - const terms = try a.alloc(ref.Iv, 2 * cols); - defer a.free(terms); - const scratch = try a.alloc(f64, 2 * cols); - defer a.free(scratch); - const zeta = try a.alloc(ref.Iv, lm.rank); - defer a.free(zeta); - const later = ref.later(s); - const zeta_depth = (2 * cols + 31) / 32 + 5; - for (0..self.shape.rows) |row| { - const h = self.h[row * cols ..][0..cols]; - const m = self.m[row * cols ..][0..cols]; - var inv: [2]ref.Iv = undefined; - for (0..2) |b| { - const x = if (b == 0) h else m; - for (terms[0..cols], x) |*t, v| { - const e = ref.Iv.of(v); - t.* = e.mul(e); - } - inv[b] = ref.rms(s.sum(terms[0..cols], depth(self.shape), scratch), cols, eps); - } - for (n[0..cols], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); - for (n[cols..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); - for (0..lm.rank) |r| { - for (terms, n, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); - zeta[r] = later.sum(terms, zeta_depth, scratch).bf(); - } - for (0..cols) |i| { - for (terms[0..lm.rank], zeta, self.f[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); - const forget = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); - for (terms[0..lm.rank], zeta, self.gain[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); - const gain = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); - const keep = ref.Iv.of(1).sub(forget); - const old = keep.mul(ref.Iv.of(h[i])); - const added = gain.mul(ref.Iv.of(m[i])); - out[row * cols + i] = old.add(added); - } - } - } - - pub fn check(self: *const Gate, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.n; - const n = try a.alloc(f32, 2 * cols); - defer a.free(n); - const weights = try a.alloc(f32, 2 * cols); - defer a.free(weights); - const zeta = try a.alloc(f32, lm.rank); - defer a.free(zeta); - const zf = try a.alloc(f32, lm.rank); - defer a.free(zf); - const zg = try a.alloc(f32, lm.rank); - defer a.free(zg); - for (0..self.shape.rows) |row| { - const h = self.h[row * cols ..][0..cols]; - const m = self.m[row * cols ..][0..cols]; - const ih = 1.0 / @sqrt(reduce(h, h, 256) / @as(f32, @floatFromInt(cols)) + eps); - const im = 1.0 / @sqrt(reduce(m, m, 256) / @as(f32, @floatFromInt(cols)) + eps); - for (n[0..cols], h) |*v, x| v.* = bfRound(x * ih); - for (n[cols..], m) |*v, x| v.* = bfRound(x * im); - for (0..lm.rank) |r| { - for (weights, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*v, w| v.* = bf(w); - zeta[r] = bfRound(reduce(weights, n, 256)); - } - for (0..cols) |i| { - for (zf, self.f[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); - for (zg, self.gain[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); - var sf: f32 = 0; - var sg: f32 = 0; - for (0..lm.rank) |r| { - sf = @mulAdd(f32, zf[r], zeta[r], sf); - sg = @mulAdd(f32, zg[r], zeta[r], sg); - } - const forget = std.math.tanh(sf); - const gain = std.math.tanh(sg); - const keep: f32 = 1.0 - forget; - const old: f32 = keep * h[i]; - const added: f32 = gain * m[i]; - const want: f32 = old + added; - const value = ref.readF32(got, row * cols + i); - if (!close(value, want)) return fail(msg, "row {d} col {d}: {e} where {e} is due", .{ row, i, value, want }); - } - } - return null; - } -}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig deleted file mode 100644 index 49bd3ae650e..00000000000 --- a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig +++ /dev/null @@ -1,426 +0,0 @@ -//! Mini QKV projection, raw AR and BF16 tap rounding, with the loop suites' shared registration. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const check = @import("check.zig"); -const ink = @import("inkling2"); -const rig_ = @import("contract_rig.zig"); -const ref = @import("contract_inkling2_ops_ref.zig"); -const base = @import("contract_inkling2_loop_math.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; -const lm = ink.loop_math_cuda; -const K = base.Checked; -const eps = base.eps; -const mini_h = base.mini_h; -const queryScale = base.queryScale; -const softmax = base.softmax; -const arStressSource = base.arStressSource; -const close = base.close; -const bf = base.bf; -const bfRound = base.bfRound; -const cudaMax = base.cudaMax; -const sameBf = base.sameBf; -const scale = base.scale; -const reduce = base.reduce; -const fail = base.fail; -const Messages = base.Messages; -const Gate = base.Gate; -const qkv_shapes = [_]c.Shape{ - .{ .rows = 1, .n = 3072, .k = mini_h }, - .{ .rows = 16, .n = 384, .k = 128 }, - .{ .rows = 2048, .n = 384, .k = 128 }, -}; - -/// Distinct q/k/v rows, with the Small single-input aliasing bug planted as the control. -pub const ProjectQkv = struct { - kern: *const lm.Kernels, - shared_input: bool = false, - shape: c.Shape = undefined, - u: [3][]u16 = .{ &.{}, &.{}, &.{} }, - w: [3][]u16 = .{ &.{}, &.{}, &.{} }, - dev: [6]u64 = @splat(0), - out: [3]u64 = @splat(0), - - pub fn spec(self: *const ProjectQkv) c.Spec { - return .{ .name = if (self.shared_input) "control: Mini split QKV projection using Small's one normalized input for all roles" else "inkling2 loop tf_ink2_loop_project_qkv (distinct normalized q/k/v inputs, unchanged raw layouts)", .accum = .f32, .depth = depth, .out = .bf16, .served = if (self.shared_input) qkv_shapes[0..2] else &qkv_shapes }; - } - - fn depth(s: c.Shape) usize { - return s.k; - } - - pub fn control(self: *const ProjectQkv) ?g.Gate { - return if (self.shared_input) .shapes else null; - } - - pub fn free(self: *ProjectQkv, a: std.mem.Allocator) void { - for (&self.u) |*x| a.free(x.*); - for (&self.w) |*x| a.free(x.*); - self.u = .{ &.{}, &.{}, &.{} }; - self.w = .{ &.{}, &.{}, &.{} }; - } - - pub fn prepare(self: *ProjectQkv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.n % 3 != 0 or shape.k == 0) return false; - self.free(a); - self.shape = shape; - for (&self.u) |*x| x.* = try ref.bfs(a, rng, shape.rows * shape.k, -1, 1); - for (&self.w, 0..) |*x, role| x.* = try ref.bfs(a, rng, (if (role == 0) shape.n else shape.n / 3) * shape.k, -0.1, 0.1); - if (fill == .stress) { - // Mirrored products cancel to eight small FP32 terms; lower precisions lose their large partials. - const half = shape.k / 2; - for (self.u) |bank| for (0..shape.rows) |row| { - const values = bank[row * shape.k ..][0..shape.k]; - for (0..half) |i| { - values[i] = c.toBf16(ref.int(rng, 8, 16)); - values[half + i] = values[i]; - } - if (shape.k % 2 != 0) values[shape.k - 1] = 0; - }; - for (self.w) |bank| for (0..bank.len / shape.k) |row| { - const values = bank[row * shape.k ..][0..shape.k]; - for (0..half) |i| { - const v = ref.int(rng, 8, 16); - values[i] = c.toBf16(v); - values[half + i] = c.toBf16(-v); - } - for (0..@min(8, half)) |i| values[half + i] = c.toBf16(1 - bf(values[i])); - if (shape.k % 2 != 0) values[shape.k - 1] = 0; - }; - } - if (fill == .nonfinite) for (&self.u) |*x| ref.plant(u16, x.*, shape.rows, shape.k, ref.asBf); - for (self.u, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - for (self.w, 0..) |x, i| self.dev[3 + i] = try ref.input(rig, x); - for (0..3) |role| self.out[role] = try rig.output(shape.rows * (if (role == 0) shape.n else shape.n / 3) * 2); - return true; - } - - pub fn run(self: *ProjectQkv, rig: *rig_.Rig) !void { - const k = if (self.shared_input) self.dev[0] else self.dev[1]; - const v = if (self.shared_input) self.dev[0] else self.dev[2]; - try lm.projectQkv(self.kern, rig.s, self.dev[0], k, v, self.dev[3], self.dev[4], self.dev[5], self.out[0], self.out[1], self.out[2], self.shape.rows, self.shape.k, self.shape.n, self.shape.n / 3); - } - - pub fn count(self: *const ProjectQkv) usize { - return self.shape.rows * self.shape.n * 5 / 3; - } - - pub fn solve(self: *const ProjectQkv, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.k; - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - var offset: usize = 0; - for (0..3) |role| { - const width = if (role == 0) self.shape.n else self.shape.n / 3; - for (0..self.shape.rows) |row| for (0..width) |j| { - for (terms, self.u[role][row * cols ..][0..cols], self.w[role][j * cols ..][0..cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(x) * ref.bf(w)); - out[offset + row * width + j] = s.sum(terms, depth(self.shape), scratch).bf(); - }; - offset += self.shape.rows * width; - } - } - - pub fn check(self: *const ProjectQkv, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.k; - const x = try a.alloc(f32, cols); - defer a.free(x); - const w = try a.alloc(f32, cols); - defer a.free(w); - var byte_at: usize = 0; - for (0..3) |role| { - const width = if (role == 0) self.shape.n else self.shape.n / 3; - for (0..self.shape.rows) |row| for (0..width) |j| { - for (x, self.u[role][row * cols ..][0..cols]) |*v, u| v.* = bf(u); - for (w, self.w[role][j * cols ..][0..cols]) |*v, u| v.* = bf(u); - var sum: f32 = 0; - for (0..cols) |i| sum = @mulAdd(f32, x[i], w[i], sum); - const want = c.toBf16(sum); - const at = byte_at + (row * width + j) * 2; - const value = std.mem.readInt(u16, got[at..][0..2], .little); - if (!sameBf(value, want)) return fail(msg, "role {d} row {d} output {d}: {x} where {x} is due", .{ role, row, j, value, want }); - }; - byte_at += self.shape.rows * width * 2; - } - return null; - } -}; - -const ar_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 1 }, - .{ .rows = 16, .n = 128, .k = 3 }, - .{ .rows = 2048, .n = 128, .k = 3 }, -}; - -/// Raw AR before controllers. Two completed blocks plus a partial; control omits the second completed block. -pub const Ar = struct { - kern: *const lm.Kernels, - partial_bf16: bool, - short: bool = false, - shape: c.Shape = undefined, - blocks: [2][]u16 = .{ &.{}, &.{} }, - partial32: []f32 = &.{}, - partial16: []u16 = &.{}, - query: []f32 = &.{}, - dev: [4]u64 = @splat(0), // two blocks, partial, query - out: u64 = 0, - - pub fn spec(self: *const Ar) c.Spec { - return .{ .name = if (self.short) "control: inkling2 loop raw AR omitting its second completed block" else if (self.partial_bf16) "inkling2 loop tf_ink2_loop_ar (BF16 partial, FP32 unnormalized output)" else "inkling2 loop tf_ink2_loop_ar (FP32 partial, FP32 unnormalized output)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.short) ar_shapes[1..2] else &ar_shapes }; - } - - fn depth(s: c.Shape) usize { - return (s.n + 511) / 512 + 10 + 3; - } - - pub fn control(self: *const Ar) ?g.Gate { - return if (self.short) .shapes else null; - } - - pub fn free(self: *Ar, a: std.mem.Allocator) void { - for (&self.blocks) |*x| a.free(x.*); - a.free(self.partial32); - a.free(self.partial16); - a.free(self.query); - self.blocks = .{ &.{}, &.{} }; - self.partial32 = &.{}; - self.partial16 = &.{}; - self.query = &.{}; - } - - pub fn prepare(self: *Ar, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > lm.max_queries) return false; - self.free(a); - self.shape = shape; - for (&self.blocks, 0..) |*x, source| { - x.* = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (x.*, 0..) |*v, i| v.* = c.toBf16(arStressSource(source, i % shape.n)); - } - } - if (self.partial_bf16) { - self.partial16 = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (self.partial16, 0..) |*v, i| v.* = c.toBf16(arStressSource(2, i % shape.n)); - } - self.dev[2] = try ref.input(rig, self.partial16); - } else { - self.partial32 = try ref.f32s(a, rng, shape.rows * shape.n, -1, 1); - if (fill == .stress) { - for (self.partial32, 0..) |*v, i| v.* = arStressSource(2, i % shape.n); - } - self.dev[2] = try ref.input(rig, self.partial32); - } - self.query = try ref.f32s(a, rng, shape.k * shape.n, -0.25, 0.25); - if (fill == .stress) @memset(self.query, 0); - if (fill == .nonfinite) for (&self.blocks) |*x| ref.plant(u16, x.*, shape.rows, shape.n, ref.asBf); - for (self.blocks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); - self.dev[3] = try ref.input(rig, self.query); - self.out = try rig.output(shape.rows * shape.n * shape.k * 4); - return true; - } - - pub fn run(self: *Ar, rig: *rig_.Rig) !void { - var args: lm.ArArgs = .{ .partial = self.dev[2], .query = self.dev[3], .out = self.out, .n_blocks = if (self.short) 1 else 2, .partial_bf16 = @intFromBool(self.partial_bf16), .nq = @intCast(self.shape.k), .rows = @intCast(self.shape.rows), .c = @intCast(self.shape.n), .eps = eps }; - args.blocks[0] = self.dev[0]; - args.blocks[1] = self.dev[1]; - try lm.ar(self.kern, rig.s, args); - } - - pub fn count(self: *const Ar) usize { - return self.shape.rows * self.shape.n * self.shape.k; - } - - fn entry(self: *const Ar, source: usize, row: usize, col: usize) f32 { - const at = row * self.shape.n + col; - return if (source < 2) bf(self.blocks[source][at]) else if (self.partial_bf16) bf(self.partial16[at]) else self.partial32[at]; - } - - pub fn solve(self: *const Ar, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { - const cols = self.shape.n; - const terms = try a.alloc(ref.Iv, cols); - defer a.free(terms); - const scratch = try a.alloc(f64, cols); - defer a.free(scratch); - for (0..self.shape.rows) |row| { - var inv: [3]ref.Iv = undefined; - for (0..3) |j| { - for (terms, 0..) |*t, i| { - const x = ref.Iv.of(self.entry(j, row, i)); - t.* = x.mul(x); - } - inv[j] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); - } - for (0..self.shape.k) |q| { - var logits: [3]ref.Iv = undefined; - for (0..3) |j| { - for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]).mul(ref.Iv.of(self.query[q * cols + i])); - logits[j] = s.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); - } - softmax(&logits); - for (0..cols) |i| { - var value = ref.Iv.of(0); - for (0..3) |j| { - const beta = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]); - value = value.add(logits[j].mul(beta)); - } - out[(q * self.shape.rows + row) * cols + i] = value; - } - } - } - } - - pub fn check(self: *const Ar, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - const cols = self.shape.n; - const sources = 3; - const raw = try a.alloc(f32, cols); - defer a.free(raw); - const beta = try a.alloc(f32, sources * cols); - defer a.free(beta); - const weights = try a.alloc(f32, sources); - defer a.free(weights); - for (0..self.shape.rows) |row| { - var invs: [3]f32 = undefined; - for (0..sources) |j| { - for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); - invs[j] = 1.0 / @sqrt(reduce(raw, raw, 512) / @as(f32, @floatFromInt(cols)) + eps); - for (beta[j * cols ..][0..cols], raw) |*v, x| v.* = x * invs[j]; - } - for (0..self.shape.k) |q| { - var logits: [3]f32 = undefined; - var m = -std.math.inf(f32); - for (0..sources) |j| { - const query = self.query[q * cols ..][0..cols]; - logits[j] = reduce(query, beta[j * cols ..][0..cols], 512) * scale(cols); - m = cudaMax(m, logits[j]); - } - var den: f32 = 0; - for (0..sources) |j| { - weights[j] = @exp(logits[j] - m); - den += weights[j]; - } - for (0..sources) |j| weights[j] /= den; - for (0..cols) |i| { - var want: f32 = 0; - for (0..sources) |j| want = @mulAdd(f32, weights[j], beta[j * cols + i], want); - const at = (q * self.shape.rows + row) * cols + i; - const value = ref.readF32(got, at); - if (!close(value, want)) return fail(msg, "query {d} row {d} col {d}: {e} where {e} is due", .{ q, row, i, value, want }); - } - } - } - return null; - } -}; - -test "AR normalizes each FP32 query term before reduction and scales after its dot" { - const source = [_]f32{ - @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), - @bitCast(@as(u32, 0x40400001)), 0, - }; - const query = [_]f32{ - @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), - @bitCast(@as(u32, 0xc0000001)), 0, - }; - const inv: f32 = @bitCast(@as(u32, 0x3f800001)); - var normalized: [4]f32 = undefined; - for (&normalized, source) |*v, x| v.* = x * inv; - const dot = reduce(&query, &normalized, 512); - const old = reduce(&query, &source, 512) * inv * scale(source.len); - const scaled = dot * scale(source.len); - try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); - try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); -} - -const round_shapes = [_]c.Shape{ - .{ .rows = 1, .n = mini_h, .k = 1 }, - .{ .rows = 2048, .n = 32, .k = 1 }, -}; - -/// Dynamic taps' required BF16 storage rounding, followed by exact widening for the FP32 convolution. -pub const RoundBf16 = struct { - kern: *const lm.Kernels, - short: bool = false, - shape: c.Shape = undefined, - x: []f32 = &.{}, - dev: u64 = 0, - out: u64 = 0, - - pub fn spec(self: *const RoundBf16) c.Spec { - return .{ .name = if (self.short) "control: inkling2 loop dynamic taps leave the final value unrounded" else "inkling2 loop tf_ink2_loop_round_bf16 (global dynamic taps, BF16 then FP32)", .accum = .none, .depth = ref.noSums, .out = .f32, .served = if (self.short) round_shapes[0..1] else &round_shapes }; - } - - pub fn control(self: *const RoundBf16) ?g.Gate { - return if (self.short) .shapes else null; - } - - pub fn free(self: *RoundBf16, a: std.mem.Allocator) void { - a.free(self.x); - self.x = &.{}; - } - - pub fn prepare(self: *RoundBf16, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n == 0) return false; - self.free(a); - self.shape = shape; - self.x = try ref.f32s(a, rng, shape.rows * shape.n, -32, 32); - if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); - self.dev = try ref.input(rig, self.x); - self.out = try rig.output(self.x.len * 4); - return true; - } - - pub fn run(self: *RoundBf16, rig: *rig_.Rig) !void { - try lm.roundBf16(self.kern, rig.s, self.dev, self.out, self.x.len - @intFromBool(self.short)); - } - - pub fn count(self: *const RoundBf16) usize { - return self.x.len; - } - - pub fn solve(self: *const RoundBf16, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { - for (out, self.x) |*o, x| o.* = ref.Iv.of(x).bf(); - } - - pub fn check(self: *const RoundBf16, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { - for (self.x, 0..) |x, i| { - const want = bfRound(x); - const value = ref.readF32(got, i); - if (!ref.sameF32(value, want)) return fail(msg, "tap {d}: {e} where {e} is due", .{ i, value, want }); - } - return null; - } -}; - -pub const Set = struct { - k: lm.Kernels = undefined, - loaded: bool = false, - messages: [2]K(Messages) = undefined, - gates: [2]K(Gate) = undefined, - qkvs: [2]K(ProjectQkv) = undefined, - ars: [3]K(Ar) = undefined, - rounds: [2]K(RoundBf16) = undefined, - - pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { - set.k = try lm.Kernels.load(gpu.d); - set.loaded = true; - const k = &set.k; - const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; - for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; - for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; - for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; - for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; - for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; - inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); - } - - pub fn deinit(set: *Set) void { - if (!set.loaded) return; - inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| x.deinit(); - set.k.unload(); - set.loaded = false; - } -}; diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 64f03dc859b..e76c2d74121 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -49,7 +49,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; From f6fa4b1d2665706f44db12ba489739303be3837b Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:19 +0800 Subject: [PATCH 82/84] inkling2 cuda: run main's cross-prompt resume check against #4441's engine Ports jschmied's crossPrompt check (c79a58f07) from origin/main's serving tests. --- zig/tests/cuda/inkling2_serving_tests.zig | 50 +++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig index 45a2d1b2ed1..d6aa3321cc0 100644 --- a/zig/tests/cuda/inkling2_serving_tests.zig +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -113,6 +113,54 @@ fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sa try sameTrace(fresh, &resumed); } +/// A keeps states at 14 and 39; B resumes A's 14, keeps its 39 and decodes; A resumed at 39 must equal fresh A. +fn crossPrompt(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { + const Keeper = struct { + b: *Mini, + saved: [2]?*Saved = .{ null, null }, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved[@intFromBool(mark != 14)] = k.b.saveState(s, mark) catch null; + } + }; + const t = loaded.target; + const b = loaded.backend; + const a = ids[0..40]; + var other: [40]u32 = undefined; + @memcpy(other[0..14], ids[0..14]); + @memcpy(other[14..], ids[500..526]); + var fresh = try trace(gpu, loaded, a, null, 8, false, .{}); + defer fresh.deinit(gpu.gpa); + var ka: Keeper = .{ .b = t }; + defer for (ka.saved) |x| if (x) |y| t.dropState(y); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-a", .prompt = a, .max_new = 1, .reuse = .{ .marks = &.{ 14, 39 } } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &ka, .at = Keeper.at }; + try b.prefill(&s); + } + var kb: Keeper = .{ .b = t }; + defer for (kb.saved) |x| if (x) |y| t.dropState(y); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-b", .prompt = &other, .max_new = 8, .reuse = .{ .saved = ka.saved[0] orelse return error.MiniSnapshotNotSaved, .at = 14, .marks = &.{39} } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &kb, .at = Keeper.at }; + try b.prefill(&s); + if (s.cached != 14 or kb.saved[1] == null) return error.MiniSnapshotNotRestored; + var h = try b.first(&s, other.len); + for (0..6) |i| h = try b.queue(&s, .{ .handle = h }, other.len + i + 1); + } + var resumed = try trace(gpu, loaded, a, null, 8, false, .{ .saved = ka.saved[1] orelse return error.MiniSnapshotNotSaved, .at = 39 }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != 39 or resumed.failed) return error.MiniSnapshotNotRestored; + sameTrace(&fresh, &resumed) catch |err| { + std.debug.print("RESULT mini-serving cross-prompt resume mismatch={s} fresh={any} resumed={any}\n", .{ @errorName(err), fresh.ids, resumed.ids }); + return err; + }; +} + fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { var fresh = try trace(gpu, loaded, prompt, sampling, 8, false, .{}); @@ -179,6 +227,8 @@ pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { check.pass("Mini CUDA serving matches the host reference token for token", .{}); try freshAndResumed(gpu, &loaded, ids[0..2309]); check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens", .{}); + try crossPrompt(gpu, &loaded, ids); + check.pass("Mini CUDA a state resumed after another prompt resumed its prefix equals the fresh prompt", .{}); try admission(gpu, &loaded, ids[0..257], ids[17..1042]); check.pass("Mini CUDA two lanes decode together in shared rounds without changing tokens; a third waits", .{}); } From 22fb3250ec2c8c2ee585f7fba4edd53d8294acc2 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:29:19 +0800 Subject: [PATCH 83/84] changelog: #188 keeps main's Metal fixes and the cross-prompt check --- .../188-inkling-2-mini-runs-whole-on-our-spark-g.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md index 55db8dce52e..73da616c6de 100644 --- a/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md +++ b/changelog.d/188-inkling-2-mini-runs-whole-on-our-spark-g.md @@ -2,9 +2,15 @@ - Merges Ash's #4387 and jschmied's C1 (#4364), C3 (#4365) and H2 + C4 (#4441) with their commits. `inkling2_loop` is now served by #4441's engine (graphs, fused input projections, every stream's rows in one forward); #4387's - separate loop engine is removed, so CUDA no longer advertises structured output it refused. -- #4387's serving checks (device draws against host selection, fresh against resumed prompts, two streams in shared - rounds against each alone) run against #4441's engine. Copy drafting is not checked: that engine has no draft path yet. + separate loop engine, which the merge of `main` brought back, stays removed, so CUDA no longer advertises structured + output it refused. +- #4387's serving checks (device draws against host selection, fresh against resumed prompts, a prompt resumed after + another prompt resumed its prefix, two streams in shared rounds against each alone) run against #4441's engine. + Copy drafting is not checked: that engine has no draft path yet. +- The merge of `main` keeps its Metal Mini fixes: a window's grammar masks step by the padded vocabulary's words; a + snapshot copies each key head's live rows, so it restores into a cache of another capacity; norm binds where `sp_norm` + reads; a later stream of a shared forward reads its relative rows where prep wrote them; and the real-checkpoint + serving test draws the first token before its row. - `docs/recipes/inkling-2-mini-cuda/run-script.sh` runs the original checkpoint on TOP's GB10: the serving checks, the float64 reference and its planted control, then first-token time, prompt speed, decode speed, memory (`/proc/meminfo`) and the bandwidth limit at 1 and 4 streams; 4 streams must give 1.5 times one stream's total. From 29f8128eb0ccbe1d3293215c9a4f845c33e182e5 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:49:24 +0800 Subject: [PATCH 84/84] docs: Inkling 2 Mini CUDA receipt from the exact-head job top-a96a7d63bedf at 22fb3250e --- docs/recipes/inkling-2-mini-cuda/README.md | 31 +++++++++++----------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/docs/recipes/inkling-2-mini-cuda/README.md b/docs/recipes/inkling-2-mini-cuda/README.md index 3ce3cb1dbfe..c473df7e183 100644 --- a/docs/recipes/inkling-2-mini-cuda/README.md +++ b/docs/recipes/inkling-2-mini-cuda/README.md @@ -17,24 +17,25 @@ checkpoint's headers) over 273 GB/s. ## Receipt: TOP's GB10, one capped run -Job `top-0b05213c9f06` at `4a5089e70`, `--context 8192`, greedy, 256 tokens, 3 reps, medians; the build ran first, then +Job `top-a96a7d63bedf` at `22fb3250e`, `--context 8192`, greedy, 256 tokens, 3 reps, medians; the build ran first, then every check and both levels inside `timeout 600`. This is one run with these settings, not a benchmark. | Streams | First token (code / chat) | Prompt (code) | Decode a stream (code / chat) | Total decode (code / chat) | Failed | |---|---|---|---|---|---| -| 1 | 0.075 s / 0.037 s | 199.4 tok/s | 32.9 / 32.8 tok/s | 32.9 / 32.8 tok/s | 0 | -| 4 | 0.186 s / 0.091 s | 83.7 tok/s | 29.8 / 29.8 tok/s | 117.9 / 118.8 tok/s | 0 | +| 1 | 0.076 s / 0.097 s | 197.4 tok/s | 32.9 / 33.1 tok/s | 32.9 / 33.1 tok/s | 0 | +| 4 | 0.187 s / 0.207 s | 83.4 tok/s | 29.9 / 30.3 tok/s | 117.7 / 121.1 tok/s | 0 | -The 4-stream gate takes each level's better prompt: 118.8 over 32.9 tok/s, 3.61x. Every stream sends the same prompt, +The 4-stream gate takes each level's better prompt: 121.1 over 33.1 tok/s, 3.66x. Every stream sends the same prompt, so the four streams route to the same experts; mixed traffic may give a lower 4-stream rate. Checks in the same job: the CUDA engine matched the host reference token for token, fresh and resumed prompts gave -identical logits and tokens, and two lanes in shared rounds kept their tokens; 0 of 32 greedy tokens differed from -the float64 reference (smallest reference margin 0.11), and its planted control (no messages) differed at 6. The -kernel contract passed gates 1-4 on all 5 loop kernels with both planted controls red. +identical logits and tokens, a prompt resumed after another prompt resumed its prefix equalled the fresh one, and two +lanes in shared rounds kept their tokens; 0 of 32 greedy tokens differed from the float64 reference (smallest reference +margin 0.11), and its planted control (no messages) differed at 6. The kernel contract passed gates 1-4 on all 5 loop +kernels with both planted controls red. -Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 11.1 GiB before the server, -31.8 GiB with Mini loaded for 4 streams and 32.2 GiB after both levels; the server held 20.0 GiB of GPU memory +Memory, sampled after each step (not process peaks): host used (`/proc/meminfo`) was 12.3 GiB before the server, +33.5 GiB with Mini loaded for 4 streams and 33.4 GiB after both levels; the server held 20.0 GiB of GPU memory (`nvidia-smi`). Bandwidth limit: a decoded token reads about 5.55 GB of weights (core layers 3 passes, 8 of 128 experts a visit, the @@ -52,12 +53,12 @@ is the receipt above. | | TensorFold (bf16 safetensors) | llama.cpp (UD-Q4_K_M) | |---|---|---| | Weights on disk | 20,161,820,584 bytes (18.78 GiB, with the 635,801,416-byte draft head `mtp.safetensors`) | 16,610,544,608 bytes (15.47 GiB) | -| Decode, 1 stream (code / chat) | 32.9 / 32.8 tok/s | 38.8 / 39.1 tok/s | -| Decode total, 4 streams (code / chat) | 117.9 / 118.8 tok/s | 85.9 / 87.6 tok/s | -| 4 streams over 1 | 3.61x | 2.24x | -| First token, 1 stream (code / chat) | 0.075 s / 0.037 s | 0.067 s (slot cache hit) / 0.130 s | -| Prompt, 1 stream (code, uncached) | 199.4 tok/s | 106.4 tok/s (15 tokens / one-token response time; median of 3) | -| Prompt, 4 streams (code) | 83.7 tok/s | 43.0 tok/s (cold requests only) | +| Decode, 1 stream (code / chat) | 32.9 / 33.1 tok/s | 38.8 / 39.1 tok/s | +| Decode total, 4 streams (code / chat) | 117.7 / 121.1 tok/s | 85.9 / 87.6 tok/s | +| 4 streams over 1 | 3.66x | 2.24x | +| First token, 1 stream (code / chat) | 0.076 s / 0.097 s | 0.067 s (slot cache hit) / 0.130 s | +| Prompt, 1 stream (code, uncached) | 197.4 tok/s | 106.4 tok/s (15 tokens / one-token response time; median of 3) | +| Prompt, 4 streams (code) | 83.4 tok/s | 43.0 tok/s (cold requests only) | | Memory, server loaded | 20.0 GiB GPU (`nvidia-smi`) | 18.1 GiB GPU (`nvidia-smi`); peak 20.57 GiB: 18.18 GPU + 2.38 resident | | Continuation text / teacher-forced tokens vs float64 reference | 32 of 32 token picks | Same free-running text when re-tokenized / 31 of 32 token picks (differs at 5) |