From a89a509fe0aa18a43114afbc37c7c4e4e31f3da6 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Fri, 20 Nov 2026 19:24:48 +1100 Subject: [PATCH 01/27] inkling2: grouped expert and vision kernels under the contract --- zig/build/cuda_kernels.zig | 4 ++-- zig/src/cuda/kernels.zig | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index cc0c00e15e5..86222efd6f9 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -167,12 +167,12 @@ 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_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) - .{ .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 .{ .name = "exl3_experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // exl3/experts.cu's device code, tensorfold_exl3_experts diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index e90fda57074..710eb26bfa8 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -117,12 +117,12 @@ 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_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; pub const ricursive_prep: []const u8 = if (available) &Blob("fatbin_ricursive_prep").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 &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; From 196ec3020381434f9f02eab1a4c8527a0151e577 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 21:19:51 +1100 Subject: [PATCH 02/27] inkling2: size the vision projector from the config --- zig/src/families/inkling2/vision.zig | 67 +++++++++++++++++++--------- 1 file changed, 46 insertions(+), 21 deletions(-) diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig index eced25b1697..b472dfd78db 100644 --- a/zig/src/families/inkling2/vision.zig +++ b/zig/src/families/inkling2/vision.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); const image = @import("image.zig"); +const config = @import("config.zig"); const vit = cuda.vit; @@ -11,8 +12,6 @@ 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."; @@ -75,9 +74,9 @@ const Layer = struct { ln1_w: u64, ln1_b: u64, qkv_w: u64, qkv_b: u64, out_w: u6 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 { +pub fn scratchBytes(v: config.Vision, 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); + return rows * row_bytes + @as(u64, tokens) * v.proj_hidden * 2 + (32 << 20); } /// The tower's weights and scratch on one GPU. @@ -89,14 +88,16 @@ pub const Tower = struct { g: vit.Gemms, bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, max_tokens: u32, + proj_inter: u32, // config.json's projection_hidden_dim + hidden: u32, // the decoder's width, config.json's text_hidden_size 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 + proj_in: u64 = 0, // [proj_inter][4096], no bias + proj_out: u64 = 0, // [hidden][proj_inter], 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) @@ -134,7 +135,7 @@ pub const Tower = struct { } /// 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 { + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, v: config.Vision, max_tokens: u32) !*Tower { if (max_tokens == 0) return error.ImageTokens; const t = try gpa.create(Tower); errdefer gpa.destroy(t); @@ -142,7 +143,7 @@ pub const Tower = struct { 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 }; + t.* = .{ .gpa = gpa, .d = d, .k = k, .vk = vk, .g = try vit.Gemms.init(gpa, d), .max_tokens = max_tokens, .proj_inter = v.proj_hidden, .hidden = v.text_hidden }; errdefer { for (t.bufs.items) |*b| b.free(); t.bufs.deinit(gpa); @@ -156,8 +157,8 @@ pub const Tower = struct { 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 }); + t.proj_in = try t.get(&ck, "model.visual.proj_in.weight", &.{ t.proj_inter, merged }); + t.proj_out = try t.get(&ck, "model.visual.proj_out.weight", &.{ t.hidden, t.proj_inter }); const w = try gpa.alloc(u8, 3 * width * width * 2); defer gpa.free(w); for (&t.layers, 0..) |*l, i| { @@ -201,15 +202,15 @@ pub const Tower = struct { 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); + t.p1 = try t.alloc(@as(usize, max_tokens) * t.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 { + pub fn bytesFor(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, v: config.Vision, max_tokens: u32) !u64 { var ck = try openTower(gpa, io, dir); defer core.checkpoint.cache.close(&ck); - var total: u64 = scratchBytes(max_tokens); + var total: u64 = scratchBytes(v, max_tokens); for (ck.files.items) |*f| for (f.names.keys()) |name| { total += f.get(name).?.bytes.len; }; @@ -273,9 +274,9 @@ pub const Tower = struct { 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); + try t.g.run(s, t.x + width * 2, t.proj_in, t.p1, T, t.proj_inter, merged, .bf16); + try t.vk.pointwise(s, t.p1, null, t.p1, T * t.proj_inter, .gelu); + try t.g.run(s, t.p1, t.proj_out, out, T, t.hidden, t.proj_inter, .bf16); } fn layer(t: *Tower, s: cuda.Stream, l: Layer, R: usize) !void { @@ -348,12 +349,17 @@ pub fn cut(sp: Span, lo: usize, hi: usize) ?Copy { return .{ .dst = @intCast(a - lo), .src = @intCast(sp.row + (a - sp.at)), .n = @intCast(b - a) }; } +/// A copy's bytes for bf16 rows `hidden` wide: the offset into the pass, the offset into the image rows, the length. +pub fn copyBytes(c: Copy, hidden: u32) [3]u64 { + const row: u64 = @as(u64, hidden) * 2; + return .{ c.dst * row, c.src * row, c.n * row }; +} + /// 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 { +pub fn splice(d: *const cuda.Driver, s: cuda.Stream, hidden: u32, 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"); + const b = copyBytes(cut(sp, lo, hi) orelse continue, hidden); + try d.check(d.api.cuMemcpyDtoDAsync_v2(x + b[0], rows + b[1], b[2], s.handle), "cuMemcpyDtoDAsync"); } } @@ -394,7 +400,26 @@ test "chunked passes give every placeholder the row masked_scatter gives it" { } } +/// Inkling 2 Small's vision_config and Mini's, whose decoder is 2304 wide. +fn testVision(text_hidden: u32) config.Vision { + return .{ .hidden = width, .layers = depth, .heads = heads, .patch = image.patch, .merge = image.merge, .grid = image.grid, .mlp_ratio = 4, .proj_hidden = 4096, .text_hidden = text_hidden }; +} + test "scratch for the default limit stays under 256 MiB" { - try std.testing.expect(scratchBytes(default_tokens) < 256 << 20); + try std.testing.expect(scratchBytes(testVision(4608), default_tokens) < 256 << 20); try std.testing.expectEqual(@as(u32, 36864), attn_smem); } + +test "the splice copies rows as wide as the config's decoder, Small's 4608 and Mini's 2304" { + const sp: Span = .{ .at = 3, .n = 5, .row = 7 }; + for ([_]u32{ 4608, 2304 }) |h| { + const v = testVision(h); + const b = copyBytes(cut(sp, 4, 6).?, v.text_hidden); + try std.testing.expectEqual([3]u64{ 0, 8 * @as(u64, h) * 2, 2 * @as(u64, h) * 2 }, b); + } + // the projector's scratch row is projection_hidden_dim wide (4096 in both releases) + var v = testVision(2304); + const wide = scratchBytes(v, 16); + v.proj_hidden = 2048; + try std.testing.expectEqual(@as(u64, 16 * 2048 * 2), wide - scratchBytes(v, 16)); +} From 0150b8d2f881162c5ac0c4d9608f998bf27929af Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 21:23:49 +1100 Subject: [PATCH 03/27] inkling2: refuse expert bit widths the grouped kernels cannot decode --- zig/src/families/inkling2/experts.zig | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/experts.zig b/zig/src/families/inkling2/experts.zig index 2d0d017d95f..d3e8dd8d636 100644 --- a/zig/src/families/inkling2/experts.zig +++ b/zig/src/families/inkling2/experts.zig @@ -8,6 +8,9 @@ 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 }; +/// The least and most half-bit widths (k2) among a layer's expert tensors, as the loader read them. +pub const Bits = struct { lo: u32, hi: u32 }; + /// 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). @@ -66,12 +69,13 @@ fn itemsAt(l: ex.Layer, sc: ex.Scratch) u64 { } /// 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 { +pub fn run(e: *const Kernels, k: *const ops.Kernels, s: cuda.Stream, l: ex.Layer, caps: Caps, bits: Bits, 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; + if (bits.lo < 2 or bits.hi > 8 or bits.lo > bits.hi) return error.BadExpertBits; // the kernels decode 1 to 4 bits const g_sk = try ex.plan(d, w, true); const d_sk = try ex.plan(w, d, false); const p = rows * slots; @@ -146,3 +150,16 @@ test "experts: the item list sits past main's scratch and holds a 2,048-row call // 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); } + +test "experts: run refuses expert widths outside the kernels' 1 to 4 bits on the host" { + var l = std.mem.zeroes(ex.Layer); + l.experts = 384; + l.dims = 4608; + l.width = 1152; + l.codebook = .mul1; + const sc = try ex.scratch(0, l, 4, 8); + const caps: Caps = .{ .gate = 0, .up = 0 }; + for ([_]Bits{ .{ .lo = 1, .hi = 8 }, .{ .lo = 2, .hi = 9 }, .{ .lo = 6, .hi = 4 } }) |b| { + try std.testing.expectError(error.BadExpertBits, run(undefined, undefined, undefined, l, caps, b, 0, 0, .f16, 0, 0, 4, 0, sc)); + } +} From 14fa28de91442e5f10b1f6565fe9f570904180c1 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 21:27:39 +1100 Subject: [PATCH 04/27] inkling2: test the expert and image refusals --- zig/src/families/inkling2/experts.zig | 14 ++++++++++++++ zig/src/families/inkling2/vision.zig | 27 +++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/zig/src/families/inkling2/experts.zig b/zig/src/families/inkling2/experts.zig index d3e8dd8d636..b8dfc56ebec 100644 --- a/zig/src/families/inkling2/experts.zig +++ b/zig/src/families/inkling2/experts.zig @@ -163,3 +163,17 @@ test "experts: run refuses expert widths outside the kernels' 1 to 4 bits on the try std.testing.expectError(error.BadExpertBits, run(undefined, undefined, undefined, l, caps, b, 0, 0, .f16, 0, 0, 4, 0, sc)); } } + +test "experts: run refuses a call or layer its kernels do not take, before any launch" { + var l = std.mem.zeroes(ex.Layer); + l.experts = 384; + l.dims = 4608; + l.width = 1152; + l.codebook = .mul1; + const sc = try ex.scratch(0, l, 4, 8); + const caps: Caps = .{ .gate = 0, .up = 0 }; + const four: Bits = .{ .lo = 8, .hi = 8 }; + try std.testing.expectError(error.BadExperts, run(undefined, undefined, undefined, l, caps, four, 0, 0, .f16, 0, 0, 5, 0, sc)); + l.codebook = .mcg; + try std.testing.expectError(error.BadExperts, run(undefined, undefined, undefined, l, caps, four, 0, 0, .f16, 0, 0, 4, 0, sc)); +} diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig index b472dfd78db..5ebd1d9a9e6 100644 --- a/zig/src/families/inkling2/vision.zig +++ b/zig/src/families/inkling2/vision.zig @@ -260,9 +260,8 @@ pub const Tower = struct { } pub fn encodeWith(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64, rope: bool) !void { + try admit(p, t.max_tokens); 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; @@ -310,6 +309,13 @@ pub const Tower = struct { } }; +/// A picture encode takes: pixels that fill its grid, and no more tokens than the tower's scratch covers. +fn admit(p: image.Prepared, max_tokens: u32) !void { + const T: usize = p.tokens(); + if (T == 0 or p.pixels.len != T * image.side * image.side * 3) return error.ImageGrid; + if (T > max_tokens) return error.ImageTooLarge; +} + /// 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 }; @@ -423,3 +429,20 @@ test "the splice copies rows as wide as the config's decoder, Small's 4608 and M v.proj_hidden = 2048; try std.testing.expectEqual(@as(u64, 16 * 2048 * 2), wide - scratchBytes(v, 16)); } + +test "encode refuses a picture whose pixels do not fill its grid" { + var px: [2 * image.side * image.side * 3]f32 = undefined; + try admit(.{ .pixels = &px, .rows = 1, .cols = 2 }, 2); + try std.testing.expectError(error.ImageGrid, admit(.{ .pixels = &px, .rows = 1, .cols = 3 }, 4)); + try std.testing.expectError(error.ImageGrid, admit(.{ .pixels = px[0..0], .rows = 0, .cols = 2 }, 4)); +} + +test "encode refuses a picture with more tokens than the tower's scratch covers" { + var px: [2 * image.side * image.side * 3]f32 = undefined; + try std.testing.expectError(error.ImageTooLarge, admit(.{ .pixels = &px, .rows = 2, .cols = 1 }, 1)); +} + +test "a tower with scratch for no image tokens is refused before any device work" { + const got = Tower.load(std.testing.allocator, std.testing.io, undefined, "", testVision(4608), 0); + try std.testing.expectError(error.ImageTokens, got); +} From 9940923efe390dfa474eafc5320367e06211e957 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 21:39:04 +1100 Subject: [PATCH 05/27] inkling2: orient RGBA pictures with core picture's pixel map --- zig/src/core/picture/picture.zig | 34 ++++++++++++++++++----------- zig/src/families/inkling2/image.zig | 29 ++++++++++++++---------- 2 files changed, 38 insertions(+), 25 deletions(-) diff --git a/zig/src/core/picture/picture.zig b/zig/src/core/picture/picture.zig index 198a90b96a4..688daa8ce3b 100644 --- a/zig/src/core/picture/picture.zig +++ b/zig/src/core/picture/picture.zig @@ -116,23 +116,31 @@ pub fn decoderProblem(err: anyerror) ?[]const u8 { }; } +/// The width and height of `s` once oriented: orientations 5-8 swap them. +pub fn orientedSize(s: Samples) [2]usize { + return if (s.orientation >= 5 and s.orientation <= 8) .{ s.height, s.width } else .{ s.width, s.height }; +} + +/// The stored (column, row) the oriented pixel (x, y) reads; an orientation outside 2-8 keeps the picture as stored. +pub fn orientedFrom(s: Samples, x: usize, y: usize) [2]usize { + return switch (s.orientation) { + 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 }, + }; +} + /// The transpose for an orientation (2-8; any other value keeps the picture as stored), then alpha over white. pub fn finish(a: Allocator, s: Samples) Allocator.Error!Rgb { - const o = if (s.orientation >= 2 and s.orientation <= 8) s.orientation else 1; - const turned = o >= 5; - const w, const h = if (turned) .{ s.height, s.width } else .{ s.width, s.height }; + const w, const h = orientedSize(s); const out = try a.alloc(u8, w * h * 3); 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 }, - }; + const sx, const sy = orientedFrom(s, x, y); const px = s.data[(sy * s.width + sx) * s.channels ..][0..s.channels]; const alpha: u8 = if (s.channels == 4) px[3] else 255; for (out[(y * w + x) * 3 ..][0..3], px[0..3]) |*c, v| c.* = overWhite(v, alpha); diff --git a/zig/src/families/inkling2/image.zig b/zig/src/families/inkling2/image.zig index 9b62e00d518..09238e10ca8 100644 --- a/zig/src/families/inkling2/image.zig +++ b/zig/src/families/inkling2/image.zig @@ -72,19 +72,9 @@ pub fn over(c: u8, alpha: u8, bg: u32) u8 { /// 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 }; + const w, const h = picture.orientedSize(s); 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 }, - }; + const sx, const sy = picture.orientedFrom(s, x, y); @memcpy(out[(y * w + x) * 4 ..][0..4], s.data[(sy * s.width + sx) * 4 ..][0..4]); }; return .{ .w = w, .h = h }; @@ -240,3 +230,18 @@ test "patches: padding reads -1 on the 0-255 scale, the patch rows reorder by 20 patchRows(p, rows); try std.testing.expectEqual(b16.bits(1), rows[4 * patch_width]); // token 1's first patch, pixel (0, 0) } + +test "the alpha turns with the colours: orient4 places pixels as picture.finish does" { + const a = std.testing.allocator; + var px: [3 * 2 * 4]u8 = undefined; + for (&px, 0..) |*v, i| v.* = if (i % 4 == 3) 255 else @intCast(i); + for (0..10) |o| { + const s: picture.Samples = .{ .width = 3, .height = 2, .channels = 4, .data = &px, .orientation = @intCast(o) }; + var want = try picture.finish(a, s); + defer want.deinit(a); + var got: [px.len]u8 = undefined; + const size = orient4(s, &got); + try std.testing.expectEqual(want.width, size.w); + for (0..size.w * size.h) |i| try std.testing.expectEqualSlices(u8, want.pixels[i * 3 ..][0..3], got[i * 4 ..][0..3]); + } +} From 26618bc584b7ed1b3267eb5412dbeb64c607c02e Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 21:39:04 +1100 Subject: [PATCH 06/27] inkling2: wrap the two long kernel table lines --- zig/build/cuda_kernels.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 86222efd6f9..bd4e859fb3a 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -167,8 +167,10 @@ 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_vision", .src = "inkling2/vision", .flags = glue }, // ours: Inkling 2's vision tower glue and attention + // ours: Inkling 2's grouped experts + .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, + // ours: Inkling 2's vision tower glue and attention + .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) .{ .name = "inkling2_modelopt", .src = "inkling2/modelopt", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // Mini packed experts on BF16 activations From 21d75c0c6b6dbc278065c0a0fb9511edd4cead7f Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 21:39:04 +1100 Subject: [PATCH 07/27] inkling2: say why the vision rotary and scaled add stay in the family --- zig/kernels/cuda/inkling2/vision.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/kernels/cuda/inkling2/vision.cu b/zig/kernels/cuda/inkling2/vision.cu index 5b0468bb4a7..0ae15232e99 100644 --- a/zig/kernels/cuda/inkling2/vision.cu +++ b/zig/kernels/cuda/inkling2/vision.cu @@ -181,7 +181,7 @@ extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_embed(const __nv } } -// 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. +// Block a row: q, k pairs (2j, 2j + 1) turned in fp32; MiniMax M3 and dots pair (i, i + half), so it is not shared. 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; @@ -194,7 +194,7 @@ extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_rope(__nv_bfloat } } -// x [count] = bf16(x + bf16(gamma[i % width] y)): the layer-scaled residual add of an attention or MLP output. +// x = bf16(x + bf16(gamma y)), the layer scale; a gamma mode on vit.cu's tf_vit_pointwise could replace it later. 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; From c6f4dbf2072f30b3b7169c04b46d9491142310f1 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Mon, 23 Nov 2026 20:24:55 +1100 Subject: [PATCH 08/27] inkling2: run vision attention on the core ViT kernel The family's attention was a copy of prefill_attention.cu's vision_kernel, so the tower now calls vit.Attention.full at head dim 64, the instance and record Qwen3-ASR already brought to main. --- zig/build/cuda_kernels.zig | 2 +- zig/kernels/cuda/inkling2/vision.cu | 142 +----------------- .../contract/inkling2_experts_records.zig | 3 +- .../contract/measurements/pending_133.zig | 1 - zig/src/families/inkling2/vision.zig | 19 +-- zig/tests/cuda/contract_inkling2_experts.zig | 12 +- .../cuda/contract_inkling2_experts_attn.zig | 28 ++-- 7 files changed, 27 insertions(+), 180 deletions(-) diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index bd4e859fb3a..75caa75cc1c 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -169,7 +169,7 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows // ours: Inkling 2's grouped experts .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, - // ours: Inkling 2's vision tower glue and attention + // ours: Inkling 2's vision tower glue .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) diff --git a/zig/kernels/cuda/inkling2/vision.cu b/zig/kernels/cuda/inkling2/vision.cu index 0ae15232e99..abc3b6c6296 100644 --- a/zig/kernels/cuda/inkling2/vision.cu +++ b/zig/kernels/cuda/inkling2/vision.cu @@ -1,13 +1,9 @@ -// Inkling 2's vision tower glue: patch rows to the sequence, axial rotary, layer-scaled residuals, full attention. +// Inkling 2's vision tower glue: patch rows to the sequence, axial rotary, layer-scaled residuals. #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; @@ -18,146 +14,10 @@ __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, diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 03397182f92..12b20cbf61b 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -1,4 +1,4 @@ -//! Inkling 2's inkling2_experts, inkling2_vision images: every SM's compile records (nvcc 13.0, 13.2, 13.3). +//! Inkling 2's expert and vision launches: 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. @@ -6,7 +6,6 @@ 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 }, diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index 56af8cdf40d..a68b44acaa9 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -8,7 +8,6 @@ pub const records = [_]Override{ .{ .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 } } }, diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig index 5ebd1d9a9e6..6168fa1bee4 100644 --- a/zig/src/families/inkling2/vision.zig +++ b/zig/src/families/inkling2/vision.zig @@ -19,12 +19,10 @@ const pre = "model.visual.backbone."; 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, @@ -35,12 +33,10 @@ pub const Kernels = struct { 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; } @@ -85,6 +81,7 @@ pub const Tower = struct { d: *const cuda.Driver, k: Kernels, vk: vit.Kernels, + fa: vit.Attention, g: vit.Gemms, bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, max_tokens: u32, @@ -143,7 +140,9 @@ pub const Tower = struct { 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, .proj_inter = v.proj_hidden, .hidden = v.text_hidden }; + var fa = try vit.Attention.load(d); + errdefer fa.unload(); + t.* = .{ .gpa = gpa, .d = d, .k = k, .vk = vk, .fa = fa, .g = try vit.Gemms.init(gpa, d), .max_tokens = max_tokens, .proj_inter = v.proj_hidden, .hidden = v.text_hidden }; errdefer { for (t.bufs.items) |*b| b.free(); t.bufs.deinit(gpa); @@ -221,6 +220,7 @@ pub const Tower = struct { for (t.bufs.items) |*b| b.free(); t.bufs.deinit(t.gpa); t.g.deinit(); + t.fa.unload(); t.vk.unload(); t.k.unload(); t.gpa.destroy(t); @@ -284,13 +284,7 @@ pub const Tower = struct { 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 t.fa.full(s, t.qkv, t.att, R, heads, head_dim, 1.0 / @sqrt(@as(f32, head_dim))); 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); @@ -413,7 +407,6 @@ fn testVision(text_hidden: u32) config.Vision { test "scratch for the default limit stays under 256 MiB" { try std.testing.expect(scratchBytes(testVision(4608), default_tokens) < 256 << 20); - try std.testing.expectEqual(@as(u32, 36864), attn_smem); } test "the splice copies rows as wide as the config's decoder, Small's 4608 and Mini's 2304" { diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig index 13206551d54..240486d3808 100644 --- a/zig/tests/cuda/contract_inkling2_experts.zig +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -17,13 +17,14 @@ pub const Set = struct { ek: ink.experts.Kernels = undefined, vk: ink.vision.Kernels = undefined, mk: ink.modelopt.Kernels = undefined, + fa: cuda.vit.Attention = undefined, groups: [2]grouped.Group = undefined, projections: [4]grouped.Grouped = undefined, moe: [13]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, + attn: 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); @@ -33,6 +34,8 @@ pub const Set = struct { const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); set.mk = try ink.modelopt.Kernels.load(gpu.d, sms); errdefer set.mk.unload(); + set.fa = try cuda.vit.Attention.load(gpu.d); + errdefer set.fa.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 }; @@ -57,7 +60,7 @@ pub const Set = struct { 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.attn = .{ .rig = rig, .att = &set.fa }; set.live = true; for (&set.groups) |*x| try list.append(a, x.kernel()); for (&set.projections) |*x| try list.append(a, x.kernel()); @@ -65,18 +68,19 @@ pub const Set = struct { 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()); + try list.append(a, set.attn.kernel()); } pub fn deinit(set: *Set) void { if (!set.live) return; - for (&set.attns) |*x| x.deinit(); + set.attn.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.fa.unload(); set.mk.unload(); set.vk.unload(); set.ek.unload(); diff --git a/zig/tests/cuda/contract_inkling2_experts_attn.zig b/zig/tests/cuda/contract_inkling2_experts_attn.zig index e914309ae75..bbe7dbc1e5f 100644 --- a/zig/tests/cuda/contract_inkling2_experts_attn.zig +++ b/zig/tests/cuda/contract_inkling2_experts_attn.zig @@ -1,4 +1,4 @@ -//! tf_ink2v_attention under the contract: the tower's full attention over one picture's rows, head dim 64. +//! prefill_attention.cu's vision_kernel<64, 8> under the contract: Inkling 2's tower attention over one picture's rows. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -12,21 +12,20 @@ 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)); +fn scale() f32 { + return 1.0 / @sqrt(@as(f32, 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 { +fn spec() 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)"; + const name = "inkling2 vit vision_kernel<64, 8> (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 } }; } @@ -43,8 +42,7 @@ fn mirrored(rng: std.Random, out: []f32) void { pub const Attention = struct { rig: rig_.Rig, - k: *const ink.vision.Kernels, - wide: bool = false, // control: the score scale of head dim 128 + att: *const cuda.vit.Attention, 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 @@ -70,7 +68,7 @@ pub const Attention = struct { } pub fn kernel(self: *Attention) g.Kernel { - return .{ .spec = spec(self.wide), .ctx = self, .vt = &vt, .control = if (self.wide) .shapes else null }; + return .{ .spec = spec(), .ctx = self, .vt = &vt }; } const vt = g.hooks(Attention); @@ -148,13 +146,7 @@ pub const Attention = struct { } 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.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.heads(), D, scale()); try self.rig.s.synchronize(); } @@ -177,7 +169,7 @@ pub const Attention = struct { var want: [D]f64 = undefined; var tol: [D]f64 = undefined; const t = j.t; - const s: f64 = scale(false); + const s: f64 = scale(); for (j.lo..j.hi) |i| { const row = i / t.heads(); const head = i % t.heads(); @@ -227,7 +219,7 @@ pub const Attention = struct { for (p, 0..) |*x, j| { var s: f64 = 0; for (0..D) |e| s += q[e] * k[j * D + e]; - x.* = s * scale(false); + x.* = s * scale(); m = @max(m, x.*); } var l: f64 = 0; From e66e49dda61f8fad41d7c7b593c9c6782e2f0f37 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:13:22 +1100 Subject: [PATCH 09/27] exl3: give the grouped expert kernel 32-member tiles grouped_body takes the member tiles a program as a template parameter. tf_exl3_grouped_wide_2 runs 32 members by 64 columns for prompt chunks; the existing instantiations compile to the same SASS on every SM. --- zig/kernels/cuda/exl3_experts.cu | 4 ++ zig/kernels/cuda/exl3_grouped.cuh | 104 +++++++++++++++++++----------- 2 files changed, 71 insertions(+), 37 deletions(-) diff --git a/zig/kernels/cuda/exl3_experts.cu b/zig/kernels/cuda/exl3_experts.cu index 77ea3a7b6ff..b05078db74f 100644 --- a/zig/kernels/cuda/exl3_experts.cu +++ b/zig/kernels/cuda/exl3_experts.cu @@ -29,6 +29,10 @@ extern "C" __global__ void tf_exl3_grouped_2(tf_exl3::GroupedArgs a) { // mul1, tf_exl3::grouped_body<2, 8, 4, GROUPED_LOAD>(a, blockIdx.x, blockIdx.y, blockIdx.z); } +extern "C" __global__ void tf_exl3_grouped_wide_2(tf_exl3::GroupedArgs a) { // mul1, 64 columns by 32 members + tf_exl3::grouped_body<2, 4, 4, GROUPED_LOAD, 2>(a, blockIdx.x, blockIdx.y, blockIdx.z); +} + namespace tf_exl3 { // Grouping in one block: distinct experts (< E) in id order, members row * 32 + slot in row order, -1 after the last. diff --git a/zig/kernels/cuda/exl3_grouped.cuh b/zig/kernels/cuda/exl3_grouped.cuh index 930700d964c..f838801ca6b 100644 --- a/zig/kernels/cuda/exl3_grouped.cuh +++ b/zig/kernels/cuda/exl3_grouped.cuh @@ -26,11 +26,19 @@ struct GroupedArgs { // How a warp reads its k tiles: main's loop, or a tile ahead (sm_120 up); SKIP and STALE are the contract's faults. enum Load : int { PLAIN = 0, AHEAD = 1, SKIP = 2, STALE = 3 }; -// One warp's k tiles [kt0, kt0 + nkt) of an expert matrix into acc: per-lane loads and the shared decode (same bits). -template -__device__ __forceinline__ void warp_tiles(const uint32_t* T, int ntiles, int kt0, int nkt, int nt0, const half* x0, - const half* x1, bool ok0, bool ok1, int lane, float (&acc)[NT][2][4]) { +// One warp's k tiles [kt0, kt0 + nkt) of an expert matrix for MT 16-member tiles: per-lane loads, the shared decode. +template +__device__ __forceinline__ void warp_tiles(const uint32_t* T, int ntiles, int kt0, int nkt, int nt0, + const half* (&x0)[MT], const half* (&x1)[MT], + const int (&r0)[MT], const int (&r1)[MT], int lane, + float (&acc)[MT][NT][2][4]) { constexpr int TW = tile_words(), LW = lane_words(); + bool ok0[MT], ok1[MT]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + ok0[m] = r0[m] >= 0; + ok1[m] = r1[m] >= 0; + } const size_t kstride = (size_t)ntiles * TW; const uint32_t* tb = T + (size_t)kt0 * kstride + (size_t)nt0 * TW; uint32_t nx[NT][LW]; // the next tile's words, in flight while this one decodes @@ -55,28 +63,36 @@ __device__ __forceinline__ void warp_tiles(const uint32_t* T, int ntiles, int kt for (int j = 0; j < NT; ++j) ldg_lane_words(tb + (size_t)next * kstride + j * TW, lane, nx[j]); } const int k = (kt0 + i) * 16; - const uint32_t a[4] = {ok0 ? *reinterpret_cast(x0 + k) : 0u, - ok1 ? *reinterpret_cast(x1 + k) : 0u, - ok0 ? *reinterpret_cast(x0 + k + 8) : 0u, - ok1 ? *reinterpret_cast(x1 + k + 8) : 0u}; + uint32_t a[MT][4]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + a[m][0] = ok0[m] ? *reinterpret_cast(x0[m] + k) : 0u; + a[m][1] = ok1[m] ? *reinterpret_cast(x1[m] + k) : 0u; + a[m][2] = ok0[m] ? *reinterpret_cast(x0[m] + k + 8) : 0u; + a[m][3] = ok1[m] ? *reinterpret_cast(x1[m] + k + 8) : 0u; + } #pragma unroll for (int j = 0; j < NT; ++j) { uint32_t b0[2], b1[2]; decode_lane(w[j], lane, b0, b1); - mma16816(acc[j][0], a, b0); - mma16816(acc[j][1], a, b1); +#pragma unroll + for (int m = 0; m < MT; ++m) { + mma16816(acc[m][j][0], a[m], b0); + mma16816(acc[m][j][1], a[m], b1); + } } } } -// Program (expert u, n block, split, member tile): 16 members times W_q over the split's K range, summed in warp order. -template +// Program (expert u, n block, split, member tile): 16 MT members times W_q over the split's K range, in warp order. +template __device__ __forceinline__ void grouped_body(const GroupedArgs a, int u, int nblock, int zz) { if (u >= a.ucount[0]) return; - const int MT = (a.maxm + 15) / 16; - const int mtile = zz % MT; - const int split = (zz / MT) % a.sk; - const int mat = zz / MT / a.sk; + constexpr int M = 16 * MT; // members a program + const int TILES = (a.maxm + M - 1) / M; + const int mtile = zz % TILES; + const int split = (zz / TILES) % a.sk; + const int mat = zz / TILES / a.sk; const half* X = mat ? a.x1 : a.x0; const int e = a.standard ? a.uids[3 * u] : a.uids[u]; if (a.standard && e == a.skip) return; @@ -86,9 +102,9 @@ __device__ __forceinline__ void grouped_body(const GroupedArgs a, int u, int nbl const int g = lane >> 2, t = lane & 3; const int NTILES = a.ns > 0 ? a.ns : (a.n >> 4); // row stride of the trellis, in tiles - __shared__ int rows_sh[16]; - if (threadIdx.x < 16) { - const int m = mtile * 16 + threadIdx.x; + __shared__ int rows_sh[M]; + if (threadIdx.x < M) { + const int m = mtile * M + threadIdx.x; const int count = a.standard ? a.uids[3 * u + 2] : a.maxm; const int first = a.standard ? a.uids[3 * u + 1] : u * a.maxm; const int code = m < count ? a.members[first + m] : -1; @@ -96,26 +112,38 @@ __device__ __forceinline__ void grouped_body(const GroupedArgs a, int u, int nbl } __syncthreads(); if (rows_sh[0] < 0) return; // members come first, so this tile is empty - const int r0 = rows_sh[g], r1 = rows_sh[g + 8]; - const half* x0 = X + (size_t)(r0 < 0 ? 0 : r0) * a.k + 2 * t; - const half* x1 = X + (size_t)(r1 < 0 ? 0 : r1) * a.k + 2 * t; + int r0[MT], r1[MT]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + r0[m] = rows_sh[16 * m + g]; + r1[m] = rows_sh[16 * m + g + 8]; + } + const half* x0[MT]; + const half* x1[MT]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + x0[m] = X + (size_t)(r0[m] < 0 ? 0 : r0[m]) * a.k + 2 * t; + x1[m] = X + (size_t)(r1[m] < 0 ? 0 : r1[m]) * a.k + 2 * t; + } 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; - float acc[NT][2][4]; + float acc[MT][NT][2][4]; #pragma unroll - for (int i = 0; i < NT; ++i) + for (int m = 0; m < MT; ++m) #pragma unroll - for (int h = 0; h < 2; ++h) + for (int i = 0; i < NT; ++i) #pragma unroll - for (int c = 0; c < 4; ++c) acc[i][h][c] = 0.f; + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int c = 0; c < 4; ++c) acc[m][i][h][c] = 0.f; - __shared__ __align__(16) float red[W][16][NT * 16]; + __shared__ __align__(16) float red[W][M][NT * 16]; switch (k2) { #define TF_EXL3X_CASE(K2_) \ case K2_: \ - warp_tiles(T, NTILES, kt0, per_warp, nt0, x0, x1, r0 >= 0, r1 >= 0, lane, acc); \ + warp_tiles(T, NTILES, kt0, per_warp, nt0, x0, x1, r0, r1, lane, acc); \ break; TF_EXL3X_CASE(2) TF_EXL3X_CASE(3) @@ -138,17 +166,19 @@ __device__ __forceinline__ void grouped_body(const GroupedArgs a, int u, int nbl } #pragma unroll - for (int i = 0; i < NT; ++i) + for (int m = 0; m < MT; ++m) #pragma unroll - for (int h = 0; h < 2; ++h) { - const int col = i * 16 + h * 8 + 2 * t; - red[warp][g][col] = acc[i][h][0]; - red[warp][g][col + 1] = acc[i][h][1]; - red[warp][g + 8][col] = acc[i][h][2]; - red[warp][g + 8][col + 1] = acc[i][h][3]; - } + 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; + red[warp][16 * m + g][col] = acc[m][i][h][0]; + red[warp][16 * m + g][col + 1] = acc[m][i][h][1]; + red[warp][16 * m + g + 8][col] = acc[m][i][h][2]; + red[warp][16 * m + g + 8][col + 1] = acc[m][i][h][3]; + } __syncthreads(); - for (int idx = threadIdx.x; idx < 16 * NT * 16; idx += W * 32) { + for (int idx = threadIdx.x; idx < M * NT * 16; idx += W * 32) { const int row = idx / (NT * 16), col = idx % (NT * 16); const int r = rows_sh[row]; if (r < 0) continue; From 2c3c9be19d08928bddb3647685ac51a71b8cf3d1 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:13:22 +1100 Subject: [PATCH 10/27] exl3: add Inkling 2's softcapped SwiGLU as a gate/up epilogue --- zig/kernels/cuda/exl3_experts.cu | 58 ++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 10 deletions(-) diff --git a/zig/kernels/cuda/exl3_experts.cu b/zig/kernels/cuda/exl3_experts.cu index b05078db74f..9116abaa531 100644 --- a/zig/kernels/cuda/exl3_experts.cu +++ b/zig/kernels/cuda/exl3_experts.cu @@ -149,13 +149,9 @@ struct GateUpArgs { int act_mode; }; -extern "C" __global__ void tf_exl3_gateup_epilogue(const GateUpArgs a) { - const int p = blockIdx.x, blk = blockIdx.y; - const int e = a.pick[p]; - if (e < 0 || e >= a.experts) return; - const int lane = threadIdx.x; - const int n = blk * 128 + 4 * lane; - float gv[4], uv[4]; +// The gate and up splits of pair p summed in order and rotated back (before the scales). +__device__ __forceinline__ void gateup_sums(const GateUpArgs& a, int p, int n, int lane, float (&gv)[4], + float (&uv)[4]) { #pragma unroll for (int j = 0; j < 4; ++j) { float sg = 0.f, su = 0.f; @@ -168,6 +164,24 @@ extern "C" __global__ void tf_exl3_gateup_epilogue(const GateUpArgs a) { } fwht128(gv, lane); fwht128(uv, lane); +} + +// The activations rotated into the down projection's inputs. +__device__ __forceinline__ void gateup_store(const GateUpArgs& a, int p, int n, int lane, float (&v)[4]) { + fwht128(v, lane); + half* o = a.xd + (size_t)p * a.n + n; +#pragma unroll + for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE); +} + +extern "C" __global__ void tf_exl3_gateup_epilogue(const GateUpArgs a) { + const int p = blockIdx.x, blk = blockIdx.y; + const int e = a.pick[p]; + if (e < 0 || e >= a.experts) return; + const int lane = threadIdx.x; + const int n = blk * 128 + 4 * lane; + float gv[4], uv[4]; + gateup_sums(a, p, n, lane, gv, uv); float v[4]; #pragma unroll for (int j = 0; j < 4; ++j) { @@ -185,10 +199,34 @@ extern "C" __global__ void tf_exl3_gateup_epilogue(const GateUpArgs a) { } v[j] = act * __half2float(a.suh_d[(size_t)e * a.n + n + j]); } - fwht128(v, lane); - half* o = a.xd + (size_t)p * a.n + n; + gateup_store(a, p, n, lane, v); +} + +// act_mode 3, Inkling 2's softcapped SwiGLU: gate_cap tanh(g / gate_cap) sigmoid(g) up_cap tanh(u / up_cap), fp32. +struct CappedArgs { + GateUpArgs g; + float gate_cap, up_cap; +}; + +extern "C" __global__ void tf_exl3_gateup_capped(const CappedArgs c) { + const GateUpArgs& a = c.g; + const int p = blockIdx.x, blk = blockIdx.y; + const int e = a.pick[p]; + if (e < 0 || e >= a.experts) return; + const int lane = threadIdx.x; + const int n = blk * 128 + 4 * lane; + float gv[4], uv[4]; + gateup_sums(a, p, n, lane, gv, uv); + float v[4]; #pragma unroll - for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE); + for (int j = 0; j < 4; ++j) { + const float g = gv[j] * HAD_SCALE * __half2float(a.svh_g[(size_t)e * a.n + n + j]); + const float u = uv[j] * HAD_SCALE * __half2float(a.svh_u[(size_t)e * a.n + n + j]); + const float act = + c.gate_cap * tanhf(g / c.gate_cap) * (1.f / (1.f + expf(-g))) * c.up_cap * tanhf(u / c.up_cap); + v[j] = act * __half2float(a.suh_d[(size_t)e * a.n + n + j]); + } + gateup_store(a, p, n, lane, v); } // Program (member row, 128-block of the width): down epilogue and combine in one launch, the same bits as the two. From ec12ae5d41bc035104c9f794b6057ca3de327673 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:33:02 +1100 Subject: [PATCH 11/27] exl3: define the wide grouped kernel before the others nvcc 13.3 changed tf_exl3_grouped_2's sm_120 and sm_121 SASS when the wide instance followed it; defined first, every existing kernel compiles as before under 13.0 and 13.3. --- zig/kernels/cuda/exl3_experts.cu | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/zig/kernels/cuda/exl3_experts.cu b/zig/kernels/cuda/exl3_experts.cu index 9116abaa531..bea32a422d8 100644 --- a/zig/kernels/cuda/exl3_experts.cu +++ b/zig/kernels/cuda/exl3_experts.cu @@ -17,6 +17,11 @@ constexpr int GROUPED_LOAD = tf_exl3::AHEAD; constexpr int GROUPED_LOAD = tf_exl3::PLAIN; #endif +// Defined before the others: nvcc 13.3 then leaves tf_exl3_grouped_2's sm_12x SASS as it was. +extern "C" __global__ void tf_exl3_grouped_wide_2(tf_exl3::GroupedArgs a) { // mul1, 64 columns by 32 members + tf_exl3::grouped_body<2, 4, 4, GROUPED_LOAD, 2>(a, blockIdx.x, blockIdx.y, blockIdx.z); +} + extern "C" __global__ void tf_exl3_grouped_0(tf_exl3::GroupedArgs a) { // 3inst, any width tf_exl3::grouped_body<0, 8, 4, GROUPED_LOAD>(a, blockIdx.x, blockIdx.y, blockIdx.z); } @@ -29,10 +34,6 @@ extern "C" __global__ void tf_exl3_grouped_2(tf_exl3::GroupedArgs a) { // mul1, tf_exl3::grouped_body<2, 8, 4, GROUPED_LOAD>(a, blockIdx.x, blockIdx.y, blockIdx.z); } -extern "C" __global__ void tf_exl3_grouped_wide_2(tf_exl3::GroupedArgs a) { // mul1, 64 columns by 32 members - tf_exl3::grouped_body<2, 4, 4, GROUPED_LOAD, 2>(a, blockIdx.x, blockIdx.y, blockIdx.z); -} - namespace tf_exl3 { // Grouping in one block: distinct experts (< E) in id order, members row * 32 + slot in row order, -1 after the last. From 5cef42d9e93ef3b960843e5a3471c356ea0c7eea Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:33:03 +1100 Subject: [PATCH 12/27] exl3: take any codebook, 32-member items and softcaps in runWith The item plan was limited to mcg and slot rows written to ey. It now takes every codebook, writes scratch y when ey is 0, picks the wide kernel for 32-member items and the capped epilogue for act_mode 3. --- zig/src/cuda/exl3_experts.zig | 42 ++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/zig/src/cuda/exl3_experts.zig b/zig/src/cuda/exl3_experts.zig index 861bb7151e9..48a06148af0 100644 --- a/zig/src/cuda/exl3_experts.zig +++ b/zig/src/cuda/exl3_experts.zig @@ -40,14 +40,16 @@ pub const Layer = struct { shared_input: bool = false, // the loader verified identical gate/up input scales across every expert gu_stride: usize = 0, // gate/up trellis row stride in tiles (0: contiguous per projection) limit: f32 = 0, // the SwiGLU clamp (0: none) - act_mode: i32 = 0, // 0: GLM's bf16 roundings (the route RED-SNOW runs), 1: fp32, 2: SwiGLU-OAI (Grouped only) + act_mode: i32 = 0, // 0: GLM's bf16 roundings (the route RED-SNOW runs), 1: fp32, 2: SwiGLU-OAI (Grouped only), 3: softcaps alpha: f32 = 0, // SwiGLU-OAI's sigmoid scale (act_mode 2) + caps: [2]f32 = .{ 0, 0 }, // the gate and up softcaps (act_mode 3, Inkling 2) }; -/// The item plan a decode window takes: the family's Router and the plan buffer the caller holds. +/// The item plan a call takes: the family's Router, the plan buffer the caller holds, and members an item. pub const Items = struct { router: *const grouped.Router, plan: grouped.Plan, + tile: usize = 16, // 16, or 32 for the 64-column wide kernel (mul1 only) }; /// What one projection launches (experts.py default_config): the 8-tile 4-warp K splits, shape-fixed; n % 128 required. @@ -141,6 +143,8 @@ pub const Experts = struct { grouped: [3]Function, // one per codebook gateup: Function, down_combine: Function, + wide: Function = undefined, // tf_exl3_grouped_wide_2: 32-member items by 64 columns, mul1 + capped: Function = undefined, // the gate/up epilogue for act_mode 3 prompt: prompt.Kernels = undefined, plan_rotate: Function = undefined, plan_finish: Function = undefined, @@ -170,6 +174,8 @@ pub const Experts = struct { try e.mod.function("tf_exl3_grouped_2"), }; e.gateup = try e.mod.function("tf_exl3_gateup_epilogue"); + e.wide = try e.mod.function("tf_exl3_grouped_wide_2"); + e.capped = try e.mod.function("tf_exl3_gateup_capped"); e.down_combine = try e.mod.function("tf_exl3_down_combine"); return e; } @@ -188,7 +194,7 @@ pub const Experts = struct { try e.runWith(s, l, x, x_stride, x_dtype, pick, wts, rows, out, sc, 0, null); } - /// run() on a decode window's item plan (`it`): the grouped kernels in standard mode, the slot rows in `ey`. + /// run() on an item plan (`it`): the grouped kernels in standard mode, the slot rows in `ey` (0: scratch y). pub fn runWith(e: *const Experts, s: Stream, l: Layer, x: u64, x_stride: usize, x_dtype: DType, pick: u64, wts: u64, rows: usize, out: u64, sc: Scratch, ey: u64, it: ?Items) !void { const d = l.dims; const w = l.width; @@ -196,7 +202,7 @@ pub const Experts = struct { std.debug.assert(rows >= 1 and rows <= sc.rows); std.debug.assert(slots >= 1 and slots <= 32); std.debug.assert(l.experts >= 1 and l.experts <= 4096); - if (l.act_mode != 0 and l.act_mode != 1) return error.BadExperts; // SwiGLU-OAI runs through Grouped only + if (l.act_mode != 0 and l.act_mode != 1 and l.act_mode != 3) return error.BadExperts; // SwiGLU-OAI: Grouped only const g_sk = try plan(d, w, true); const d_sk = try plan(w, d, false); const p = rows * slots; @@ -207,20 +213,25 @@ pub const Experts = struct { return @intCast(v); } }.f; - // A decode window's item plan: the picks grouped into 16-pair items, the grouped kernels in standard mode. - const items = it != null; // one codebook a launch, a plan, and ey to write the slot rows into: nothing else - if (items and (l.codebook != .mcg or wts != 0 or out != 0 or ey == 0 or it.?.plan.members == 0 or it.?.plan.items == 0 or it.?.plan.counts == 0)) return error.TileNotBuilt; - const nx: usize = if (items) grouped.maxItems(p, l.experts + 1, 16) else maxu; // grid x and nexp_max - const mtu: usize = if (items) 1 else mt; // member tiles a program (a 16-pair item, or ceil(rows/16)) + // An item plan: the picks grouped into 16- or 32-pair items, the grouped kernels in standard mode. + const items = it != null; + const tile: usize = if (items) it.?.tile else 16; + const wide = tile == 32; // 32-pair items take the wide kernel, built for mul1 + if (items and (it.?.plan.members == 0 or it.?.plan.items == 0 or it.?.plan.counts == 0)) return error.TileNotBuilt; + if ((tile != 16 and !wide) or (wide and l.codebook != .mul1)) return error.TileNotBuilt; + const nx: usize = if (items) grouped.maxItems(p, l.experts + 1, tile) else maxu; // grid x and nexp_max + const mtu: usize = if (items) 1 else mt; // member tiles a program (one item, or ceil(rows/16)) const uids = if (items) it.?.plan.items else sc.ids; const ucount = if (items) it.?.plan.counts else sc.count; const members = if (items) it.?.plan.members else sc.members; - const maxm_a: i32 = if (items) 16 else i32d(rows); + const maxm_a: i32 = if (items) i32d(tile) else i32d(rows); + const proj = if (wide) e.wide else e.grouped[@backingInt(l.codebook)]; + const cols: usize = if (wide) 64 else 128; const std_a: i32 = if (items) 1 else 0; const skip_a: i32 = if (items) i32d(l.experts) else -1; if (items) { - try it.?.router.route(s, pick, p, l.experts + 1, 16, it.?.plan); + try it.?.router.route(s, pick, p, l.experts + 1, tile, it.?.plan); } else { var a: launch_.Args = .{}; a.add(pick); @@ -270,7 +281,7 @@ pub const Experts = struct { g.add(i32d(l.gu_stride)); g.add(std_a); g.add(skip_a); - try launch_.launch(e.grouped[@backingInt(l.codebook)], .{ .grid = .{ .x = @intCast(nx), .y = @intCast(w / 128), .z = @intCast(2 * g_sk * mtu) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &g); + try launch_.launch(proj, .{ .grid = .{ .x = @intCast(nx), .y = @intCast(w / cols), .z = @intCast(2 * g_sk * mtu) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &g); var ep: launch_.Args = .{}; ep.add(sc.z); @@ -285,7 +296,8 @@ pub const Experts = struct { ep.add(i32d(l.experts)); ep.add(l.limit); ep.add(l.act_mode); - try launch_.launch(e.gateup, .{ .grid = .{ .x = @intCast(p), .y = @intCast(w / 128), .z = 1 }, .block = .{ .x = 32, .y = 1, .z = 1 } }, s, &ep); + if (l.act_mode == 3) for (l.caps) |c| ep.add(c); // tf_exl3_gateup_capped's CappedArgs + try launch_.launch(if (l.act_mode == 3) e.capped else e.gateup, .{ .grid = .{ .x = @intCast(p), .y = @intCast(w / 128), .z = 1 }, .block = .{ .x = 32, .y = 1, .z = 1 } }, s, &ep); var dn: launch_.Args = .{}; dn.add(sc.xd); @@ -309,13 +321,13 @@ pub const Experts = struct { dn.add(@as(i32, 0)); dn.add(std_a); dn.add(skip_a); - try launch_.launch(e.grouped[@backingInt(l.codebook)], .{ .grid = .{ .x = @intCast(nx), .y = @intCast(d / 128), .z = @intCast(d_sk * mtu) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &dn); + try launch_.launch(proj, .{ .grid = .{ .x = @intCast(nx), .y = @intCast(d / cols), .z = @intCast(d_sk * mtu) }, .block = .{ .x = 128, .y = 1, .z = 1 } }, s, &dn); var cb: launch_.Args = .{}; cb.add(sc.z); cb.add(pick); cb.add(l.svh_d); - cb.add(if (items) ey else sc.y); // items: write ey's routed slot rows in place (no copy back) + cb.add(if (ey != 0) ey else sc.y); // ey: write the caller's routed slot rows in place (no copy back) cb.add(wts); cb.add(out); cb.add(i32d(p)); From 3228cbd912a126fcbe58a0a297642f3703c428a0 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:33:03 +1100 Subject: [PATCH 13/27] inkling2: run the experts on the core grouped kernel The family's grouper and grouped projections were copies of core's. Inkling now runs exl3_experts.runWith on grouped.Router's item plan, 16-member items below 512 rows and the wide kernel from there; outputs are bit-equal to the kernels this replaces. Expert widths up to 8 bits are admitted, as core decodes them. --- zig/build/cuda_kernels.zig | 6 +- zig/kernels/cuda/inkling2/experts.cu | 330 +----------------- .../contract/inkling2_experts_records.zig | 7 +- .../contract/measurements/pending_133.zig | 5 +- zig/src/cuda/kernels.zig | 2 +- zig/src/families/inkling2/experts.zig | 144 +++----- zig/tests/cuda/contract_inkling2_experts.zig | 11 +- .../contract_inkling2_experts_grouped.zig | 174 ++------- .../cuda/contract_inkling2_experts_ref.zig | 39 +-- zig/tests/fixtures/gradient-serving.tsv | 2 +- 10 files changed, 94 insertions(+), 626 deletions(-) diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 75caa75cc1c..aa0aab27ffd 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -165,14 +165,14 @@ pub const kernels = [_]Kernel{ .{ .name = "idol_decoder", .flags = glue }, // ours: Idol's decoders' stem, to_kv, head norms and attention .{ .name = "inkling2_attn", .src = "inkling2/attention", .flags = &.{"-O3"} }, // ours: Inkling 2's relative-bias attention .{ .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_ops", .src = "inkling2/ops", .flags = glue }, // ours: Inkling 2's residual mix, convs, router .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows - // ours: Inkling 2's grouped experts - .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // ours: Inkling 2's vision tower glue .{ .name = "inkling2_vision", .src = "inkling2/vision", .flags = glue }, .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) + // Mini's tensor-path expert epilogue and ascending combine: the modelopt contract's baseline + .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, .{ .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 = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family diff --git a/zig/kernels/cuda/inkling2/experts.cu b/zig/kernels/cuda/inkling2/experts.cu index cd0b81c7803..84ce373d3cf 100644 --- a/zig/kernels/cuda/inkling2/experts.cu +++ b/zig/kernels/cuda/inkling2/experts.cu @@ -1,334 +1,6 @@ -// Inkling 2's grouped expert projections: exl3_grouped.cuh's arithmetic per output, launched without empty tiles. +// Inkling 2 Mini's tensor-path expert epilogue and ascending combine: the modelopt contract's baseline kernels. #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 { diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 12b20cbf61b..18507ea3ee9 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -3,9 +3,8 @@ 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 = "exl3_experts tf_exl3_grouped_wide_2 (Inkling 2)", .symbol = "tf_exl3_grouped_wide_2", .image = "exl3_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 140, .static = 32896, .bound = 0 }, .{ .regs = 140, .static = 32896, .bound = 0 } }, .later_pending = true }, + .{ .launch = .{ .name = "exl3_experts tf_exl3_gateup_capped (Inkling 2)", .symbol = "tf_exl3_gateup_capped", .image = "exl3_experts", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } }, .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 }, @@ -24,5 +23,5 @@ pub const cuda = [_]registry.CudaRecord{ }; /// 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). +/// nvcc 13.3's: none here, as later_pending reads 13.3 from measurements/pending_133.zig (all five 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 a68b44acaa9..8111b6052f7 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -5,9 +5,8 @@ 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 = "exl3_experts tf_exl3_grouped_wide_2 (Inkling 2)", .usage = .{ .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 128, .static = 32896, .bound = 0 }, .{ .regs = 128, .static = 32896, .bound = 0 } } }, + .{ .name = "exl3_experts tf_exl3_gateup_capped (Inkling 2)", .usage = .{ .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, .{ .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 } } }, diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 710eb26bfa8..9a5aac5c84a 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -117,10 +117,10 @@ 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_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; pub const ricursive_prep: []const u8 = if (available) &Blob("fatbin_ricursive_prep").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 glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; diff --git a/zig/src/families/inkling2/experts.zig b/zig/src/families/inkling2/experts.zig index b8dfc56ebec..b610def8115 100644 --- a/zig/src/families/inkling2/experts.zig +++ b/zig/src/families/inkling2/experts.zig @@ -1,9 +1,9 @@ -//! Inkling 2's routed experts: the family's grouping and grouped projections, main's rotation and combine. +//! Inkling 2's routed experts on core exl3_experts: core's item plan, grouped kernels and softcapped epilogue. const std = @import("std"); const cuda = @import("cuda"); -const ops = @import("ops.zig"); const ex = cuda.exl3_experts; +const grouped = cuda.grouped; /// The two SwiGLU softcaps (config.json mlp_gate_softcap, mlp_up_softcap). pub const Caps = struct { gate: f32, up: f32 }; @@ -11,31 +11,21 @@ pub const Caps = struct { gate: f32, up: f32 }; /// The least and most half-bit widths (k2) among a layer's expert tensors, as the loader read them. pub const Bits = struct { lo: u32, hi: u32 }; -/// 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). +/// Calls of at least this many rows take 32-member items on core's wide kernel (64 columns a block). pub const wide_from = 512; -/// main's experts module beside the family's grouped projections. +/// Core's experts module and the plan kernels of the shared experts image. pub const Kernels = struct { main: ex.Experts, mod: cuda.Module, - group: cuda.Function, - rows: cuda.Function, - wide: cuda.Function, + router: grouped.Router, 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); + var mod = try cuda.Module.load(d, cuda.kernels.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"), - }; + return .{ .main = main, .mod = mod, .router = try grouped.Router.resolve(mod) }; } pub fn unload(k: *Kernels) void { @@ -44,88 +34,45 @@ pub const Kernels = struct { } }; -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 { +/// The plan's buffers past core's scratch: members, items, counts, then the wide plan's rank and hist. +fn planSizes(l: ex.Layer, rows: usize, slots: usize) [5]usize { const p = rows * slots; - return (p + 15) / 16 + @min(p, l.experts); + const hist = if (p > grouped.small) (p + grouped.small - 1) / grouped.small * (l.experts + 1) else 1; + return .{ p * 4, grouped.maxItems(p, l.experts + 1, 16) * 12, 8, p * 4, hist * 4 }; } -/// main's scratch, then the item count and the item list (three int32 an item). +/// Core's scratch, then the item plan. 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); + var n = try ex.scratchBytes(l, rows, slots); + for (planSizes(l, rows, slots)) |b| n += align256(b); + return n; } -/// 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); +/// Where the plan sits in scratch laid out by ex.scratch over scratchBytes(). +fn planAt(l: ex.Layer, sc: ex.Scratch) grouped.Plan { + var at = sc.members + align256(@min(sc.rows * sc.slots, l.experts) * sc.rows * 4); + var ptr: [5]u64 = undefined; + for (&ptr, planSizes(l, sc.rows, sc.slots)) |*q, b| { + q.* = at; + at += align256(b); + } + return .{ .members = ptr[0], .items = ptr[1], .counts = ptr[2], .rank = ptr[3], .hist = ptr[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, bits: Bits, 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; +/// exl3_experts.Experts.runWith on core's item plan, with the softcaps as act_mode 3. +pub fn run(e: *const Kernels, s: cuda.Stream, l: ex.Layer, caps: Caps, bits: Bits, x: u64, x_stride: usize, x_dtype: ex.DType, pick: u64, wts: u64, rows: usize, out: u64, sc: ex.Scratch) !void { + if (rows < 1 or rows > sc.rows or sc.slots < 1 or sc.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; - if (bits.lo < 2 or bits.hi > 8 or bits.lo > bits.hi) return error.BadExpertBits; // the kernels decode 1 to 4 bits - 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); + if (bits.lo < 2 or bits.hi > 16 or bits.lo > bits.hi) return error.BadExpertBits; // core decodes 1 to 8 bits + var c = l; + c.act_mode = 3; + c.caps = .{ caps.gate, caps.up }; + const it: ex.Items = .{ .router = &e.router, .plan = planAt(l, sc), .tile = if (rows >= wide_from) 32 else 16 }; + try e.main.runWith(s, c, x, x_stride, x_dtype, pick, wts, rows, out, sc, 0, it); } test "experts: Inkling's expert shapes have built tiles (gate/up 4608 -> 2304 whole and a rank's 1152, down back)" { @@ -133,9 +80,11 @@ test "experts: Inkling's expert shapes have built tiles (gate/up 4608 -> 2304 wh 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); + // the wide kernel's 64 columns and the rows kernel's 128 divide a rank's 1152 and the 4608 width + try std.testing.expect(1152 % 128 == 0 and 4608 % 128 == 0); } -test "experts: the item list sits past main's scratch and holds a 2,048-row call's items" { +test "experts: the item plan sits past core's scratch and holds a 2,048-row call's items" { var l = std.mem.zeroes(ex.Layer); l.experts = 384; l.dims = 4608; @@ -143,15 +92,14 @@ test "experts: the item list sits past main's scratch and holds a 2,048-row call 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); + const pl = planAt(l, sc); + try std.testing.expectEqual(@as(u64, try ex.scratchBytes(l, 2048, 8)), pl.members); + try std.testing.expect(pl.items - pl.members >= 16384 * 4); + try std.testing.expect(pl.counts - pl.items >= (16384 / 16 + 385) * 12); + try std.testing.expect(pl.hist + 16 * 385 * 4 <= bytes); } -test "experts: run refuses expert widths outside the kernels' 1 to 4 bits on the host" { +test "experts: run refuses expert widths outside core's 1 to 8 bits on the host" { var l = std.mem.zeroes(ex.Layer); l.experts = 384; l.dims = 4608; @@ -159,8 +107,8 @@ test "experts: run refuses expert widths outside the kernels' 1 to 4 bits on the l.codebook = .mul1; const sc = try ex.scratch(0, l, 4, 8); const caps: Caps = .{ .gate = 0, .up = 0 }; - for ([_]Bits{ .{ .lo = 1, .hi = 8 }, .{ .lo = 2, .hi = 9 }, .{ .lo = 6, .hi = 4 } }) |b| { - try std.testing.expectError(error.BadExpertBits, run(undefined, undefined, undefined, l, caps, b, 0, 0, .f16, 0, 0, 4, 0, sc)); + for ([_]Bits{ .{ .lo = 1, .hi = 8 }, .{ .lo = 2, .hi = 17 }, .{ .lo = 6, .hi = 4 } }) |b| { + try std.testing.expectError(error.BadExpertBits, run(undefined, undefined, l, caps, b, 0, 0, .f16, 0, 0, 4, 0, sc)); } } @@ -173,7 +121,7 @@ test "experts: run refuses a call or layer its kernels do not take, before any l const sc = try ex.scratch(0, l, 4, 8); const caps: Caps = .{ .gate = 0, .up = 0 }; const four: Bits = .{ .lo = 8, .hi = 8 }; - try std.testing.expectError(error.BadExperts, run(undefined, undefined, undefined, l, caps, four, 0, 0, .f16, 0, 0, 5, 0, sc)); + try std.testing.expectError(error.BadExperts, run(undefined, undefined, l, caps, four, 0, 0, .f16, 0, 0, 5, 0, sc)); l.codebook = .mcg; - try std.testing.expectError(error.BadExperts, run(undefined, undefined, undefined, l, caps, four, 0, 0, .f16, 0, 0, 4, 0, sc)); + try std.testing.expectError(error.BadExperts, run(undefined, undefined, l, caps, four, 0, 0, .f16, 0, 0, 4, 0, sc)); } diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig index 240486d3808..5c89bbe40ba 100644 --- a/zig/tests/cuda/contract_inkling2_experts.zig +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -1,4 +1,4 @@ -//! Inkling 2's grouped experts and vision tower (inkling2/experts.cu, vision.cu) under the contract, with controls. +//! Inkling 2's prompt-chunk experts on core's wide kernel and its vision tower (vision.cu), with controls. const std = @import("std"); const cuda = @import("cuda"); const ink = @import("inkling2"); @@ -18,8 +18,7 @@ pub const Set = struct { vk: ink.vision.Kernels = undefined, mk: ink.modelopt.Kernels = undefined, fa: cuda.vit.Attention = undefined, - groups: [2]grouped.Group = undefined, - projections: [4]grouped.Grouped = undefined, + projections: [2]grouped.Grouped = undefined, moe: [13]modelopt.ModelOpt = undefined, embeds: [2]ref.Gated(vision.Embed) = undefined, ropes: [2]ref.Gated(vision.Rope) = undefined, @@ -37,9 +36,7 @@ pub const Set = struct { set.fa = try cuda.vit.Attention.load(gpu.d); errdefer set.fa.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.projections, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .fault = if (i == 1) .swapped else .none }; const prompt = [13]bool{ false, true, false, true, false, true, false, false, false, true, false, false, false }; for (&set.moe, 0..) |*x, i| x.* = .{ .rig = rig, @@ -62,7 +59,6 @@ pub const Set = struct { for (&set.adds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; set.attn = .{ .rig = rig, .att = &set.fa }; 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()); @@ -79,7 +75,6 @@ pub const Set = struct { 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.fa.unload(); set.mk.unload(); set.vk.unload(); diff --git a/zig/tests/cuda/contract_inkling2_experts_grouped.zig b/zig/tests/cuda/contract_inkling2_experts_grouped.zig index 1d82f7c6a2f..496d863686f 100644 --- a/zig/tests/cuda/contract_inkling2_experts_grouped.zig +++ b/zig/tests/cuda/contract_inkling2_experts_grouped.zig @@ -1,4 +1,4 @@ -//! tf_ink2x_rows, tf_ink2x_wide and tf_ink2x_group under the contract: each bit-equal to the main kernel it replaces. +//! Core's tf_exl3_grouped_wide_2 on Inkling 2's prompt chunks: bit-equal to tf_exl3_grouped_2 on the same members. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -13,11 +13,10 @@ 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. +/// One projection as exl3_experts.runWith launches it on 32-member items; 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 }, @@ -26,6 +25,7 @@ pub const Grouped = struct { uids: u64 = 0, ucount: u64 = 0, members: u64 = 0, + plan: u64 = 0, // the item plan's members: pair p = row * slots + slot items: u64 = 0, nitems: u64 = 0, out: u64 = 0, @@ -44,7 +44,7 @@ pub const Grouped = struct { } 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 }; + return .{ .spec = ref.spec(self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; } const vt = g.hooks(Grouped); @@ -84,32 +84,36 @@ pub const Grouped = struct { 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); + const n = l.items(shape.rows, 32, items); + const plan = try a.alloc(i32, l.members.len); + defer a.free(plan); + for (plan, l.members) |*q, code| q.* = if (code < 0) -1 else @divTrunc(code, 32) * ref.slots + @mod(code, 32); + for (0..@intCast(n)) |i| { // (expert, first member in the plan, count), as grouped.Router.route writes them + const u: usize = @intCast(items[3 * i]); + items[3 * i] = l.uids[u]; + items[3 * i + 1] += @intCast(u * shape.rows); + } + self.plan = try self.put(plan); 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.nitems = try self.put(&[1]i32{n}); 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). + /// exl3_experts.runWith's launch on an item plan: GroupedArgs in standard mode, 32 members by 64 columns. 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 m = ref.mats(sh); + const nx = cuda.grouped.maxItems(p, ref.experts + 1, 32); 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); + for ([_]u64{ x0, self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.items, self.nitems, self.plan, self.out }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, 32, ref.slots, nx, m, 0, 1 }) |v| a.add(i32s(v)); + a.add(@as(i32, ref.experts)); + try cuda.launch.launch(self.k.main.wide, .{ .grid = .{ .x = @intCast(nx), .y = @intCast(sh.n / 64), .z = @intCast(m * sk) }, .block = .{ .x = 128 } }, self.rig.s, &a); } pub fn run(self: *Grouped) !void { @@ -160,137 +164,3 @@ pub const Grouped = struct { 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 index 9549c2b112e..3f5f1290bdf 100644 --- a/zig/tests/cuda/contract_inkling2_experts_ref.zig +++ b/zig/tests/cuda/contract_inkling2_experts_ref.zig @@ -13,13 +13,11 @@ 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 warps = 4; // grouped_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 }; +/// Gate 3's planted fault, a launch argument: the up rows read as gate rows. +pub const Fault = enum { none, 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 { @@ -36,16 +34,6 @@ 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); @@ -65,20 +53,17 @@ fn served(rows: []const usize, comptime n: usize) [2 * n]c.Shape { 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 { +pub fn spec(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", + .none => "inkling2 exl3 tf_exl3_grouped_wide_2 (prompt chunks from 512, 64 columns by 32 members)", + .swapped => "inkling2 exl3 control: tf_exl3_grouped_wide_2 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 edge: c.Tile = .{ .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 } }; + 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 = &wide_served, .sums = .{ .exact = false } }; } /// Each row's 8 distinct experts: expert 0 in every row (long runs and a partial one), the rest at random. @@ -249,7 +234,7 @@ pub const Lists = struct { a.free(l.members); } - /// tf_ink2x_group's items for runs of `run` members: (u, first, count) in expert order, -1 words after them. + /// 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; @@ -275,11 +260,11 @@ fn value(h: u16) f64 { } test "inkling2 experts contract: every served shape has a split, items fit experts.zig's room" { - for (rows_served ++ wide_served) |s| { + for (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])); + try std.testing.expectEqual(@as(usize, 4), split(wide_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); @@ -288,6 +273,6 @@ test "inkling2 experts contract: every served shape has a split, items fit exper 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.expect(l.items(2048, 32, out) <= maxItems(pick.len)); try std.testing.expectEqual(@as(i32, 0), l.uids[0]); } diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 8a0a95c4644..aaf316741d3 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 0ada89c63783a53d138cdf33b3f3e2f961535e91448c82eeb5ca99a 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 0ee921a870a4611905830c893b475eb55e1c1539a62bab4a28ee81d68333be57 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; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered +zig/src/cuda/kernels.zig d856075d70900e8c0baf2d1c12cf5f7eca638ee4700636b3fabeff956fa771a8 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; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 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 3b8b7567e1f1e7c19528bb652b4c17c3f0716030 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:33:11 +1100 Subject: [PATCH 14/27] inkling2: use the core softcapped epilogue for the experts tf_ink2_gateup duplicated core's gate/up epilogue apart from the softcaps, which core now runs as act_mode 3. Its registration moves to tf_exl3_gateup_capped, with the swapped-caps control kept. --- zig/kernels/cuda/inkling2/ops.cu | 48 +------------------ .../core/contract/inkling2_ops_records.zig | 1 - zig/src/families/inkling2/ops.zig | 26 ---------- zig/tests/cuda/contract_inkling2_ops.zig | 6 ++- .../cuda/contract_inkling2_ops_route.zig | 30 ++++++++++-- 5 files changed, 32 insertions(+), 79 deletions(-) diff --git a/zig/kernels/cuda/inkling2/ops.cu b/zig/kernels/cuda/inkling2/ops.cu index 648eb50686d..9307948b0db 100644 --- a/zig/kernels/cuda/inkling2/ops.cu +++ b/zig/kernels/cuda/inkling2/ops.cu @@ -1,4 +1,4 @@ -// Inkling 2 glue: embedding, block attention-residual mix, row dots, router top-k, softcapped SwiGLU, short convs. +// Inkling 2 glue: embedding, block attention-residual mix, row dots, router top-k, short convs. #include #include #include @@ -320,52 +320,6 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_topk(const float* __re } } -// The shared gate/up epilogue with Inkling's softcapped SwiGLU: gcap tanh(g/gcap) sigmoid(g) ucap tanh(u/ucap). -struct GateUpArgs { - const float* z; // [(mat * sk + split) * P + p] * N + col - const int* pick; // int32 [P] - const half* svh_g; // fp16 [E, N] - const half* svh_u; // fp16 [E, N] - const half* suh_d; // fp16 [E, N] - half* xd; // fp16 [P, N] - int p, n, sk, experts; - float gate_cap, up_cap; -}; - -extern "C" __global__ void tf_ink2_gateup(const GateUpArgs a) { - using namespace tf_exl3; - const int p = blockIdx.x, blk = blockIdx.y; - const int e = a.pick[p]; - if (e < 0 || e >= a.experts) return; - const int lane = threadIdx.x; - const int n = blk * 128 + 4 * lane; - float gv[4], uv[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) { - float sg = 0.f, su = 0.f; - for (int s = 0; s < a.sk; ++s) { - sg += a.z[((size_t)(0 * a.sk + s) * a.p + p) * a.n + n + j]; - su += a.z[((size_t)(1 * a.sk + s) * a.p + p) * a.n + n + j]; - } - gv[j] = sg; - uv[j] = su; - } - fwht128(gv, lane); - fwht128(uv, lane); - float v[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const float g = gv[j] * HAD_SCALE * __half2float(a.svh_g[(size_t)e * a.n + n + j]); - const float u = uv[j] * HAD_SCALE * __half2float(a.svh_u[(size_t)e * a.n + n + j]); - const float act = a.gate_cap * tanhf(g / a.gate_cap) * (1.f / (1.f + expf(-g))) * a.up_cap * tanhf(u / a.up_cap); - v[j] = act * __half2float(a.suh_d[(size_t)e * a.n + n + j]); - } - fwht128(v, lane); - half* o = a.xd + (size_t)p * a.n + n; -#pragma unroll - for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE); -} - // Short causal conv over a stream's rows (4 taps, last 3 inputs in `state`): static [C][4] or dynamic [4][C] + dyn. struct ConvArgs { const void* x; // [rows, C]: fp32 (`parts` rank partials, part_stride apart, added in rank order) or bf16 diff --git a/zig/src/core/contract/inkling2_ops_records.zig b/zig/src/core/contract/inkling2_ops_records.zig index ca64067c034..7dd35ea2f6e 100644 --- a/zig/src/core/contract/inkling2_ops_records.zig +++ b/zig/src/core/contract/inkling2_ops_records.zig @@ -8,7 +8,6 @@ pub const cuda = [_]registry.CudaRecord{ .{ .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 } } }, - .{ .launch = .{ .name = "inkling2 ops tf_ink2_gateup", .symbol = "tf_ink2_gateup", .image = "inkling2_ops", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_conv", .symbol = "tf_ink2_conv", .image = "inkling2_ops", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_conv_rewind", .symbol = "tf_ink2_conv_rewind", .image = "inkling2_ops", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 0, .bound = 128 }, .{ .regs = 28, .static = 0, .bound = 128 }, .{ .regs = 28, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 }, .{ .regs = 34, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_softcap", .symbol = "tf_ink2_softcap", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, diff --git a/zig/src/families/inkling2/ops.zig b/zig/src/families/inkling2/ops.zig index fb2bdeeabc6..cf2231091e1 100644 --- a/zig/src/families/inkling2/ops.zig +++ b/zig/src/families/inkling2/ops.zig @@ -42,22 +42,6 @@ pub const ConvArgs = extern struct { mode: i32, }; -/// ops.cu's GateUpArgs, field for field. -pub const GateUpArgs = extern struct { - z: u64, - pick: u64, - svh_g: u64, - svh_u: u64, - suh_d: u64, - xd: u64, - p: i32, - n: i32, - sk: i32, - experts: i32, - gate_cap: f32, - up_cap: f32, -}; - pub const Kernels = struct { mod: cuda.Module, rows_mod: cuda.Module, @@ -68,7 +52,6 @@ pub const Kernels = struct { mix_rows: cuda.Function, rowdot: cuda.Function, topk: cuda.Function, - gateup: cuda.Function, conv: cuda.Function, softcap: cuda.Function, top1: cuda.Function, @@ -93,7 +76,6 @@ pub const Kernels = struct { .mix_rows = try mod.function("tf_ink2_mix_rows"), .rowdot = try mod.function("tf_ink2_rowdot"), .topk = try mod.function("tf_ink2_topk"), - .gateup = try mod.function("tf_ink2_gateup"), .conv = try mod.function("tf_ink2_conv"), .softcap = try mod.function("tf_ink2_softcap"), .top1 = try mod.function("tf_ink2_top1"), @@ -159,13 +141,6 @@ pub fn topk(k: *const Kernels, s: cuda.Stream, scores: u64, bias: u64, pick: u64 try go(k.topk, s, .{ .x = @intCast(rows) }, 512, &a); } -/// The softcapped SwiGLU epilogue over `p` (row, slot) pairs, `n` wide: the grid of exl3_experts' gate/up epilogue. -pub fn gateup(k: *const Kernels, s: cuda.Stream, g: GateUpArgs) !void { - var a: cuda.Args = .{}; - a.add(g); - try go(k.gateup, s, .{ .x = @intCast(g.p), .y = @intCast(@divExact(g.n, 128)) }, 32, &a); -} - /// 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 { var a: cuda.Args = .{}; @@ -250,5 +225,4 @@ test "ops: the argument structs keep ops.cu's layouts" { try std.testing.expectEqual(@as(usize, 8 * 8 + 8 + 8 + 3 * 8 + 8 + 6 * 4), @sizeOf(MixArgs)); try std.testing.expectEqual(@as(usize, 9 * 8 + 2 * 8 + 7 * 4 + 4), @sizeOf(ConvArgs)); try std.testing.expectEqual(@as(usize, 32), @sizeOf(RewindSite)); - try std.testing.expectEqual(@as(usize, 6 * 8 + 6 * 4), @sizeOf(GateUpArgs)); } diff --git a/zig/tests/cuda/contract_inkling2_ops.zig b/zig/tests/cuda/contract_inkling2_ops.zig index 48cbc7606a8..b1c345f6039 100644 --- a/zig/tests/cuda/contract_inkling2_ops.zig +++ b/zig/tests/cuda/contract_inkling2_ops.zig @@ -16,6 +16,7 @@ const groups = .{ "embeds", "mixes", "dots", "topks", "gateups", "convs", "rewin pub const Set = struct { k: ref.Kernels = undefined, + ex: cuda.exl3_experts.Experts = undefined, loaded: bool = false, mixes: [7]G(mix.Mix) = undefined, embeds: [2]G(rows.Embed) = undefined, @@ -34,6 +35,8 @@ pub const Set = struct { /// Every registration, each control after the kernel it breaks, appended to `list`. pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { set.k = try ref.Kernels.load(gpu.d); + errdefer set.k.unload(); + set.ex = try cuda.exl3_experts.Experts.load(gpu.d); set.loaded = true; const k = &set.k; const rig: @import("contract_rig.zig").Rig = .{ .gpu = gpu, .s = s }; @@ -44,7 +47,7 @@ pub const Set = struct { 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.gateups, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .swapped = i == 1 } }; + for (&set.gateups, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .capped = set.ex.capped, .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 } }; @@ -59,6 +62,7 @@ pub const Set = struct { pub fn deinit(set: *Set) void { if (!set.loaded) return; inline for (groups) |f| for (&@field(set, f)) |*x| x.deinit(); + set.ex.unload(); set.k.unload(); set.loaded = false; } diff --git a/zig/tests/cuda/contract_inkling2_ops_route.zig b/zig/tests/cuda/contract_inkling2_ops_route.zig index 8e04891dab9..06bd1d58a7d 100644 --- a/zig/tests/cuda/contract_inkling2_ops_route.zig +++ b/zig/tests/cuda/contract_inkling2_ops_route.zig @@ -1,4 +1,4 @@ -//! Inkling 2's router and expert epilogues under the contract: tf_ink2_topk, tf_ink2_gateup, tf_ink2_prompt_tail. +//! Inkling 2's router and expert epilogues: tf_ink2_topk, core's tf_exl3_gateup_capped, tf_ink2_prompt_tail. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -143,19 +143,38 @@ 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 }, .{ .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)"; + const name = if (swapped) "control: inkling2 exl3 tf_exl3_gateup_capped with the caps swapped" else "inkling2 exl3 tf_exl3_gateup_capped (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 }; } +/// exl3_experts.cu's CappedArgs, field for field: act_mode 3, no clamp. +pub const CappedArgs = extern struct { + z: u64, + pick: u64, + svh_g: u64, + svh_u: u64, + suh_d: u64, + xd: u64, + p: i32, + n: i32, + sk: i32, + experts: i32, + limit: f32 = 0, + act_mode: i32 = 3, + gate_cap: f32, + up_cap: f32, +}; + /// xd = H(gcap tanh(g / gcap) sigmoid(g) ucap tanh(u / ucap) suh_d) 2^-3.5, g and u the split sums' H times svh. pub const Gateup = struct { kern: *const ops.Kernels, + capped: cuda.Function, // exl3_experts.Experts.capped swapped: bool = false, shape: c.Shape = undefined, z: []f32 = &.{}, // [(mat * sk + split) * P + pair] * n + column sv: [3][]u16 = .{ &.{}, &.{}, &.{} }, // fp16 [experts][n]: svh_g, svh_u, suh_d pick: []i32 = &.{}, - args: ops.GateUpArgs = undefined, + args: CappedArgs = undefined, pub const sums = {}; @@ -207,7 +226,10 @@ pub const Gateup = struct { } pub fn run(self: *Gateup, rig: *rig_.Rig) !void { - try ops.gateup(self.kern, rig.s, self.args); + var a: cuda.Args = .{}; + a.add(self.args); + const grid: cuda.Dim3 = .{ .x = @intCast(self.args.p), .y = @intCast(@divExact(self.args.n, 128)) }; + try cuda.launch.launch(self.capped, .{ .grid = grid, .block = .{ .x = 32 } }, rig.s, &a); } pub fn count(self: *const Gateup) usize { From d2361b7d5b6bae47e3d12f8a189b948ac069f6df Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:10:18 +1100 Subject: [PATCH 15/27] core: one image-rows module for the four vision families RADIO, MiniMax M3, Qwen 27 and Inkling 2 each kept their own copy of the placeholder span and the cut that maps a prompt pass onto it. They now share core.image_rows, started from RADIO's copy, and each family keeps only its own splice. The cut now works in usize and takes the offset before adding the buffer row, as RADIO's did. MiniMax M3 and Inkling 2 already cut in usize, so their results are unchanged. RADIO and Qwen 27 no longer overflow u32 on a span that ends past 2^32; nothing else changes. --- zig/src/core/image_rows.zig | 41 +++++++++++++++++++++ zig/src/core/root.zig | 3 ++ zig/src/families/inkling2/vision.zig | 33 +++++------------ zig/src/families/minimax_m3/cuda_vision.zig | 9 ++--- zig/src/families/qwen27/image_rows.zig | 10 ++--- zig/src/families/radio/rows.zig | 41 +++------------------ 6 files changed, 68 insertions(+), 69 deletions(-) create mode 100644 zig/src/core/image_rows.zig diff --git a/zig/src/core/image_rows.zig b/zig/src/core/image_rows.zig new file mode 100644 index 00000000000..2c477377f79 --- /dev/null +++ b/zig/src/core/image_rows.zig @@ -0,0 +1,41 @@ +//! Image placeholder rows of a prompt: which rows of a pass's image buffer each prompt row takes. +const std = @import("std"); + +/// An image's placeholder rows [at, at + n) of the prompt take buffer rows [row, row + n); `image` is its index. +pub const Span = struct { at: u32, n: u32, row: u32, image: u32 = 0 }; + +/// What a span gives prompt rows [lo, hi): `n` rows from prompt row `at` on, taken from buffer row `row` on. +pub const Cut = struct { at: usize, row: usize, n: usize }; + +/// The part of `sp` prompt rows [lo, hi) cross, or null for none. +pub fn cut(sp: Span, lo: usize, hi: usize) ?Cut { + const from = @max(lo, sp.at); + const to = @min(hi, @as(usize, sp.at) + sp.n); + return if (from < to) .{ .at = from, .row = sp.row + (from - sp.at), .n = to - from } else null; // offset first +} + +/// Rows the spans hold in all. +pub fn total(spans: []const Span) u32 { + var n: u32 = 0; + for (spans) |s| n += s.n; + return n; +} + +test "a cut near the top of the u32 range takes its offset before adding the buffer row" { + const sp: Span = .{ .at = 0xffffff00, .n = 128, .row = 256 }; + try std.testing.expectEqual(Cut{ .at = 0xffffff00, .row = 256, .n = 0x40 }, cut(sp, 0xffffff00, 0xffffff40).?); + try std.testing.expectEqual(Cut{ .at = 0xffffff40, .row = 320, .n = 0x40 }, cut(sp, 0xffffff40, 0xffffffff).?); + try std.testing.expect(cut(sp, 0xffffff80, 0xffffffff) == null); + const top: Span = .{ .at = 0xffffff80, .n = 0x100, .row = 0xffffff00 }; // ends past 2^32 on both sides + try std.testing.expectEqual(Cut{ .at = 0xffffffc0, .row = 0xffffff40, .n = 0x40 }, cut(top, 0xffffffc0, 0x100000000).?); +} + +test "a chunk takes the rows it crosses: a span cut at both ends, and none past it" { + const first: Span = .{ .at = 5, .n = 256, .row = 0 }; + const second: Span = .{ .at = 300, .n = 300, .row = 256, .image = 1 }; + try std.testing.expectEqual(Cut{ .at = 200, .row = 195, .n = 61 }, cut(first, 200, 400).?); + try std.testing.expectEqual(Cut{ .at = 300, .row = 256, .n = 100 }, cut(second, 200, 400).?); + try std.testing.expectEqual(Cut{ .at = 5, .row = 0, .n = 256 }, cut(first, 0, 1000).?); + try std.testing.expect(cut(first, 261, 300) == null and cut(second, 600, 700) == null); + try std.testing.expectEqual(@as(u32, 556), total(&.{ first, second })); +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 070b01a5a36..24955286902 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -63,6 +63,8 @@ pub const modelopt = @import("modelopt.zig"); 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. pub const qwen_vl = @import("qwen_vl/qwen_vl.zig"); +/// Image placeholder spans of a prompt and the part of each a prompt pass takes, for every vision family. +pub const image_rows = @import("image_rows.zig"); pub const drafter_release = @import("drafter_release.zig"); pub const drafter_layout = @import("drafter_layout.zig"); pub const dspine = @import("dspine.zig"); @@ -147,6 +149,7 @@ test { _ = modelopt; _ = picture; _ = qwen_vl; + _ = image_rows; _ = @import("nvfp4_fixture_test.zig"); _ = @import("drafter_release_test.zig"); _ = kv_pool; diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig index 6168fa1bee4..d06bbc4b2bc 100644 --- a/zig/src/families/inkling2/vision.zig +++ b/zig/src/families/inkling2/vision.zig @@ -310,8 +310,8 @@ fn admit(p: image.Prepared, max_tokens: u32) !void { if (T > max_tokens) return error.ImageTooLarge; } -/// 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 }; +const image_rows = core.image_rows; +pub const Span = image_rows.Span; /// 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 { @@ -333,32 +333,19 @@ pub fn spans(a: std.mem.Allocator, ids: []const u32) ![]Span { 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; + if (image_rows.total(list) != 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) }; -} - -/// A copy's bytes for bf16 rows `hidden` wide: the offset into the pass, the offset into the image rows, the length. -pub fn copyBytes(c: Copy, hidden: u32) [3]u64 { +/// A cut's bytes for a pass from `lo`, bf16 rows `hidden` wide: offsets into the pass and the image rows, the length. +pub fn copyBytes(c: image_rows.Cut, lo: usize, hidden: u32) [3]u64 { const row: u64 = @as(u64, hidden) * 2; - return .{ c.dst * row, c.src * row, c.n * row }; + return .{ (c.at - lo) * row, c.row * row, c.n * row }; } /// 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, hidden: u32, rows: u64, list: []const Span, lo: usize, hi: usize, x: u64) !void { for (list) |sp| { - const b = copyBytes(cut(sp, lo, hi) orelse continue, hidden); + const b = copyBytes(image_rows.cut(sp, lo, hi) orelse continue, lo, hidden); try d.check(d.api.cuMemcpyDtoDAsync_v2(x + b[0], rows + b[1], b[2], s.handle), "cuMemcpyDtoDAsync"); } } @@ -388,8 +375,8 @@ test "chunked passes give every placeholder the row masked_scatter gives it" { 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); + for (list) |sp| if (image_rows.cut(sp, lo, hi)) |c| for (0..c.n) |i| { + got[c.at + i] = @intCast(c.row + i); }; } var next: i32 = 0; // masked_scatter: the k-th placeholder in the prompt takes feature row k @@ -413,7 +400,7 @@ test "the splice copies rows as wide as the config's decoder, Small's 4608 and M const sp: Span = .{ .at = 3, .n = 5, .row = 7 }; for ([_]u32{ 4608, 2304 }) |h| { const v = testVision(h); - const b = copyBytes(cut(sp, 4, 6).?, v.text_hidden); + const b = copyBytes(image_rows.cut(sp, 4, 6).?, 4, v.text_hidden); try std.testing.expectEqual([3]u64{ 0, 8 * @as(u64, h) * 2, 2 * @as(u64, h) * 2 }, b); } // the projector's scratch row is projection_hidden_dim wide (4096 in both releases) diff --git a/zig/src/families/minimax_m3/cuda_vision.zig b/zig/src/families/minimax_m3/cuda_vision.zig index 5f1b24c485f..f5ed74cbb5a 100644 --- a/zig/src/families/minimax_m3/cuda_vision.zig +++ b/zig/src/families/minimax_m3/cuda_vision.zig @@ -31,8 +31,7 @@ pub const image_config: vl.Config = .{ .depth = depth, .hidden = width, .heads = /// A request's image limits (--vision): image tokens in all and images. pub const Limits = struct { image_tokens: u32, max_images: u32 }; -/// Prompt rows [at, at + n) take image rows [row, row + n). -pub const Span = struct { at: u32, n: u32, row: u32 }; +pub const Span = core.image_rows.Span; /// An image's bytes to patches in merge order: torchvision's antialiased bicubic, then CLIP's mean and std. pub fn prepare(io: std.Io, gpa: std.mem.Allocator, bytes: []const u8, budget: u32) !vl.geometry.Prepared { @@ -279,10 +278,8 @@ pub const Images = struct { /// A sequence's image rows over prompt rows [lo, hi) of its pass, into the residual rows at `resid` (row lo first). pub fn splice(mk: *const kern.Kernels, s: cuda.Stream, rows: u64, spans: []const Span, lo: usize, hi: usize, resid: u64) !void { for (spans) |sp| { - const a = @max(lo, sp.at); - const b = @min(hi, sp.at + sp.n); - if (a >= b) continue; - try kern.splice(mk, s, rows + (sp.row + (a - sp.at)) * hidden * 2, resid + (a - lo) * hidden * 4, b - a, hidden); + const c = core.image_rows.cut(sp, lo, hi) orelse continue; + try kern.splice(mk, s, rows + c.row * hidden * 2, resid + (c.at - lo) * hidden * 4, c.n, hidden); } } diff --git a/zig/src/families/qwen27/image_rows.zig b/zig/src/families/qwen27/image_rows.zig index 946bd341231..f990639434d 100644 --- a/zig/src/families/qwen27/image_rows.zig +++ b/zig/src/families/qwen27/image_rows.zig @@ -1,12 +1,12 @@ //! A round's rows under M-RoPE: each window's rope positions from its slot's images, and the rows image rows replace. const std = @import("std"); -const mrope = @import("core").qwen_vl.rope; +const core = @import("core"); +const mrope = core.qwen_vl.rope; const Ref = @import("projection.zig").Ref; const Round = @import("round_plan.zig").Round; const Frame = @import("gpu_frame.zig").Frame; -/// One image's rows in a prompt pass: prompt rows [at, at + n) take rows [row, row + n) of the pass's image rows. -pub const Span = struct { at: u32, n: u32, row: u32 }; +pub const Span = core.image_rows.Span; /// A prompt pass's images: the stream in `slot` takes `rows` (bf16, the model's width) at its spans. pub const Images = struct { slot: u32, rows: Ref, spans: []const Span }; @@ -38,8 +38,8 @@ fn placeRows(pos: []i32, takes: []i32, cap: usize, rope: []const mrope.Layout, i pos[2 * cap + row] = x[2]; grid = grid or x[1] != x[0] or x[2] != x[0]; takes[row] = -1; - if (images) |im| if (im.slot == slot) for (im.spans) |s| if (p >= s.at and p < s.at + s.n) { - takes[row] = @intCast(s.row + (p - s.at)); + if (images) |im| if (im.slot == slot) for (im.spans) |s| if (core.image_rows.cut(s, p, @as(usize, p) + 1)) |c| { + takes[row] = @intCast(c.row); took = true; }; } diff --git a/zig/src/families/radio/rows.zig b/zig/src/families/radio/rows.zig index af9db179ef3..760d9b8ccbf 100644 --- a/zig/src/families/radio/rows.zig +++ b/zig/src/families/radio/rows.zig @@ -2,10 +2,11 @@ const std = @import("std"); const cuda = @import("cuda"); const Image = @import("lanes").stream.Image; +const image_rows = @import("core").image_rows; const Allocator = std.mem.Allocator; -/// An image's placeholder rows [at, at + n) of the prompt, its rows from `row` of the buffer, `image` its index. -pub const Span = struct { at: u32, n: u32, row: u32, image: u32 }; +pub const Span = image_rows.Span; +pub const total = image_rows.total; /// The images a prompt pass from `from` reads, in prompt order, their rows back to back from row 0. pub fn plan(a: Allocator, images: []const Image, from: u32) ![]Span { @@ -23,13 +24,6 @@ pub fn plan(a: Allocator, images: []const Image, from: u32) ![]Span { return out.toOwnedSlice(a); } -/// Rows the spans hold in all. -pub fn total(spans: []const Span) u32 { - var n: u32 = 0; - for (spans) |s| n += s.n; - return n; -} - /// bf16 [limit, hidden] row-major: a pass's image rows, filled on rank 0 and broadcast whole to the others. pub const Rows = struct { d: *const cuda.Driver, @@ -63,27 +57,13 @@ pub const Rows = struct { const w = r.hidden * 2; for (spans) |sp| { if (sp.row + sp.n > r.limit) return error.ImageRows; - const from, const row, const n = cut(sp, lo, hi) orelse continue; - const src = r.buf.ptr + @as(u64, row) * w; - try r.d.check(r.d.api.cuMemcpyDtoDAsync_v2(emb + @as(u64, from - lo) * w, src, @as(usize, n) * w, s.handle), "cuMemcpyDtoDAsync"); + const c = image_rows.cut(sp, lo, hi) orelse continue; + const src = r.buf.ptr + @as(u64, c.row) * w; + try r.d.check(r.d.api.cuMemcpyDtoDAsync_v2(emb + @as(u64, c.at - lo) * w, src, c.n * w, s.handle), "cuMemcpyDtoDAsync"); } } }; -/// The part of `sp` prompt rows [lo, hi) cross: its first prompt row, its first buffer row, its rows; null for none. -pub fn cut(sp: Span, lo: u32, hi: u32) ?[3]u32 { - const from = @max(lo, sp.at); - const to = @min(hi, sp.at + sp.n); - return if (from < to) .{ from, sp.row + (from - sp.at), to - from } else null; // the offset first: no u32 overflow -} - -test "a cut near the top of the u32 range takes its offset before adding the buffer row" { - const sp: Span = .{ .at = 0xffffff00, .n = 128, .row = 256, .image = 0 }; - try std.testing.expectEqual([3]u32{ 0xffffff00, 256, 0x40 }, cut(sp, 0xffffff00, 0xffffff40).?); - try std.testing.expectEqual([3]u32{ 0xffffff40, 320, 0x40 }, cut(sp, 0xffffff40, 0xffffffff).?); - try std.testing.expect(cut(sp, 0xffffff80, 0xffffffff) == null); -} - test "a pass from a restored point plans only the images that end past it, rows back to back" { const a = std.testing.allocator; const imgs = [_]Image{ @@ -101,12 +81,3 @@ test "a pass from a restored point plans only the images that end past it, rows const overlapping = [_]Image{ imgs[1], imgs[0] }; try std.testing.expectError(error.ImageSpans, plan(a, &overlapping, 0)); } - -test "a chunk takes the rows it crosses: a span cut at both ends, and none past it" { - const first: Span = .{ .at = 5, .n = 256, .row = 0, .image = 0 }; - const second: Span = .{ .at = 300, .n = 300, .row = 256, .image = 1 }; - try std.testing.expectEqual([3]u32{ 200, 195, 61 }, cut(first, 200, 400).?); - try std.testing.expectEqual([3]u32{ 300, 256, 100 }, cut(second, 200, 400).?); - try std.testing.expectEqual([3]u32{ 5, 0, 256 }, cut(first, 0, 1000).?); - try std.testing.expect(cut(first, 261, 300) == null and cut(second, 600, 700) == null); -} From 95150b6b614e69167cf5c75bb57d59d2d7b4c593 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sat, 21 Nov 2026 22:10:58 +1100 Subject: [PATCH 16/27] vit: give the pointwise kernel a gamma mode Inkling 2's tf_ink2v_scale_add was a layer-scaled residual add, which is tf_vit_pointwise with a per-column scale between the activation and the add. vit.cu now has tf_vit_pointwise_gamma for that, and the tower calls it through vit.Kernels.pointwiseGamma. Its fp32 multiply, bf16 rounding and add are the same round-to-nearest steps the family kernel took, so the tower's results are unchanged. Every existing function in vit.cu and inkling2/vision.cu compiles to the same SASS on sm_80, 86, 89, 120 and 121 under nvcc 13.0 and 13.3. The contract now registers the core kernel, with the late-gamma control retargeted to it; its records come from cuobjdump -res-usage, and 13.2 stays pending. --- zig/kernels/cuda/inkling2/vision.cu | 10 +--------- zig/kernels/cuda/vit.cu | 15 +++++++++++++-- .../core/contract/inkling2_experts_records.zig | 2 +- .../core/contract/measurements/pending_133.zig | 2 +- zig/src/cuda/vit.zig | 14 ++++++++++++++ zig/src/families/inkling2/vision.zig | 15 ++------------- zig/tests/cuda/contract_inkling2_experts.zig | 6 +++++- .../cuda/contract_inkling2_experts_vision.zig | 10 +++++----- zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 9 files changed, 44 insertions(+), 34 deletions(-) diff --git a/zig/kernels/cuda/inkling2/vision.cu b/zig/kernels/cuda/inkling2/vision.cu index abc3b6c6296..1554ac5cbb0 100644 --- a/zig/kernels/cuda/inkling2/vision.cu +++ b/zig/kernels/cuda/inkling2/vision.cu @@ -1,4 +1,4 @@ -// Inkling 2's vision tower glue: patch rows to the sequence, axial rotary, layer-scaled residuals. +// Inkling 2's vision tower glue: patch rows to the sequence and axial rotary. #include #include @@ -53,11 +53,3 @@ extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_rope(__nv_bfloat p[1] = tobf(__fadd_rn(__fmul_rn(b, c), __fmul_rn(a, s))); } } - -// x = bf16(x + bf16(gamma y)), the layer scale; a gamma mode on vit.cu's tf_vit_pointwise could replace it later. -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/kernels/cuda/vit.cu b/zig/kernels/cuda/vit.cu index def2b3303d6..7e40c45725e 100644 --- a/zig/kernels/cuda/vit.cu +++ b/zig/kernels/cuda/vit.cu @@ -30,11 +30,13 @@ __device__ __forceinline__ float gelu_erf(float x) { return __fmul_rn(__fmul_rn(x, 0.5f), __fadd_rn(1.0f, erff(__fmul_rn(x, alpha)))); } -// bf16(act(v)), then bf16(R[at] + v) when R; v is already rounded to bf16. -__device__ __forceinline__ __nv_bfloat16 pointwise_at(float v, const __nv_bfloat16* R, int64_t at, int act) { +// bf16(act(v)), bf16(G[at % width] v) when G, then bf16(R[at] + v) when R; v is already rounded to bf16. +__device__ __forceinline__ __nv_bfloat16 pointwise_at(float v, const __nv_bfloat16* R, int64_t at, int act, + const __nv_bfloat16* G = nullptr, int width = 1) { if (act == 1) v = rbf(gelu_tanh(v)); if (act == 2) v = rbf(gelu_erf(v)); if (act == 3) v = rbf(v > 0.0f ? __fmul_rn(v, v) : 0.0f); + if (G) v = rbf(__fmul_rn(bf(G[at % width]), v)); return __float2bfloat16_rn(R ? __fadd_rn(bf(R[at]), v) : v); } @@ -71,6 +73,15 @@ extern "C" __global__ void __launch_bounds__(NT) tf_vit_pointwise(const __nv_bfl O[at] = pointwise_at(bf(X[at]), R, at, act); } +// tf_vit_pointwise with a layer scale G [width] between act and the add: torch's `r + gamma * h` (Inkling 2). +extern "C" __global__ void __launch_bounds__(NT) tf_vit_pointwise_gamma(const __nv_bfloat16* X, const __nv_bfloat16* R, __nv_bfloat16* O, + int64_t count, int act, const __nv_bfloat16* __restrict__ G, + int width) { + const int64_t at = static_cast(blockIdx.x) * NT + threadIdx.x; + if (at >= count) return; + O[at] = pointwise_at(bf(X[at]), R, at, act, G, width); +} + // Block (row, column block): bias then pointwise, keeping the intermediate bf16 rounding in a register. extern "C" __global__ void __launch_bounds__(NT) tf_vit_bias_act(const float* __restrict__ ACC, const __nv_bfloat16* __restrict__ BIAS, const __nv_bfloat16* R, __nv_bfloat16* O, int N, int act) { diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 18507ea3ee9..e312fe88a43 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -7,7 +7,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "exl3_experts tf_exl3_gateup_capped (Inkling 2)", .symbol = "tf_exl3_gateup_capped", .image = "exl3_experts", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } }, .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 = "vit tf_vit_pointwise_gamma (Inkling 2)", .symbol = "tf_vit_pointwise_gamma", .image = "vit", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .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 = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .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 = 96, .static = 5120, .bound = 128 }, .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 111, .static = 5120, .bound = 128 }, .{ .regs = 111, .static = 5120, .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 = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index 8111b6052f7..6a61b1ae580 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -9,7 +9,7 @@ pub const records = [_]Override{ .{ .name = "exl3_experts tf_exl3_gateup_capped (Inkling 2)", .usage = .{ .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, .{ .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 = "vit tf_vit_pointwise_gamma (Inkling 2)", .usage = .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .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/vit.zig b/zig/src/cuda/vit.zig index 6d56690b677..7b5aa96931a 100644 --- a/zig/src/cuda/vit.zig +++ b/zig/src/cuda/vit.zig @@ -29,6 +29,7 @@ pub const Kernels = struct { g4_gelu_fn: module.Function, g4_pool_fn: module.Function, pointwise_fn: module.Function, + pointwise_gamma_fn: module.Function, bias_fn: module.Function, bias_act_fn: module.Function, unshuffle_fn: module.Function, @@ -49,6 +50,7 @@ pub const Kernels = struct { .g4_gelu_fn = try mod.function("tf_vit_g4_gelu_mul"), .g4_pool_fn = try mod.function("tf_vit_g4_pool"), .pointwise_fn = try mod.function("tf_vit_pointwise"), + .pointwise_gamma_fn = try mod.function("tf_vit_pointwise_gamma"), .bias_fn = try mod.function("tf_vit_bias"), .bias_act_fn = try mod.function("tf_vit_bias_act"), .unshuffle_fn = try mod.function("tf_vit_unshuffle"), @@ -122,6 +124,18 @@ pub const Kernels = struct { try go(k.pointwise_fn, s, blocks(count, threads), 1, &a); } + /// pointwise with a layer scale: o = bf16(r + bf16(gamma[i % width] act(x))), gamma bf16 [width]. + pub fn pointwiseGamma(k: *const Kernels, s: Stream, x: u64, r: ?u64, o: u64, count: usize, act: Act, gamma: u64, width: usize) !void { + if (width == 0) return error.RowShape; + var a: Args = .{}; + for ([_]u64{ x, r orelse 0, o }) |p| a.add(p); + a.add(@as(i64, @intCast(count))); + a.add(@backingInt(act)); + a.add(gamma); + a.add(int(width)); + try go(k.pointwise_gamma_fn, s, blocks(count, threads), 1, &a); + } + /// o [rows, n] = bf16(acc + b), acc f32. pub fn bias(k: *const Kernels, s: Stream, acc: u64, b: u64, o: u64, rows: usize, n: usize) !void { var a: Args = .{}; diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig index d06bbc4b2bc..9d6eace57b6 100644 --- a/zig/src/families/inkling2/vision.zig +++ b/zig/src/families/inkling2/vision.zig @@ -25,7 +25,6 @@ pub const Kernels = struct { mod: cuda.Module, 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; @@ -35,7 +34,6 @@ pub const Kernels = struct { .mod = mod, .embed = try mod.function("tf_ink2v_embed"), .rope = try mod.function("tf_ink2v_rope"), - .scale_add = try mod.function("tf_ink2v_scale_add"), }; return k; } @@ -286,20 +284,11 @@ pub const Tower = struct { try go(t.k.rope, s, .{ .x = @intCast(R) }, 256, 0, &a); try t.fa.full(s, t.qkv, t.att, R, heads, head_dim, 1.0 / @sqrt(@as(f32, head_dim))); 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.pointwiseGamma(s, t.y, t.x, t.x, R * width, .none, l.ls1, width); // torch's `x + gamma * h` 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); + try t.vk.pointwiseGamma(s, t.y, t.x, t.x, R * width, .none, l.ls2, width); } }; diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig index 5c89bbe40ba..bdf77db4871 100644 --- a/zig/tests/cuda/contract_inkling2_experts.zig +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -18,6 +18,7 @@ pub const Set = struct { vk: ink.vision.Kernels = undefined, mk: ink.modelopt.Kernels = undefined, fa: cuda.vit.Attention = undefined, + vt: cuda.vit.Kernels = undefined, projections: [2]grouped.Grouped = undefined, moe: [13]modelopt.ModelOpt = undefined, embeds: [2]ref.Gated(vision.Embed) = undefined, @@ -35,6 +36,8 @@ pub const Set = struct { errdefer set.mk.unload(); set.fa = try cuda.vit.Attention.load(gpu.d); errdefer set.fa.unload(); + set.vt = try cuda.vit.Kernels.load(gpu.d); + errdefer set.vt.unload(); const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; for (&set.projections, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .fault = if (i == 1) .swapped else .none }; const prompt = [13]bool{ false, true, false, true, false, true, false, false, false, true, false, false, false }; @@ -56,7 +59,7 @@ pub const Set = struct { }; 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.adds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vt, .late = i == 1 } }; set.attn = .{ .rig = rig, .att = &set.fa }; set.live = true; for (&set.projections) |*x| try list.append(a, x.kernel()); @@ -75,6 +78,7 @@ pub const Set = struct { for (&set.embeds) |*x| x.deinit(); for (&set.moe) |*x| x.deinit(); for (&set.projections) |*x| x.deinit(); + set.vt.unload(); set.fa.unload(); set.mk.unload(); set.vk.unload(); diff --git a/zig/tests/cuda/contract_inkling2_experts_vision.zig b/zig/tests/cuda/contract_inkling2_experts_vision.zig index 976a8ce7448..61e022cbb71 100644 --- a/zig/tests/cuda/contract_inkling2_experts_vision.zig +++ b/zig/tests/cuda/contract_inkling2_experts_vision.zig @@ -1,4 +1,4 @@ -//! Inkling 2's tower glue (vision.cu) under the contract: patch rows to the sequence, axial rotary, layer-scaled adds. +//! Inkling 2's tower glue under the contract: patch rows to the sequence, axial rotary (vision.cu), layer-scaled adds. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -208,9 +208,9 @@ pub const Rope = struct { } }; -/// x = bf16(x + bf16(gamma[i % 1024] y)) over [R, 1024] in place: torch's `residual + lambda * h` in bf16. +/// tf_vit_pointwise_gamma as the tower runs it: x = bf16(x + bf16(gamma[i % 1024] y)) over [R, 1024] in place. pub const ScaleAdd = struct { - kern: *const Kernels, + kern: *const cuda.vit.Kernels, late: bool = false, // control: gamma read one column late shape: c.Shape = undefined, x: []u16 = &.{}, @@ -220,7 +220,7 @@ pub const ScaleAdd = struct { 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)"; + const name = if (self.late) "inkling2 experts control: tf_vit_pointwise_gamma reading gamma one column late" else "inkling2 vit tf_vit_pointwise_gamma (layer-scaled residual add, in place)"; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &add_served }; } @@ -259,7 +259,7 @@ pub const ScaleAdd = struct { 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)); + try self.kern.pointwiseGamma(rig.s, self.dev[0], self.out, self.out, n, .none, self.dev[1] + @as(u64, if (self.late) 2 else 0), width); } pub fn count(self: *const ScaleAdd) usize { diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index aaf316741d3..37e1362184a 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -79,7 +79,7 @@ zig/kernels/cuda/torch_ops/nucleus.cu c3328dc3ad1fb28c820c343f22c10dd1b4f9a9d8c8 zig/kernels/cuda/torch_ops/pointwise.cu 3d3118159265538679968e56a8c4b5d61b01c07487530e95e4f93ba8662f98c8 raw zig/kernels/cuda/torch_ops/topk.cu 0b5ddb5b02af2ebd9a3992cb11bb80eefd7547c32d6dfdafdf216ab484dd1627 raw zig/kernels/cuda/train_mixers.cuh cec88446cede27c941da254d94f81afa1c92c6880e63bfd66a0efcdc7f95aa13 raw -zig/kernels/cuda/vit.cu 5bdb9bb4e247c1deb6d5e30bc65aa7976786b1a3f55569e1729a87717d2e37b3 raw #2239 (tf_vit_conv_cols and tf_vit_conv_flatten for Qwen3-ASR's audio tower; existing kernels unchanged) +zig/kernels/cuda/vit.cu b33259c5a546a60a05e00e07bb307ec31560040e3d256807992408bf8e21af6a raw #2239 (tf_vit_conv_cols and tf_vit_conv_flatten for Qwen3-ASR's audio tower; existing kernels unchanged); #4127: tf_vit_pointwise_gamma added for Inkling 2's layer scale, existing functions unchanged zig/src/cuda/abi.zig fef21a6302d1863001496b3765899a265470cfdf78678d7f73fa7fd3115d2a93 raw commits ef23b5934; 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/aot.zig bd4e41f32eebf8e75e6f40e036847aaca2900aee7628167552c661824c79d62b raw commits 9349e38bb; series patches 14-runtime-foundation.patch, 45-runtime-one-fallback.patch, 46-preserve-nospec-and-capture.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 3a7e6fac7 (identity export for persisted serving states) zig/src/cuda/carveout.zig 5ebe77d420ec42d1494fbe7259ce12e20e56427d8f7d931d672b7ca1240b1759 raw main 6a1feb26e (malformed TF_CUDA_CARVEOUT settings refused by name) @@ -113,7 +113,7 @@ zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125d zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0bd5f468ace3 raw main 13d7450fd (#2354), 7ead07c92 (bounded peer warm-up, #2512) zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw -zig/src/cuda/vit.zig 3a22b6aaf70bcf83a1d3c7624c8c554e262e69d12be07b6e6b389702f77b5877 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) +zig/src/cuda/vit.zig 222f8151384518297c157e6dd270c04674ae288d8a180e5e1d117a5ce41c86ed raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw zig/src/families/flashnext/cuda_batch.zig 318500bd273d45ed2a2021252ee447e0a25a390f85c7534a79d9781883e19301 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged; this change: a one-rank prompt chunk before the last that nothing taps skips its last layer's MLP stream and experts, which head(.none) never reads; outputs unchanged zig/src/families/flashnext/cuda_batch_state.zig a2ec8aa19551587fc034fe2791493e95a502e37e5f78e0cfd3c360308bf65a52 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; #3368 (the scratch sized by the checkpoint's slot count and shared width; default-shape replies unchanged); y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; D1040 (opt-in TF_FLASHNEXT_GRAPH_TAIL) From e1b68552f6ea172e821da55095cdf07be91263fb Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sun, 22 Nov 2026 14:08:48 +1100 Subject: [PATCH 17/27] qwen27: export core's image rows from the roots Qwen 2.7 builds against The Metal and residency builds give qwen27 its own core roots, which lacked image_rows after the shared module moved into core. --- zig/qwen27_core.zig | 1 + zig/residency_owner_tests.zig | 1 + zig/src/tensorfold.zig | 1 + 3 files changed, 3 insertions(+) diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index b309ce2fd32..b3880df10db 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -11,6 +11,7 @@ pub const npy = @import("src/core/npy.zig"); pub const tokenizer = @import("tokenizer"); /// Qwen-VL image input's backend-neutral parts (M-RoPE positions for the forward). pub const qwen_vl = @import("src/core/qwen_vl/qwen_vl.zig"); +pub const image_rows = @import("src/core/image_rows.zig"); pub const segments = @import("src/core/segments.zig"); pub const prompt_tail = @import("src/core/prompt_tail.zig"); diff --git a/zig/residency_owner_tests.zig b/zig/residency_owner_tests.zig index b1b8657fc36..c9832508dbd 100644 --- a/zig/residency_owner_tests.zig +++ b/zig/residency_owner_tests.zig @@ -21,6 +21,7 @@ pub const shared_attention = @import("src/core/shared_attention.zig"); pub const segments = @import("src/core/segments.zig"); pub const bf16_topk_gpu = @import("bf16_topk_gpu"); pub const qwen_vl = @import("src/core/qwen_vl/qwen_vl.zig"); +pub const image_rows = @import("src/core/image_rows.zig"); pub const tree_round = @import("tree_round"); pub const tree_round_gpu = @import("tree_round_gpu"); pub const tree_commit_gpu = @import("tree_commit_gpu"); diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 16630a418d7..33eae89df3f 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -17,6 +17,7 @@ pub const checkpoint_metal = checkpoint; pub const qwen27 = @import("families/qwen27/qwen27.zig"); /// Qwen-VL image input: backend-neutral parts, and the tower on Metal. pub const qwen_vl = @import("core/qwen_vl/qwen_vl.zig"); +pub const image_rows = @import("core/image_rows.zig"); pub const qwen_vl_tower = @import("core/qwen_vl/metal.zig"); /// Qwen-Image-2.1's transformer on Metal: a denoiser driven by tf-qwen-image, outside the lane engine. pub const qwen_image = @import("families/qwen_image/qwen_image.zig"); From 8bae5764289a5dbb38d257d68d9fcc0881824724 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 12:17:20 +1100 Subject: [PATCH 18/27] exl3: round the capped expert epilogue as written Core builds exl3_experts.cu with contraction on, so the soft-capped SwiGLU's products and sum fused into FMAs, and Inkling 2 Small's tokens no longer matched the build it was validated on. Explicitly rounded operations give the SASS the old text has at the glue kernels' flags. --- zig/kernels/cuda/exl3_experts.cu | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/zig/kernels/cuda/exl3_experts.cu b/zig/kernels/cuda/exl3_experts.cu index bea32a422d8..f9974c08c4b 100644 --- a/zig/kernels/cuda/exl3_experts.cu +++ b/zig/kernels/cuda/exl3_experts.cu @@ -223,9 +223,10 @@ extern "C" __global__ void tf_exl3_gateup_capped(const CappedArgs c) { for (int j = 0; j < 4; ++j) { const float g = gv[j] * HAD_SCALE * __half2float(a.svh_g[(size_t)e * a.n + n + j]); const float u = uv[j] * HAD_SCALE * __half2float(a.svh_u[(size_t)e * a.n + n + j]); - const float act = - c.gate_cap * tanhf(g / c.gate_cap) * (1.f / (1.f + expf(-g))) * c.up_cap * tanhf(u / c.up_cap); - v[j] = act * __half2float(a.suh_d[(size_t)e * a.n + n + j]); + // Each product and the sum round on their own: core's flags would otherwise fuse them into FMAs. + const float gs = __fmul_rn(__fmul_rn(c.gate_cap, tanhf(g / c.gate_cap)), 1.f / __fadd_rn(1.f, expf(-g))); + const float act = __fmul_rn(__fmul_rn(gs, c.up_cap), tanhf(u / c.up_cap)); + v[j] = __fmul_rn(act, __half2float(a.suh_d[(size_t)e * a.n + n + j])); } gateup_store(a, p, n, lane, v); } From e128c7ad90b1907d53c1228cdbbd23c24e0bd533 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:43:00 +0000 Subject: [PATCH 19/27] inkling2: main's capped epilogue and layer scale equal the core kernels, bit for bit With #4127, Inkling 2's softcapped gate/up epilogue and vision layer scale come from core (tf_exl3_gateup_capped, tf_vit_pointwise_gamma) in place of main's family kernels (tf_ink2_gateup, built at --fmad=false, and tf_ink2v_scale_add). A host test writes both kernels' arithmetic at their rounding points: every product and sum on its own, the same order, the shared rotation and the fp16 or bf16 store. Over 512 random 128-column blocks with saturating and non-finite inputs, and 65,536 layer-scale values, the old and new forms give the same bits. A control contracts one product into the rotation's first sum, as core's fmad=true flags would without the explicit _rn operations, and it differs, so the comparison can see one fused rounding. --- zig/src/families/inkling2/inkling2.zig | 1 + .../families/inkling2/shared_kernels_test.zig | 140 ++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 zig/src/families/inkling2/shared_kernels_test.zig diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index f311dc17d35..3d437042dd0 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -25,4 +25,5 @@ test { _ = loop; _ = loop_model; _ = loop_math_cuda; + _ = @import("shared_kernels_test.zig"); } diff --git a/zig/src/families/inkling2/shared_kernels_test.zig b/zig/src/families/inkling2/shared_kernels_test.zig new file mode 100644 index 00000000000..6da0c5a0b47 --- /dev/null +++ b/zig/src/families/inkling2/shared_kernels_test.zig @@ -0,0 +1,140 @@ +//! Main's tf_ink2_gateup and tf_ink2v_scale_add against the core kernels replacing them, bit for bit at every rounding. +const std = @import("std"); + +const had: f32 = 0.08838834764831845; // exl3_decode.cuh's HAD_SCALE, 1 / sqrt(128) +const gate_cap: f32 = 4; +const up_cap: f32 = 25; + +/// Stand-ins for the device tanhf and expf: both kernels call the same functions, so the test fixes the rest. +fn tanh(x: f32) f32 { + return std.math.tanh(x); +} +fn exp(x: f32) f32 { + return @exp(x); +} + +/// ops.cu: `gate_cap * tanhf(g / gate_cap) * (1.f / (1.f + expf(-g))) * up_cap * tanhf(u / up_cap)`, left to right. +fn oldAct(g: f32, u: f32, gc: f32, uc: f32) f32 { + return gc * tanh(g / gc) * (1.0 / (1.0 + exp(-g))) * uc * tanh(u / uc); +} + +/// exl3_experts.cu: `gs = (gc * tanhf(g / gc)) * (1 / (1 + expf(-g)))`, then `act = (gs * uc) * tanhf(u / uc)`. +fn newAct(g: f32, u: f32, gc: f32, uc: f32) f32 { + const gs = (gc * tanh(g / gc)) * (1.0 / (1.0 + exp(-g))); + return (gs * uc) * tanh(u / uc); +} + +const Form = enum { old, new, fused }; + +/// One expert pair's 128-column block after the shared sums and rotation: each column's product, the rotation, fp16. +fn block(form: Form, gv: *const [128]f32, uv: *const [128]f32, sg: *const [128]f16, su: *const [128]f16, sd: *const [128]f16, out: *[128]u16) void { + var act: [128]f32 = undefined; + for (&act, 0..) |*a, c| { + const g = gv[c] * had * @as(f32, sg[c]); + const u = uv[c] * had * @as(f32, su[c]); + a.* = if (form == .old) oldAct(g, u, gate_cap, up_cap) else newAct(g, u, gate_cap, up_cap); + } + // fwht128: lane l holds columns 4l..4l+3; its first stage adds the products, then five shuffle stages + var v: [32][4]f32 = undefined; + for (0..32) |l| { + const p = [4]f32{ act[4 * l] * @as(f32, sd[4 * l]), act[4 * l + 1] * @as(f32, sd[4 * l + 1]), act[4 * l + 2] * @as(f32, sd[4 * l + 2]), act[4 * l + 3] * @as(f32, sd[4 * l + 3]) }; + // Contracted at fmad=true without explicit _rn: the first product fuses into each first-stage sum. + const a = if (form == .fused) @mulAdd(f32, act[4 * l], @as(f32, sd[4 * l]), p[1]) else p[0] + p[1]; + const b = if (form == .fused) @mulAdd(f32, act[4 * l], @as(f32, sd[4 * l]), -p[1]) else p[0] - p[1]; + const c = if (form == .fused) @mulAdd(f32, act[4 * l + 2], @as(f32, sd[4 * l + 2]), p[3]) else p[2] + p[3]; + const d = if (form == .fused) @mulAdd(f32, act[4 * l + 2], @as(f32, sd[4 * l + 2]), -p[3]) else p[2] - p[3]; + v[l] = .{ a + c, b + d, a - c, b - d }; + } + var m: usize = 1; + while (m < 32) : (m <<= 1) { + const prev = v; + for (0..32) |l| for (0..4) |j| { + const o = prev[l ^ m][j]; + v[l][j] = if (l & m != 0) o - prev[l][j] else prev[l][j] + o; + }; + } + for (0..32) |l| for (0..4) |j| { + out[4 * l + j] = @bitCast(@as(f16, @floatCast(v[l][j] * had))); + }; +} + +fn bf(x: u16) f32 { + return @bitCast(@as(u32, x) << 16); +} +/// __float2bfloat16_rn: round to nearest even, NaN kept quiet. +fn tobf(x: f32) u16 { + const u: u32 = @bitCast(x); + if (std.math.isNan(x)) return @intCast((u >> 16) | 0x40); + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +/// vision.cu: `x = tobf(__fadd_rn(bf(x), bf(tobf(__fmul_rn(bf(gamma), bf(y))))))`. +fn scaleAdd(x: u16, y: u16, gamma: u16) u16 { + return tobf(bf(x) + bf(tobf(bf(gamma) * bf(y)))); +} +/// vit.cu's pointwise_at with act none and G: `v = rbf(__fmul_rn(bf(G), v))`, then `bf16_rn(__fadd_rn(bf(R), v))`. +fn pointwiseGamma(x_in: u16, r: u16, gamma: u16, fused: bool) u16 { + const v0 = bf(x_in); + if (fused) return tobf(@mulAdd(f32, bf(gamma), v0, bf(r))); + const v = bf(tobf(bf(gamma) * v0)); + return tobf(bf(r) + v); +} + +fn special(rng: std.Random) f32 { + const edge = [_]f32{ 0, -0.0, std.math.inf(f32), -std.math.inf(f32), std.math.nan(f32), 1e-40, -1e-40, 3.4e38, 88.7, -88.7, 4, -4, 25, 1e-7 }; + return if (rng.uintLessThan(u32, 16) == 0) edge[rng.uintLessThan(usize, edge.len)] else (rng.float(f32) * 2 - 1) * std.math.pow(f32, 2, @floatFromInt(rng.intRangeAtMost(i32, -12, 12))); +} + +test "capped epilogue: main's tf_ink2_gateup and core's tf_exl3_gateup_capped write the same fp16 bits" { + var prng = std.Random.DefaultPrng.init(0x4127); + const rng = prng.random(); + var differ_fused: usize = 0; + for (0..512) |_| { + var gv: [128]f32 = undefined; + var uv: [128]f32 = undefined; + var sg: [128]f16 = undefined; + var su: [128]f16 = undefined; + var sd: [128]f16 = undefined; + for (&gv, &uv, &sg, &su, &sd) |*g, *u, *a, *b, *c| { + g.* = special(rng) * 64; + u.* = special(rng) * 64; + a.* = @floatCast(0.5 + rng.float(f32) * 2); + b.* = @floatCast(0.5 + rng.float(f32) * 2); + c.* = @floatCast(rng.float(f32) * 2 - 1); + } + var old: [128]u16 = undefined; + var new: [128]u16 = undefined; + var fused: [128]u16 = undefined; + block(.old, &gv, &uv, &sg, &su, &sd, &old); + block(.new, &gv, &uv, &sg, &su, &sd, &new); + block(.fused, &gv, &uv, &sg, &su, &sd, &fused); + try std.testing.expectEqualSlices(u16, &old, &new); + for (old, fused) |o, f| differ_fused += @intFromBool(o != f); + } + // the comparison sees one contracted product: without it the test would prove nothing + try std.testing.expect(differ_fused > 0); +} + +test "capped epilogue: each activation agrees at the caps, saturation and non-finite inputs" { + const xs = [_]f32{ 0, -0.0, 1, -1, 4, -4, 25, -25, 1e4, -1e4, 88.8, -88.8, 1e-40, std.math.inf(f32), -std.math.inf(f32), std.math.nan(f32) }; + for (xs) |g| for (xs) |u| { + const o: u32 = @bitCast(oldAct(g, u, gate_cap, up_cap)); + const n: u32 = @bitCast(newAct(g, u, gate_cap, up_cap)); + try std.testing.expectEqual(o, n); + }; +} + +test "layer scale: main's tf_ink2v_scale_add and core's tf_vit_pointwise_gamma write the same bf16 bits" { + var prng = std.Random.DefaultPrng.init(0x4127_2); + const rng = prng.random(); + var differ_fused: usize = 0; + for (0..1 << 16) |_| { + const x = tobf(special(rng)); + const y = tobf(special(rng)); + const gamma = tobf(special(rng)); + // in place, as vision.zig calls it: X is the block's output y, R and O are the residual x + try std.testing.expectEqual(scaleAdd(x, y, gamma), pointwiseGamma(y, x, gamma, false)); + differ_fused += @intFromBool(scaleAdd(x, y, gamma) != pointwiseGamma(y, x, gamma, true)); + } + try std.testing.expect(differ_fused > 0); +} From 055542a53093100674b3edbd84e5dd957a134532 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 06:24:41 +1100 Subject: [PATCH 20/27] inkling2: load standard exllamav3 packs with two-rank cuts Reads an EXL3 pack from exllamav3 1.x on the mul1 codebook: every attention projection and the head as EXL3 linears, each layer's experts as one grouped layer, cut to a rank by key heads, columns or rows. --- THIRD_PARTY_NOTICES.md | 7 + zig/src/families/inkling2/config.zig | 5 +- zig/src/families/inkling2/exl3.zig | 222 +++++++++++++++++++ zig/src/families/inkling2/inkling2.zig | 8 + zig/src/families/inkling2/pack_weights.zig | 234 +++++++++++++++++++++ zig/src/families/inkling2/shape.zig | 179 ++++++++++++++++ zig/src/families/inkling2/shard.zig | 67 ++++++ 7 files changed, 720 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/inkling2/exl3.zig create mode 100644 zig/src/families/inkling2/pack_weights.zig create mode 100644 zig/src/families/inkling2/shape.zig create mode 100644 zig/src/families/inkling2/shard.zig diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 4b75de86c17..a19f0251755 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -625,3 +625,10 @@ under the Tencent Hy License 1.0 (see [the license text](LICENSES/Tencent-Hy-1.0 `ace1100dcde7bf4eb06add6ae11ce4f43a11ddfe` (all but its last, ByteLevel), under the Apache License 2.0 stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)), and the pieces the Hugging Face tokenizers library splits with them and with a few other patterns. `tools/zig/onig_anchor_fixtures.py` rebuilds the file. + +## Inkling 2 EXL3 packs + +`zig/src/families/inkling2/exl3.zig` and `zig/src/families/inkling2/pack_weights.zig` read packs in the EXL3 format of +[turboderp-org/exllamav3](https://github.com/turboderp-org/exllamav3) 1.x (MIT): the trellis layout, the `mul1` codebook +and the per-tensor records. Packs carry the tensor names of an `inkling2` architecture added to exllamav3 for this +model. The loader and its two-rank cuts are TensorFold's own. diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index 07f3330fc2e..2404e94baef 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -376,17 +376,18 @@ fn parseMtp(o: std.json.ObjectMap, t: *const Text, why: *Why) !Mtp { return m; } -/// A quantization_config in config.json must be ModelOpt NVFP4, which the experts' header dtype refines per layer. +/// A quantization_config must be ModelOpt NVFP4 (the experts' header dtype refines it per layer) or EXL3. fn quantization(o: std.json.ObjectMap, why: *Why) !void { const v = o.get("quantization_config") orelse return; const q = if (v == .object) v.object else { why.set("quantization_config is not an object", .{}); return error.Quant; }; + if (std.mem.eql(u8, text(q, "quant_method") orelse "", "exl3")) return; // EXL3 tensors carry their own records 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)", .{}); + why.set("quantization_config: the loader reads ModelOpt NVFP4 experts or an EXL3 pack", .{}); return error.Quant; } } diff --git a/zig/src/families/inkling2/exl3.zig b/zig/src/families/inkling2/exl3.zig new file mode 100644 index 00000000000..5b4c805f7ed --- /dev/null +++ b/zig/src/families/inkling2/exl3.zig @@ -0,0 +1,222 @@ +//! Inkling 2's EXL3 tensors (exllamav3 1.x, mul1, an inkling2 architecture added to it): rank cuts, grouped experts. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const shard = @import("shard.zig"); +const experts_run = @import("experts.zig"); + +const Tensor = core.checkpoint.Tensor; + +/// The mul1 codebook marker's value. +const mul1_magic: u32 = 0x83DCD12D; + +/// What a rank takes of a projection: all of it, its output columns, or its input rows (each a multiple of 128). +pub const Cut = union(enum) { whole, cols: shard.Span, rows: shard.Span }; + +/// The device side of a load: uploads go through `put`, dense weights reserve their scratch on `dense`. +pub const Sink = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, bytes: []const u8) anyerror!u64, + dense: *cuda.exl3.Dense, + stream: cuda.Stream, +}; + +/// config.json's quantization_config: EXL3 from exllamav3 1.x on mul1 (each tensor's width is checked as it loads). +pub fn admit(gpa: std.mem.Allocator, config_json: []const u8) !void { + const doc = try std.json.parseFromSlice(std.json.Value, gpa, config_json, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.NotExl3; + const q = doc.value.object.get("quantization_config") orelse return error.NotExl3; + if (q != .object) return error.NotExl3; + const method = q.object.get("quant_method") orelse return error.NotExl3; + if (method != .string or !std.mem.eql(u8, method.string, "exl3")) return error.NotExl3; + const book = q.object.get("codebook") orelse return error.UnsupportedExl3; + if (book != .string or !std.mem.eql(u8, book.string, "mul1")) return error.UnsupportedExl3; + const version = q.object.get("version") orelse return error.UnsupportedExl3; + if (version != .string or !std.mem.startsWith(u8, version.string, "1.")) return error.UnsupportedExl3; +} + +/// One stored projection's tensors, checked: trellis [k/16][n/16][16 * bits] i16, the mul1 marker, fp16 suh and svh. +pub const Group = struct { + trellis: Tensor, + suh: Tensor, + svh: Tensor, + halves: u32, + + fn tile(g: Group) usize { + return g.halves * 16; + } +}; + +pub fn group(ck: *core.Checkpoint, base: []const u8, n: usize, k: usize) !Group { + var buf: [192]u8 = undefined; + const t = try ck.get(try std.fmt.bufPrint(&buf, "{s}.trellis", .{base})); + if (t.dtype != .i16 or t.rank != 3 or t.dim(0) != k / 16 or t.dim(1) != n / 16 or t.dim(2) % 8 != 0) { + std.log.err("inkling2: {s}.trellis is not [{d}, {d}, 16 * bits]", .{ base, k / 16, n / 16 }); + return error.UnexpectedInkling2Tensor; + } + const halves = t.dim(2) / 8; + if (halves < 2 or halves > 16) return error.UnsupportedExl3; + const marker = try ck.get(try std.fmt.bufPrint(&buf, "{s}.mul1", .{base})); + if (marker.dtype != .i32 or marker.bytes.len != 4 or std.mem.readInt(u32, marker.bytes[0..4], .little) != mul1_magic) return error.UnsupportedExl3; + const suh = try ck.get(try std.fmt.bufPrint(&buf, "{s}.suh", .{base})); + const svh = try ck.get(try std.fmt.bufPrint(&buf, "{s}.svh", .{base})); + if (!suh.is(.f16, &.{k}) or !svh.is(.f16, &.{n})) return error.UnexpectedInkling2Tensor; + return .{ .trellis = t, .suh = suh, .svh = svh, .halves = @intCast(halves) }; +} + +/// The cut's shape (k, n) and, appended to `out`, its trellis words, suh and svh in the stored layout. +pub fn cut(gpa: std.mem.Allocator, g: Group, n: usize, k: usize, c: Cut, out: *std.ArrayList(u8), suh: *std.ArrayList(u8), svh: *std.ArrayList(u8)) ![2]usize { + const tb = g.tile(); + const nt = n / 16; + const tr = g.trellis.bytes; + switch (c) { + .whole => { + try out.appendSlice(gpa, tr); + try suh.appendSlice(gpa, g.suh.bytes); + try svh.appendSlice(gpa, g.svh.bytes); + return .{ k, n }; + }, + .cols => |s| { + if (s.lo % 128 != 0 or s.len() % 128 != 0 or s.hi > n or s.len() == 0) return error.BadSplit; + for (0..k / 16) |kt| try out.appendSlice(gpa, tr[(kt * nt + s.lo / 16) * tb ..][0 .. s.len() / 16 * tb]); + try suh.appendSlice(gpa, g.suh.bytes); + try svh.appendSlice(gpa, g.svh.bytes[2 * s.lo .. 2 * s.hi]); + return .{ k, s.len() }; + }, + .rows => |s| { + if (s.lo % 128 != 0 or s.len() % 128 != 0 or s.hi > k or s.len() == 0) return error.BadSplit; + try out.appendSlice(gpa, tr[s.lo / 16 * nt * tb .. s.hi / 16 * nt * tb]); + try suh.appendSlice(gpa, g.suh.bytes[2 * s.lo .. 2 * s.hi]); + try svh.appendSlice(gpa, g.svh.bytes); + return .{ s.len(), n }; + }, + } +} + +/// The stored [n][k] projection under `base`, cut to the rank, on the device for cuda.exl3.Dense. +pub fn linear(gpa: std.mem.Allocator, ck: *core.Checkpoint, sink: Sink, base: []const u8, n: usize, k: usize, c: Cut) !cuda.exl3.Weight { + const g = try group(ck, base, n, k); + if (cuda.exl3.variantIndex(g.halves, .mul1, 4) == null) return error.UnsupportedExl3; + var tr: std.ArrayList(u8) = .empty; + defer tr.deinit(gpa); + var su: std.ArrayList(u8) = .empty; + defer su.deinit(gpa); + var sv: std.ArrayList(u8) = .empty; + defer sv.deinit(gpa); + const kn = try cut(gpa, g, n, k, c, &tr, &su, &sv); + const st = cuda.exl3.strides(kn[0], kn[1], g.halves, false); + const w: cuda.exl3.Weight = .{ + .trellis = try sink.put(sink.ctx, tr.items), + .suh = try sink.put(sink.ctx, su.items), + .svh = try sink.put(sink.ctx, sv.items), + .k = @intCast(kn[0]), + .n = @intCast(kn[1]), + .halves = g.halves, + .codebook = .mul1, + .stride_k = st.k, + .stride_nb = st.nb, + }; + try sink.dense.reserve(sink.stream, w); + return w; +} + +/// A layer's routed experts on the device and the least and most half-bit widths among their tensors. +pub const Experts = struct { layer: cuda.exl3_experts.Layer, bits: experts_run.Bits }; + +/// Layer `i`'s routed experts as one grouped EXL3 layer: gate and up by the rank's columns, down by its rows. +pub fn experts(gpa: std.mem.Allocator, ck: *core.Checkpoint, sink: Sink, prefix: []const u8, i: u32, count: usize, d: usize, inter: usize, span: shard.Span) !Experts { + const mods = [3][]const u8{ "gate_proj", "up_proj", "down_proj" }; + var ptrs: [3]u64 = undefined; + var k2: [3]u64 = undefined; + var suh: [3]u64 = undefined; + var svh: [3]u64 = undefined; + var base_buf: [160]u8 = undefined; + var bits: experts_run.Bits = .{ .lo = 16, .hi = 0 }; + for (mods, 0..) |mod, m| { + const down = m == 2; + const n = if (down) d else inter; + const k = if (down) inter else d; + var tr: std.ArrayList(u8) = .empty; + defer tr.deinit(gpa); + var su: std.ArrayList(u8) = .empty; + defer su.deinit(gpa); + var sv: std.ArrayList(u8) = .empty; + defer sv.deinit(gpa); + const at = try gpa.alloc(usize, count); + defer gpa.free(at); + const widths = try gpa.alloc(i32, count); + defer gpa.free(widths); + for (0..count) |e| { + const base = try std.fmt.bufPrint(&base_buf, "{s}layers.{d}.mlp.experts.{d}.{s}", .{ prefix, i, e, mod }); + const g = try group(ck, base, n, k); + at[e] = tr.items.len; + widths[e] = @intCast(g.halves); + bits = .{ .lo = @min(bits.lo, g.halves), .hi = @max(bits.hi, g.halves) }; + _ = try cut(gpa, g, n, k, if (down) .{ .rows = span } else .{ .cols = span }, &tr, &su, &sv); + } + const words = try sink.put(sink.ctx, tr.items); + const table = try gpa.alloc(u64, count); + defer gpa.free(table); + for (table, at) |*t, off| t.* = words + off; + ptrs[m] = try sink.put(sink.ctx, std.mem.sliceAsBytes(table)); + k2[m] = try sink.put(sink.ctx, std.mem.sliceAsBytes(widths)); + suh[m] = try sink.put(sink.ctx, su.items); + svh[m] = try sink.put(sink.ctx, sv.items); + ck.release(); + } + return .{ .bits = bits, .layer = .{ + .gate = ptrs[0], + .up = ptrs[1], + .down = ptrs[2], + .gate_k2 = k2[0], + .up_k2 = k2[1], + .down_k2 = k2[2], + .suh_g = suh[0], + .suh_u = suh[1], + .svh_g = svh[0], + .svh_u = svh[1], + .suh_d = suh[2], + .svh_d = svh[2], + .experts = count, + .dims = d, + .width = span.len(), + .codebook = .mul1, + } }; +} + +test "exl3: admit takes exllamav3 1.x on mul1 and refuses other codebooks, versions and formats" { + const a = std.testing.allocator; + try admit(a, "{\"quantization_config\":{\"quant_method\":\"exl3\",\"version\":\"1.6.6\",\"codebook\":\"mul1\"}}"); + try std.testing.expectError(error.UnsupportedExl3, admit(a, "{\"quantization_config\":{\"quant_method\":\"exl3\",\"version\":\"1.6.6\",\"codebook\":\"mcg\"}}")); + try std.testing.expectError(error.UnsupportedExl3, admit(a, "{\"quantization_config\":{\"quant_method\":\"exl3\",\"version\":\"0.9\",\"codebook\":\"mul1\"}}")); + try std.testing.expectError(error.NotExl3, admit(a, "{\"text_config\":{}}")); +} + +test "exl3: a cut takes a rank's tile columns of every k row, or its whole tile rows, with the matching scales" { + const a = std.testing.allocator; + var words: [16 * 16 * 32]u8 = undefined; + for (0..16) |kt| for (0..16) |nt| @memset(words[(kt * 16 + nt) * 32 ..][0..32], @intCast(kt * 16 + nt)); + var scales: [512]u8 = undefined; + for (&scales, 0..) |*s, j| s.* = @intCast(j / 2 % 256); + const t: Tensor = .{ .dtype = .i16, .rank = 3, .shape = .{ 16, 16, 16, 1, 1 }, .bytes = &words }; + const v: Tensor = .{ .dtype = .f16, .rank = 1, .shape = .{ 256, 1, 1, 1, 1 }, .bytes = &scales }; + const g: Group = .{ .trellis = t, .suh = v, .svh = v, .halves = 2 }; + var tr: std.ArrayList(u8) = .empty; + defer tr.deinit(a); + var su: std.ArrayList(u8) = .empty; + defer su.deinit(a); + var sv: std.ArrayList(u8) = .empty; + defer sv.deinit(a); + try std.testing.expectEqual([2]usize{ 256, 128 }, try cut(a, g, 256, 256, .{ .cols = .{ .lo = 128, .hi = 256 } }, &tr, &su, &sv)); + try std.testing.expectEqual(@as(u8, 8), tr.items[0]); + try std.testing.expectEqual(@as(u8, 16 + 8), tr.items[8 * 32]); + try std.testing.expectEqualSlices(u8, scales[256..], sv.items); + tr.clearRetainingCapacity(); + su.clearRetainingCapacity(); + sv.clearRetainingCapacity(); + try std.testing.expectEqual([2]usize{ 128, 256 }, try cut(a, g, 256, 256, .{ .rows = .{ .lo = 128, .hi = 256 } }, &tr, &su, &sv)); + try std.testing.expectEqual(@as(u8, 8 * 16), tr.items[0]); + try std.testing.expectEqualSlices(u8, scales[256..], su.items); + try std.testing.expectError(error.BadSplit, cut(a, g, 256, 256, .{ .cols = .{ .lo = 64, .hi = 192 } }, &tr, &su, &sv)); +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 3d437042dd0..c7086e916cf 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -2,8 +2,12 @@ pub const image = @import("image.zig"); pub const vision = @import("vision.zig"); +pub const shape = @import("shape.zig"); pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); +pub const shard = @import("shard.zig"); +pub const exl3 = @import("exl3.zig"); +pub const pack_weights = @import("pack_weights.zig"); pub const experts = @import("experts.zig"); pub const modelopt = @import("modelopt.zig"); pub const loop = @import("loop.zig"); @@ -17,8 +21,12 @@ pub const model_type = "inkling2"; test { _ = image; _ = vision; + _ = shape; _ = kernels; _ = ops; + _ = shard; + _ = exl3; + _ = pack_weights; _ = experts; _ = modelopt; _ = native; diff --git a/zig/src/families/inkling2/pack_weights.zig b/zig/src/families/inkling2/pack_weights.zig new file mode 100644 index 00000000000..2ef7e312f4d --- /dev/null +++ b/zig/src/families/inkling2/pack_weights.zig @@ -0,0 +1,234 @@ +//! One TP rank's Inkling 2 weights from an EXL3 pack: EXL3 projections and experts, the rest as stored. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const cfg = @import("shape.zig"); +const shard = @import("shard.zig"); +const exl3 = @import("exl3.zig"); +const experts = @import("experts.zig"); + +const Tensor = core.checkpoint.Tensor; +pub const Linear = cuda.exl3.Weight; + +/// The text decoder's tensors sit under this prefix; the vision tower and the drafter ship beside the pack. +pub const prefix = "model.llm."; + +/// q, r, gate by the rank's query heads, k, v by its key heads, o by its rows; the raw tensors cut the same way. +pub const Attention = struct { + q: Linear, + k: Linear, + v: Linear, + r: Linear, + gate: Linear, + o: Linear, + sink: u64, // bf16 [heads][hidden] + q_scale: u64, // bf16 [heads][128] + rel_scale: u64, // bf16 [heads][16] + rel_proj: u64, // bf16 [16][1024], whole + k_conv: u64, // sliding: bf16 [kv * 128][4]; global: static taps bf16 [4][kv * 128] + v_conv: u64, + k_proj: u64 = 0, // global: the dynamic taps' projection, bf16 [kv * 4][hidden] + v_proj: u64 = 0, +}; + +pub const Layer = struct { + kind: cfg.Kind, + norms: [3]u64, // attn_norm (sliding) or q/k/v input norms (global), bf16 [hidden] + attn_query: u64, // fp32 [nq][hidden]; 0 on layer 0 (no mix) + nq: u32, + mlp_query: u64, // fp32 [hidden] + mlp_norm: u64, + attn_conv: u64, // bf16 [hidden][4] + mlp_conv: u64, + attn: Attention, + router: u64, // bf16 [experts][hidden] + bias: u64, // fp32 [experts] + experts: cuda.exl3_experts.Layer, + bits: experts.Bits, // the experts' least and most half-bit widths +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + config: cfg.Config, + share: shard.Share, + padded_vocab: usize = 0, + embed: u64 = 0, // bf16 [vocab][hidden], whole on every rank + embed_norm: u64 = 0, + norm: u64 = 0, + out_query: u64 = 0, // fp32 [hidden] + head: Linear = undefined, // the rank's vocabulary rows of the 8-bit head + layers: []Layer = &.{}, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + bytes: u64 = 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 put(ctx: *anyopaque, bytes: []const u8) anyerror!u64 { + const w: *Weights = @ptrCast(@alignCast(ctx)); + const b = try cuda.DeviceBuffer.fromHost(w.d, bytes); + errdefer { + var owned = b; + owned.free(); + } + try w.buffers.append(w.gpa, b); + w.bytes += b.len; + return b.ptr; + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + w: *Weights, + ck: *core.Checkpoint, + sink: exl3.Sink, + buf: [192]u8 = undefined, + name: []const u8 = "", + + fn get(L: *Loader, comptime fmt: []const u8, args: anytype) !Tensor { + L.name = try std.fmt.bufPrint(&L.buf, prefix ++ fmt, args); + return L.ck.get(L.name); + } + + fn expect(L: *Loader, comptime fmt: []const u8, args: anytype, dtype: core.checkpoint.DType, dims: []const usize) !Tensor { + const t = try L.get(fmt, args); + if (!t.is(dtype, dims)) { + std.log.err("inkling2: {s} is not {s}{any}", .{ L.name, @tagName(dtype), dims }); + return error.UnexpectedInkling2Tensor; + } + return t; + } + + fn put(L: *Loader, bytes: []const u8) !u64 { + return L.sink.put(L.sink.ctx, bytes); + } + + /// Rows [lo, hi) of a stored row-major tensor whose rows are `row_bytes` long. + fn rows(L: *Loader, t: Tensor, lo: usize, hi: usize) !u64 { + const rb = t.bytes.len / t.dim(0); + return L.put(t.bytes[lo * rb .. hi * rb]); + } + + /// Columns [lo, hi) of every row of a stored 2-D bf16 tensor. + fn cols(L: *Loader, t: Tensor, lo: usize, hi: usize) !u64 { + const n = t.dim(1); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(L.gpa); + for (0..t.dim(0)) |r| try out.appendSlice(L.gpa, t.bytes[2 * (r * n + lo) .. 2 * (r * n + hi)]); + return L.put(out.items); + } + + fn lin(L: *Loader, i: u32, name: []const u8, n: usize, k: usize, c: exl3.Cut) !Linear { + var b: [128]u8 = undefined; + return exl3.linear(L.gpa, L.ck, L.sink, try std.fmt.bufPrint(&b, prefix ++ "layers.{d}.attn.{s}", .{ i, name }), n, k, c); + } + + fn attention(L: *Loader, i: u32) !Attention { + const c = &L.w.config; + const s = L.w.share; + const h: usize = c.hidden; + const D: usize = c.head_dim; + const H: usize = c.heads; + const KV: usize = c.kv_heads; + const q: shard.Span = .{ .lo = s.heads.lo * D, .hi = s.heads.hi * D }; + const kv: shard.Span = .{ .lo = s.kv.lo * D, .hi = s.kv.hi * D }; + const rel: shard.Span = .{ .lo = s.heads.lo * c.d_rel, .hi = s.heads.hi * c.d_rel }; + var a: Attention = .{ + .q = try L.lin(i, "wq_du", H * D, h, .{ .cols = q }), + .k = try L.lin(i, "wk_dv", KV * D, h, .{ .cols = kv }), + .v = try L.lin(i, "wv_dv", KV * D, h, .{ .cols = kv }), + .r = try L.lin(i, "wr_du", H * c.d_rel, h, if (s.whole()) .whole else .{ .cols = rel }), + .gate = try L.lin(i, "gate_attn", H * D, h, .{ .cols = q }), + .o = try L.lin(i, "wo_ud", h, H * D, .{ .rows = q }), + .sink = try L.rows(try L.expect("layers.{d}.attn.attn_sink_proj.weight", .{i}, .bf16, &.{ H, h }), s.heads.lo, s.heads.hi), + .q_scale = try L.rows(try L.expect("layers.{d}.attn.q_l2_clip.scale", .{i}, .bf16, &.{ H, D }), s.heads.lo, s.heads.hi), + .rel_scale = try L.rows(try L.expect("layers.{d}.attn.rel_l2_clip.scale", .{i}, .bf16, &.{ H, c.d_rel }), s.heads.lo, s.heads.hi), + .rel_proj = try L.rows(try L.expect("layers.{d}.attn.rel_logits_proj.proj", .{i}, .bf16, &.{ c.d_rel, c.rel_extent }), 0, c.d_rel), + .k_conv = 0, + .v_conv = 0, + }; + if (c.layer[i] == .sliding) { + a.k_conv = try L.rows(try L.expect("layers.{d}.attn.k_sconv.weight", .{i}, .bf16, &.{ KV * D, 1, c.conv }), kv.lo, kv.hi); + a.v_conv = try L.rows(try L.expect("layers.{d}.attn.v_sconv.weight", .{i}, .bf16, &.{ KV * D, 1, c.conv }), kv.lo, kv.hi); + } else { + a.k_conv = try L.cols(try L.expect("layers.{d}.attn.k_sconv.static_w", .{i}, .bf16, &.{ c.conv, KV * D }), kv.lo, kv.hi); + a.v_conv = try L.cols(try L.expect("layers.{d}.attn.v_sconv.static_w", .{i}, .bf16, &.{ c.conv, KV * D }), kv.lo, kv.hi); + const t0 = s.kv.lo * c.conv; + const t1 = s.kv.hi * c.conv; + a.k_proj = try L.rows(try L.expect("layers.{d}.attn.k_sconv.weight_proj", .{i}, .bf16, &.{ KV * c.conv, h }), t0, t1); + a.v_proj = try L.rows(try L.expect("layers.{d}.attn.v_sconv.weight_proj", .{i}, .bf16, &.{ KV * c.conv, h }), t0, t1); + } + return a; + } + + fn vector(L: *Loader, comptime fmt: []const u8, args: anytype, dtype: core.checkpoint.DType, n: usize) !u64 { + return L.put((try L.expect(fmt, args, dtype, &.{n})).bytes); + } + + fn layer(L: *Loader, i: u32) !Layer { + const c = &L.w.config; + const h: usize = c.hidden; + const global = c.layer[i] == .global; + var l: Layer = undefined; + l.kind = c.layer[i]; + l.norms = @splat(0); + if (global) { + for ([_][]const u8{ "q", "k", "v" }, 0..) |n, j| l.norms[j] = try L.vector("layers.{d}.{s}_input_norm.weight", .{ i, n }, .bf16, h); + } else l.norms[0] = try L.vector("layers.{d}.attn_norm.weight", .{i}, .bf16, h); + l.nq = if (global) 3 else 1; + l.attn_query = 0; + if (i > 0) { + const t = try L.get("attn_res.attn_queries.{d}", .{i - 1}); + if (t.dtype != .f32 or t.numel() != l.nq * h) return error.UnexpectedInkling2Tensor; + l.attn_query = try L.put(t.bytes); + } + l.mlp_query = try L.vector("attn_res.mlp_queries.{d}", .{i}, .f32, h); + l.mlp_norm = try L.vector("layers.{d}.mlp_norm.weight", .{i}, .bf16, h); + l.attn_conv = try L.put((try L.expect("layers.{d}.attn_sconv.weight", .{i}, .bf16, &.{ h, 1, c.conv })).bytes); + l.mlp_conv = try L.put((try L.expect("layers.{d}.mlp_sconv.weight", .{i}, .bf16, &.{ h, 1, c.conv })).bytes); + l.attn = try L.attention(i); + l.router = try L.put((try L.expect("layers.{d}.mlp.gate.weight", .{i}, .bf16, &.{ c.experts, h })).bytes); + l.bias = try L.vector("layers.{d}.mlp.gate.bias", .{i}, .f32, c.experts); + const ex = try exl3.experts(L.gpa, L.ck, L.sink, prefix, i, c.experts, h, c.intermediate, L.w.share.inter); + l.experts = ex.layer; + l.bits = ex.bits; + return l; + } +}; + +/// The rank's weights of `layers` (a prefix for a truncated pack), the embedding whole, its vocabulary's head rows. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dense: *cuda.exl3.Dense, stream: cuda.Stream, dir: []const u8, c: cfg.Config, rank: usize, world: usize) !Weights { + { + 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 << 22)); + defer gpa.free(bytes); + try exl3.admit(gpa, bytes); // exllamav3 1.x on mul1, before a tensor is read + } + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + const head_svh = try ck.get(prefix ++ "unembed.svh"); + const padded = head_svh.dim(0); + if (padded < c.vocab or padded % 128 != 0) return error.UnexpectedInkling2Tensor; + var w: Weights = .{ .gpa = gpa, .d = d, .config = c, .share = try shard.Share.of(&c, padded, rank, world), .padded_vocab = padded }; + errdefer w.deinit(); + var L: Loader = .{ .gpa = gpa, .w = &w, .ck = &ck, .sink = .{ .ctx = &w, .put = Weights.put, .dense = dense, .stream = stream } }; + w.layers = try gpa.alloc(Layer, c.layers); + for (w.layers, 0..) |*l, i| { + l.* = try L.layer(@intCast(i)); + ck.release(); // the pages read so far, before they crowd the device's allocations + } + w.embed = try L.put((try L.expect("embed.weight", .{}, .bf16, &.{ c.vocab, c.hidden })).bytes); + w.embed_norm = try L.vector("embed_norm.weight", .{}, .bf16, c.hidden); + w.norm = try L.vector("norm.weight", .{}, .bf16, c.hidden); + w.out_query = try L.vector("attn_res.output_query", .{}, .f32, c.hidden); + const v = w.share.vocab; + w.head = try exl3.linear(gpa, &ck, L.sink, prefix ++ "unembed", padded, c.hidden, if (w.share.whole()) .whole else .{ .cols = v }); + try stream.synchronize(); + return w; +} diff --git a/zig/src/families/inkling2/shape.zig b/zig/src/families/inkling2/shape.zig new file mode 100644 index 00000000000..ec90708b87f --- /dev/null +++ b/zig/src/families/inkling2/shape.zig @@ -0,0 +1,179 @@ +//! The engine's view of Inkling 2 Small: the shared config (config.zig) narrowed to what the CUDA kernels run. +const std = @import("std"); +const shared = @import("config.zig"); + +pub const max_layers = 64; + +/// A layer's attention: sliding (window, static short convolutions) or global (log scaling, dynamic convolutions). +pub const Kind = enum { sliding, global }; + +pub const Config = struct { + hidden: u32 = 4608, + layers: u32 = 48, + vocab: u32 = 201024, + /// Rows of the head that are real tokens; the rest of `vocab` is padding. + real_vocab: u32 = 200058, + eps: f32 = 1e-6, + heads: u32 = 48, + kv_heads: u32 = 8, + head_dim: u32 = 128, + /// Width of each head's relative-position vector and the distances its bias profile covers. + d_rel: u32 = 16, + rel_extent: u32 = 1024, + window: u32 = 1024, + qk_clip: f32 = 22.627416997969522, + rel_clip: f32 = 8.0, + log_floor: f32 = 128000, + log_alpha: f32 = 0.1, + conv: u32 = 4, + block_layers: u32 = 6, + experts: u32 = 384, + topk: u32 = 8, + intermediate: u32 = 2304, + gate_softcap: f32 = 4.0, + up_softcap: f32 = 25.0, + route_scale: f32 = 8.0, + logit_softcap: f32 = 30.0, + context: u32 = 1048576, + eos: [4]u32 = .{ 200006, 0, 0, 0 }, + eos_count: u32 = 1, + layer: [max_layers]Kind = undefined, + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + return parse(gpa, bytes); + } + + /// Query heads that share one key head. + pub fn group(c: *const Config) u32 { + return c.heads / c.kv_heads; + } + + pub fn globals(c: *const Config) u32 { + var n: u32 = 0; + for (c.layer[0..c.layers]) |k| n += @intFromBool(k == .global); + return n; + } + + /// Key and value bytes one token takes on a rank holding `kv` key heads: the global layers' bf16 keys and values. + pub fn tokenBytes(c: *const Config, kv: u32) u64 { + return @as(u64, c.globals()) * kv * c.head_dim * 2 * 2; + } + + /// The end-of-reply ids config.json names. + pub fn stops(c: *const Config) []const u32 { + return c.eos[0..c.eos_count]; + } +}; + +pub const Error = error{ BadInkling2Config, UnsupportedInkling2Attention, UnsupportedInkling2Experts }; + +/// config.json through the family's shared parser, then the kernels' limits; a refusal logs the parser's reason. +pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Config { + var why: shared.Why = .{}; + const s = shared.parse(gpa, bytes, &why) catch |err| { + std.log.err("inkling2: {s}", .{why.text()}); + return err; + }; + return from(&s); +} + +/// The shared config as the kernels read it; one attention shape serves sliding and global layers. +pub fn from(s: *const shared.Config) Error!Config { + const t = &s.text; + if (t.layers > max_layers) return error.BadInkling2Config; + if (!std.meta.eql(t.local, t.global)) return error.UnsupportedInkling2Attention; + var c: Config = .{ + .hidden = t.hidden, + .layers = t.layers, + .vocab = t.vocab, + .real_vocab = t.unpadded_vocab, + .eps = t.eps, + .heads = t.global.q, + .kv_heads = t.global.kv, + .head_dim = t.global.dim, + .d_rel = t.d_rel, + .rel_extent = t.rel_extent, + .window = t.window, + .qk_clip = t.qk_clip, + .rel_clip = t.rel_clip, + .log_floor = @floatFromInt(t.log_floor), + .log_alpha = t.log_alpha, + .conv = shared.conv_taps, + .block_layers = t.block, + .experts = t.experts, + .topk = t.topk, + .intermediate = t.expert_inter, + .gate_softcap = t.gate_cap, + .up_softcap = t.up_cap, + .route_scale = t.route_scale, + .logit_softcap = t.logit_cap, + .context = t.max_context, + .eos = .{ s.eos, 0, 0, 0 }, + .eos_count = 1, + }; + for (c.layer[0..c.layers], 0..) |*k, i| k.* = if (shared.isGlobal(@intCast(i))) .global else .sliding; + try validate(&c); + return c; +} + +/// What tf_ink2_* and the plan cover: 128-wide heads, a 16-wide rel vector over 1,024 distances, whole key groups. +pub fn validate(c: *const Config) Error!void { + if (c.head_dim != 128 or c.d_rel != 16 or c.rel_extent != 1024 or c.window != 1024 or c.kv_heads == 0 or + c.heads % c.kv_heads != 0 or c.kv_heads % 2 != 0 or c.qk_clip <= 0 or c.rel_clip <= 0 or c.log_floor < 1 or + c.conv != 4 or c.block_layers == 0) return error.UnsupportedInkling2Attention; + if (c.globals() == c.layers) return error.UnsupportedInkling2Attention; // truncated checks may hold no global layer + if (c.experts == 0 or c.experts % 8 != 0 or c.topk == 0 or c.topk > 8 or c.intermediate % 128 != 0 or + c.hidden % 128 != 0) return error.UnsupportedInkling2Experts; + if (c.real_vocab == 0 or c.real_vocab > c.vocab or c.context == 0) return error.BadInkling2Config; +} + +const fixture = @embedFile("fixtures/config.json"); + +test "inkling2 shape: the release's shape, 40 sliding and 8 global layers, eos from config.json" { + const c = try parse(std.testing.allocator, fixture); + try std.testing.expectEqual(@as(u32, 48), c.layers); + try std.testing.expectEqual(@as(u32, 8), c.globals()); + for ([_]usize{ 5, 11, 17, 23, 29, 35, 41, 47 }) |i| try std.testing.expectEqual(Kind.global, c.layer[i]); + try std.testing.expectEqual(Kind.sliding, c.layer[0]); + try std.testing.expectEqual(Kind.sliding, c.layer[46]); + try std.testing.expectEqual(@as(u32, 6), c.group()); + try std.testing.expectEqual(@as(u32, 1048576), c.context); + try std.testing.expectEqualSlices(u32, &.{200006}, c.stops()); + try std.testing.expectEqual(@as(f32, 128000), c.log_floor); + try std.testing.expectEqual(@as(f32, 22.627416997969522), c.qk_clip); + // at TP=2 a rank holds 4 key heads: 16 KiB a token, 16 GiB at 1M + try std.testing.expectEqual(@as(u64, 16384), c.tokenBytes(4)); +} + +test "inkling2 shape: an EXL3 pack's config reads as the release's" { + const modelopt = "\"quant_method\": \"modelopt\",\n \"quant_algo\": \"NVFP4\""; + const exl3 = "\"quant_method\": \"exl3\",\n \"version\": \"1.6.6\", \"bits\": 2.2"; + const bytes = try std.mem.replaceOwned(u8, std.testing.allocator, fixture, modelopt, exl3); + defer std.testing.allocator.free(bytes); + try std.testing.expect(!std.mem.eql(u8, bytes, fixture)); + const a = try parse(std.testing.allocator, fixture); + const b = try parse(std.testing.allocator, bytes); + try std.testing.expect(std.meta.eql(a, b)); +} + +test "inkling2 shape: shapes the kernels do not run are refused" { + const Case = struct { from: []const u8, to: []const u8, err: anyerror }; + const cases = [_]Case{ + .{ .from = "\"head_dim\": 128", .to = "\"head_dim\": 96", .err = error.UnsupportedInkling2Attention }, + .{ .from = "\"swa_head_dim\": 128", .to = "\"swa_head_dim\": 64", .err = error.UnsupportedInkling2Attention }, + .{ .from = "\"rel_extent\": 1024", .to = "\"rel_extent\": 2048", .err = error.UnsupportedInkling2Attention }, + .{ .from = "\"d_rel\": 16", .to = "\"d_rel\": 32", .err = error.UnsupportedInkling2Attention }, + .{ .from = "\"sliding_window_size\": 1024", .to = "\"sliding_window_size\": 4096", .err = error.UnsupportedInkling2Attention }, + .{ .from = "\"num_experts_per_tok\": 8", .to = "\"num_experts_per_tok\": 9", .err = error.UnsupportedInkling2Experts }, + }; + for (cases) |x| { + const bytes = try std.mem.replaceOwned(u8, std.testing.allocator, fixture, x.from, x.to); + defer std.testing.allocator.free(bytes); + try std.testing.expect(!std.mem.eql(u8, bytes, fixture)); + try std.testing.expectError(x.err, parse(std.testing.allocator, bytes)); + } +} diff --git a/zig/src/families/inkling2/shard.zig b/zig/src/families/inkling2/shard.zig new file mode 100644 index 00000000000..69b40664a4d --- /dev/null +++ b/zig/src/families/inkling2/shard.zig @@ -0,0 +1,67 @@ +//! A TP rank's share of Inkling 2: whole key heads (their query groups with them), 128-wide expert and vocab blocks. +const std = @import("std"); +const cfg = @import("shape.zig"); + +/// [lo, hi) of something a rank holds. +pub const Span = struct { + lo: usize, + hi: usize, + + pub fn len(s: Span) usize { + return s.hi - s.lo; + } + + /// Part `rank` of `world` of [0, n) in whole `unit`s, the earlier ranks taking any extra unit. + pub fn part(n: usize, unit: usize, rank: usize, world: usize) !Span { + if (n % unit != 0 or world == 0 or rank >= world) return error.BadSplit; + const units = n / unit; + if (units < world) return error.BadSplit; + const base = units / world; + const extra = units % world; + const lo = rank * base + @min(rank, extra); + return .{ .lo = lo * unit, .hi = (lo + base + @intFromBool(rank < extra)) * unit }; + } +}; + +pub const Share = struct { + rank: usize, + world: usize, + kv: Span, // key heads + heads: Span, // query heads: the key heads' groups + inter: Span, // expert intermediate columns + vocab: Span, // padded vocabulary rows of the head + + /// The rank's share; key heads must split evenly (each rank holds whole query groups and the same cache shape). + pub fn of(c: *const cfg.Config, padded_vocab: usize, rank: usize, world: usize) !Share { + if (c.kv_heads % world != 0) return error.BadSplit; + const kv = try Span.part(c.kv_heads, 1, rank, world); + const g = c.group(); + return .{ + .rank = rank, + .world = world, + .kv = kv, + .heads = .{ .lo = kv.lo * g, .hi = kv.hi * g }, + .inter = try Span.part(c.intermediate, 128, rank, world), + .vocab = try Span.part(padded_vocab, 128, rank, world), + }; + } + + pub fn whole(s: Share) bool { + return s.world == 1; + } +}; + +test "shard: two ranks take whole key heads with their query groups, 128-wide expert and vocab blocks" { + const c: cfg.Config = .{}; + const r0 = try Share.of(&c, 201088, 0, 2); + const r1 = try Share.of(&c, 201088, 1, 2); + try std.testing.expectEqual(Span{ .lo = 0, .hi = 4 }, r0.kv); + try std.testing.expectEqual(Span{ .lo = 24, .hi = 48 }, r1.heads); + try std.testing.expectEqual(Span{ .lo = 1152, .hi = 2304 }, r1.inter); + // 201,088 = 1,571 blocks of 128: rank 0 takes the odd one + try std.testing.expectEqual(Span{ .lo = 0, .hi = 786 * 128 }, r0.vocab); + try std.testing.expectEqual(@as(usize, 201088), r1.vocab.hi); + const one = try Share.of(&c, 201088, 0, 1); + try std.testing.expect(one.whole() and one.heads.len() == 48 and one.inter.len() == 2304); + try std.testing.expectError(error.BadSplit, Share.of(&c, 201088, 0, 3)); +} From 9a8a1daa420718772460ca46e86adc64a1f33067 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 06:40:02 +1100 Subject: [PATCH 21/27] inkling2: serve Small on two GB10s from an EXL3 pack Rank 0 serves and sends every step to rank 1 over NCCL; the per-layer partial sums cross by RoCE writes. Decode rows from several streams share one graphed forward, prompts run in 2,048-row chunks with kept states at chunk starts, and images go through the vision tower. No drafter yet: a stream decodes one row a step. --- THIRD_PARTY_NOTICES.md | 8 + docs/environment.md | 2 + zig/build/inkling2.zig | 9 +- zig/src/core/profile.zig | 2 +- zig/src/families/inkling2/admit.zig | 46 ++ zig/src/families/inkling2/admit_test.zig | 52 ++ zig/src/families/inkling2/chat.zig | 140 +++++ zig/src/families/inkling2/engine.zig | 346 ++++++++++++ zig/src/families/inkling2/engine_main.zig | 153 ++++++ zig/src/families/inkling2/follow.zig | 291 ++++++++++ zig/src/families/inkling2/forward.zig | 515 ++++++++++++++++++ zig/src/families/inkling2/inkling2.zig | 22 + zig/src/families/inkling2/kept.zig | 122 +++++ zig/src/families/inkling2/lanes.zig | 267 +++++++++ zig/src/families/inkling2/native.zig | 269 +++++++++ zig/src/families/inkling2/pictures.zig | 173 ++++++ zig/src/families/inkling2/prompt_dense.zig | 110 ++++ zig/src/families/inkling2/sampler.zig | 107 ++++ zig/src/families/inkling2/shape.zig | 2 + .../families/inkling2/tokenizer_fixture.json | 66 +++ zig/src/native/cuda_families.zig | 7 +- zig/src/platform/environment.zig | 4 +- zig/src/platform/environment_flags.zig | 2 + zig/src/platform/environment_test.zig | 4 +- 24 files changed, 2711 insertions(+), 8 deletions(-) create mode 100644 zig/src/families/inkling2/admit.zig create mode 100644 zig/src/families/inkling2/admit_test.zig create mode 100644 zig/src/families/inkling2/chat.zig create mode 100644 zig/src/families/inkling2/engine.zig create mode 100644 zig/src/families/inkling2/engine_main.zig create mode 100644 zig/src/families/inkling2/follow.zig create mode 100644 zig/src/families/inkling2/forward.zig create mode 100644 zig/src/families/inkling2/kept.zig create mode 100644 zig/src/families/inkling2/lanes.zig create mode 100644 zig/src/families/inkling2/native.zig create mode 100644 zig/src/families/inkling2/pictures.zig create mode 100644 zig/src/families/inkling2/prompt_dense.zig create mode 100644 zig/src/families/inkling2/sampler.zig create mode 100644 zig/src/families/inkling2/tokenizer_fixture.json diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index a19f0251755..d649a74d8e6 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -632,3 +632,11 @@ with them and with a few other patterns. `tools/zig/onig_anchor_fixtures.py` reb [turboderp-org/exllamav3](https://github.com/turboderp-org/exllamav3) 1.x (MIT): the trellis layout, the `mul1` codebook and the per-tensor records. Packs carry the tensor names of an `inkling2` architecture added to exllamav3 for this model. The loader and its two-rank cuts are TensorFold's own. + +## Inkling 2 serving + +`zig/src/families/inkling2/forward.zig`, `engine.zig` and the files they call run the decoder in the layer order of +Hugging Face transformers' `src/transformers/models/inkling2/modeling_inkling2.py` at commit `109a7d19bf66` +([huggingface/transformers](https://github.com/huggingface/transformers), Apache-2.0): `Inkling2SlidingDecoderLayer`, +`Inkling2FullDecoderLayer` and `Inkling2TextModel`. The two-rank engine, the lanes and the prompt path are TensorFold's +own. diff --git a/docs/environment.md b/docs/environment.md index a8b264f77d3..7d80b99da6d 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -98,6 +98,8 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_NEMOTRON_RANK` | Nemotron 3.5 Super on CUDA: a whole rank index from 0 through 4294967295, set with `TF_NEMOTRON_WORLD`; unset with it gives one rank | | `TF_NEMOTRON_WORLD` | Nemotron 3.5 Super on CUDA: a whole rank count from 1 through 4294967295, set with `TF_NEMOTRON_RANK`; unset with it gives one rank | | `TF_NEMOTRON_WIDE_ROUNDS` | Exactly `0` or `1`, checked when the CUDA backend starts; default off. `1` lets Nemotron's shared rounds hold 16 streams and 32 rows on GB10 (one rank, non-latent, not Bolt, no `--precision checkpoint`, no bf16 experts, no Sliding Weights or saved lessons; refused with a log line naming why), each row's bits as in two 16-row rounds; a lone stream's window is unchanged | +| `TF_INKLING2_RANK` | Inkling 2 on CUDA: a whole rank index, 0 or 1 at two ranks, set with `TF_INKLING2_WORLD`; unset with it gives one rank | +| `TF_INKLING2_WORLD` | Inkling 2 on CUDA: a whole rank count, 2 on CUDA, set with `TF_INKLING2_RANK`; unset with it gives one rank | | `TF_MINIMAX_RANK` | MiniMax-M3.1-Flash on CUDA: a whole rank index, 0 or 1 at two ranks, set with `TF_MINIMAX_WORLD`; unset with it gives one rank | | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_MINIMAX_GRAPHS` | MiniMax-M3.1-Flash on CUDA: exactly `0` or `1`, the same on every rank; default off. `1` records each one-stream decode verify window's launches as a CUDA graph and updates the held graph with that round's arguments before launching it (one graph per row count, sparse or dense attention, and taps); the same kernels with the same arguments in the same order, so tokens keep their bits. A refused capture or refresh on any rank sends every rank back to eager launches | diff --git a/zig/build/inkling2.zig b/zig/build/inkling2.zig index ad9d1ba52f7..0a084941084 100644 --- a/zig/build/inkling2.zig +++ b/zig/build/inkling2.zig @@ -10,10 +10,15 @@ pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui return m; } -/// The family in tf-cuda-test's `runner`, where the kernel contract reaches its launchers. +/// The family in tf-cuda-test's `runner`; tf-inkling2-engine (the engine's graph and greedy checks). pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, strip: bool, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, runner: *std.Build.Module) void { - _ = strip; runner.addImport("inkling2", module(b, target, optimize, cuda, core, lanes)); + const m = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/engine_main.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip }); + m.addImport("cuda", cuda); + m.addImport("inkling2", module(b, target, optimize, cuda, core, lanes)); + const exe = b.addExecutable(.{ .name = "tf-inkling2-engine", .root_module = m }); + b.installArtifact(exe); + b.step("tf-inkling2-engine", "Inkling 2's engine checks: graph replay against eager rows, greedy decode").dependOn(&b.addInstallArtifact(exe, .{}).step); } /// The family's host regressions (config, chat wiring, reply split, admission, the attention plan) in `all`. diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index eb857acd4bb..293cf1f11ca 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -146,7 +146,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", "nemo_speechlm", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark", "ricursive", "inkling2_loop", "lfm3" }; +pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "nemo_speechlm", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark", "ricursive", "inkling2_loop", "lfm3", "inkling2" }; pub const entries = [_]Entry{ .{ .id = .TF_CUDA_POOL_AFTER_WARMUP, .families = &.{"qwen3_5"}, .class = .experimental, .syntax = .one, .report_values = &.{"1"}, .effect = "Size an idle device KV pool after Qwen DFlash2 warm-up", .evidence = "Default off; host sizing checks; device capacity and token checks required" }, diff --git a/zig/src/families/inkling2/admit.zig b/zig/src/families/inkling2/admit.zig new file mode 100644 index 00000000000..b3408aa9409 --- /dev/null +++ b/zig/src/families/inkling2/admit.zig @@ -0,0 +1,46 @@ +//! Inkling 2 on CUDA is admitted only as it was run: on GB10 (sm_121) at two ranks, placed by TF_INKLING2_RANK/WORLD. +const std = @import("std"); +const cuda = @import("cuda"); +const environment = @import("sys").environment; + +pub const Refusal = error{ Inkling2RequiresSm121, Inkling2RequiresTwoRanks }; + +pub fn admit(sm: u32, world: usize) Refusal!void { + if (sm != 121) return error.Inkling2RequiresSm121; + if (world != 2) return error.Inkling2RequiresTwoRanks; +} + +/// The first check of the family's open: the device's capability, then the rank count, before any image loads. +pub fn check(ctx: *const cuda.Context, world: usize) (Refusal || cuda.Error)!void { + try admit(try ctx.capability(), world); +} + +pub fn explain(err: anyerror) ?[]const u8 { + return switch (err) { + error.Inkling2RequiresSm121 => "Inkling 2 on CUDA is validated on GB10 (sm_121) only", + error.Inkling2RequiresTwoRanks => "Inkling 2 on CUDA runs on exactly two ranks: set TF_INKLING2_RANK (0 or 1) and TF_INKLING2_WORLD=2", + error.Inkling2NoRank => "TF_INKLING2_RANK and TF_INKLING2_WORLD go together, with the rank below the world", + else => null, + }; +} + +/// This rank's place: TF_INKLING2_RANK of TF_INKLING2_WORLD (both, or neither for one rank). +pub const Place = struct { rank: usize, world: usize }; + +pub fn placeFrom(rank: ?[]const u8, world: ?[]const u8) !Place { + return placeOf(try environment.value(?u32, "TF_INKLING2_RANK", rank, null), try environment.value(?u32, "TF_INKLING2_WORLD", world, null)); +} + +pub fn place() !Place { + return placeOf(try environment.read(?u32, "TF_INKLING2_RANK", null), try environment.read(?u32, "TF_INKLING2_WORLD", null)); +} + +fn placeOf(r: ?u32, w: ?u32) error{Inkling2NoRank}!Place { + if (r == null and w == null) return .{ .rank = 0, .world = 1 }; + if (r == null or w == null or w.? == 0 or r.? >= w.?) return error.Inkling2NoRank; + return .{ .rank = r.?, .world = w.? }; +} + +test { + _ = @import("admit_test.zig"); +} diff --git a/zig/src/families/inkling2/admit_test.zig b/zig/src/families/inkling2/admit_test.zig new file mode 100644 index 00000000000..96c8a27cbc0 --- /dev/null +++ b/zig/src/families/inkling2/admit_test.zig @@ -0,0 +1,52 @@ +//! Inkling 2's admission on a fake driver: only sm_121 at two ranks passes, refused before any image loads. +const std = @import("std"); +const cuda = @import("cuda"); +const admit = @import("admit.zig"); +const t = std.testing; + +const Fake = struct { + var sm: u32 = 121; + var reads: usize = 0; + var loads: usize = 0; + fn attribute(out: *c_int, key: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + reads += 1; + out.* = switch (key) { + .compute_capability_major => @intCast(sm / 10), + .compute_capability_minor => @intCast(sm % 10), + else => unreachable, + }; + return cuda.abi.success; + } + fn load(_: *cuda.abi.Module, _: ?*const anyopaque) callconv(.c) cuda.abi.Result { + loads += 1; + return cuda.abi.error_not_ready; + } +}; + +test "inkling2 admission: GB10 at two ranks only, read from the device before any module load" { + var driver: cuda.Driver = undefined; + driver.api.cuDeviceGetAttribute = Fake.attribute; + driver.api.cuModuleLoadData = Fake.load; + const ctx: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; + Fake.sm = 121; + try admit.check(&ctx, 2); + for ([_]usize{ 1, 3, 4 }) |w| try t.expectError(error.Inkling2RequiresTwoRanks, admit.check(&ctx, w)); + for ([_]u32{ 80, 90, 100, 120, 122 }) |sm| { + Fake.sm = sm; + try t.expectError(error.Inkling2RequiresSm121, admit.check(&ctx, 2)); + } + try t.expect(Fake.reads > 0); + try t.expectEqual(@as(usize, 0), Fake.loads); + try t.expect(admit.explain(error.Inkling2RequiresSm121) != null); + try t.expect(admit.explain(error.Inkling2RequiresTwoRanks) != null); +} + +test "inkling2 admission: the rank settings come in pairs and are read through the environment table" { + try t.expectEqual(admit.Place{ .rank = 0, .world = 1 }, try admit.placeFrom(null, null)); + try t.expectEqual(admit.Place{ .rank = 1, .world = 2 }, try admit.placeFrom("1", "2")); + try t.expectError(error.Inkling2NoRank, admit.placeFrom("1", null)); + try t.expectError(error.Inkling2NoRank, admit.placeFrom("2", "2")); + try t.expectError(error.InvalidEnvironment, admit.placeFrom("one", "2")); + // one rank parses as a place; admission is what refuses it + try t.expectError(error.Inkling2RequiresTwoRanks, admit.admit(121, (try admit.placeFrom(null, null)).world)); +} diff --git a/zig/src/families/inkling2/chat.zig b/zig/src/families/inkling2/chat.zig new file mode 100644 index 00000000000..7e033d6116f --- /dev/null +++ b/zig/src/families/inkling2/chat.zig @@ -0,0 +1,140 @@ +//! Inkling 2's chat wiring: the block markers' ids from tokenizer_config.json, the stop ids and the template's checks. +const std = @import("std"); +const cfg = @import("shape.zig"); +/// The release's block markers (special tokens in tokenizer_config.json) the server's reply split reads. +pub const markers = struct { + pub const model = "<|message_model|>"; + pub const text = "<|content_text|>"; + pub const thinking = "<|content_thinking|>"; + pub const end = "<|end_message|>"; + pub const end_sampling = "<|content_model_end_sampling|>"; + pub const tool_json = "<|content_invoke_tool_json|>"; + pub const tool_text = "<|content_invoke_tool_text|>"; + pub const tool_error = "<|content_tool_error|>"; +}; + +/// The special tokens the template writes and the reply split reads, by id. +pub const Tokens = struct { + endoftext: u32 = 0, + user: u32 = 0, + model: u32 = 0, + system: u32 = 0, + tool: u32 = 0, + text: u32 = 0, + image_block: u32 = 0, + end_sampling: u32 = 0, + thinking: u32 = 0, + end: u32 = 0, + tool_error: u32 = 0, + xml: u32 = 0, + tool_json: u32 = 0, + tool_text: u32 = 0, + /// The image placeholder the processor expands into the tower's rows. + image: u32 = 0, +}; + +const names = [_]struct { field: []const u8, text: []const u8 }{ + .{ .field = "endoftext", .text = "<|endoftext|>" }, + .{ .field = "user", .text = "<|message_user|>" }, + .{ .field = "model", .text = markers.model }, + .{ .field = "system", .text = "<|message_system|>" }, + .{ .field = "tool", .text = "<|message_tool|>" }, + .{ .field = "text", .text = markers.text }, + .{ .field = "image_block", .text = "<|content_image|>" }, + .{ .field = "end_sampling", .text = markers.end_sampling }, + .{ .field = "thinking", .text = markers.thinking }, + .{ .field = "end", .text = markers.end }, + .{ .field = "tool_error", .text = markers.tool_error }, + .{ .field = "xml", .text = "<|content_xml|>" }, + .{ .field = "tool_json", .text = markers.tool_json }, + .{ .field = "tool_text", .text = markers.tool_text }, + .{ .field = "image", .text = "<|unused_200054|>" }, +}; + +pub const Error = error{ BadInkling2Tokenizer, Inkling2TokenMissing, Inkling2StopMismatch, Inkling2TemplateMismatch }; + +pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Tokens { + const path = try std.fs.path.join(gpa, &.{ dir, "tokenizer_config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 24)); + defer gpa.free(bytes); + return parse(gpa, bytes); +} + +/// Every marker must be a special added token; its id is the decoder key that spells it. +pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Tokens { + var doc = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.BadInkling2Tokenizer; + const dec = doc.value.object.get("added_tokens_decoder") orelse return error.BadInkling2Tokenizer; + if (dec != .object) return error.BadInkling2Tokenizer; + var out: Tokens = .{}; + inline for (names) |n| { + var found = false; + var it = dec.object.iterator(); + while (it.next()) |e| { + if (e.value_ptr.* != .object) continue; + const content = e.value_ptr.object.get("content") orelse continue; + if (content != .string or !std.mem.eql(u8, content.string, n.text)) continue; + const special = e.value_ptr.object.get("special") orelse return error.BadInkling2Tokenizer; + if (special != .bool or !special.bool) return error.BadInkling2Tokenizer; + @field(out, n.field) = std.fmt.parseInt(u32, e.key_ptr.*, 10) catch return error.BadInkling2Tokenizer; + found = true; + } + if (!found) return error.Inkling2TokenMissing; + } + return out; +} + +/// The ids a reply stops at: config.json's eos, which must be the template's end of a model turn. +pub fn stops(c: *const cfg.Config, tok: *const Tokens) Error![]const u32 { + const s = c.stops(); + for (s) |id| if (id == tok.end_sampling) return s; + return error.Inkling2StopMismatch; +} + +/// The template must write the blocks the server splits and take the effort switch; any other format is refused. +pub fn checkTemplate(template: []const u8) Error!void { + const needed = [_][]const u8{ markers.model, markers.thinking, markers.text, markers.end, markers.tool_json, markers.end_sampling, "reasoning_effort", "tool_declare" }; + for (needed) |n| if (std.mem.indexOf(u8, template, n) == null) return error.Inkling2TemplateMismatch; +} + +pub fn readTemplate(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !void { + const path = try std.fs.path.join(gpa, &.{ dir, "chat_template.jinja" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(bytes); + try checkTemplate(bytes); +} + +const t = std.testing; +const fixture = @embedFile("tokenizer_fixture.json"); + +test "inkling2 chat: the markers' ids, the image token and the stop id from the release's files" { + const tok = try parse(t.allocator, fixture); + try t.expectEqual(@as(u32, 200001), tok.model); + try t.expectEqual(@as(u32, 200006), tok.end_sampling); + try t.expectEqual(@as(u32, 200008), tok.thinking); + try t.expectEqual(@as(u32, 200010), tok.end); + try t.expectEqual(@as(u32, 200049), tok.tool_json); + try t.expectEqual(@as(u32, 200054), tok.image); + const c = try cfg.parse(t.allocator, @embedFile("fixtures/config.json")); + try t.expectEqualSlices(u32, &.{200006}, try stops(&c, &tok)); + var other = c; + other.eos[0] = tok.end; + try t.expectError(error.Inkling2StopMismatch, stops(&other, &tok)); +} + +test "inkling2 chat: a missing or non-special marker is refused" { + const gone = try std.mem.replaceOwned(u8, t.allocator, fixture, "<|content_thinking|>", "<|content_think|>"); + defer t.allocator.free(gone); + try t.expectError(error.Inkling2TokenMissing, parse(t.allocator, gone)); + const plain = try std.mem.replaceOwned(u8, t.allocator, fixture, "\"special\": true", "\"special\": false"); + defer t.allocator.free(plain); + try t.expectError(error.BadInkling2Tokenizer, parse(t.allocator, plain)); +} + +test "inkling2 chat: the template check takes the release's blocks and refuses another format" { + try checkTemplate(@embedFile("fixtures/chat_template.jinja")); + try t.expectError(error.Inkling2TemplateMismatch, checkTemplate("{{ '' }} reasoning_effort")); +} diff --git a/zig/src/families/inkling2/engine.zig b/zig/src/families/inkling2/engine.zig new file mode 100644 index 00000000000..2f253cf6da8 --- /dev/null +++ b/zig/src/families/inkling2/engine.zig @@ -0,0 +1,346 @@ +//! One TP rank's Inkling 2 engine: streams by slot, prompt chunks, decode rows (shared, graphed) and their draws. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("shape.zig"); +const shard = @import("shard.zig"); +const weights = @import("pack_weights.zig"); +const fw = @import("forward.zig"); +const ops = @import("ops.zig"); +const sampler = @import("sampler.zig"); +const kept = @import("kept.zig"); +const vision = @import("vision.zig"); +const image = @import("image.zig"); +const pictures = @import("pictures.zig"); + +/// Rows a prompt chunk holds (the prompt cache's mark grid) and a stream's window at most (one row: no drafts). +pub const prompt_rows = 2048; +pub const window_rows = 1; +/// A shared decode forward's streams and rows at most. +pub const max_shared = 16; +pub const shared_rows = max_shared * window_rows; +/// Partial slots a prompt call writes at most: 2,048 rows over 8 global chunks (deeper calls take fewer rows). +const prompt_parts = 8; + +/// Rank 0's own word on its request (cancelled or not); the other ranks have none and hear rank 0's. +pub const Cancel = struct { ptr: ?*anyopaque, check: *const fn (?*anyopaque) bool }; + +/// One stream's window in a shared forward: its slot, its ids (the pending token), its draws. +pub const Part = struct { slot: u32, ids: []const u32, out: []u32 }; + +/// A slot's request state: its sampling (null: greedy). +const Seq = struct { sampling: ?sampler.Sampling = null }; + +pub const Options = struct { capacity: usize, vision: ?pictures.Limits = null }; + +/// A graph's key: a decode call's rows, streams, attention tiles and partial stride (its global chunks). +const Key = struct { n: u32, ni: u32, nt: u32, stride: u32 }; + +pub const Engine = struct { + gpa: std.mem.Allocator, + io: std.Io, + d: *const cuda.Driver, + c: cfg.Config, + m: fw.Modules, + stream: cuda.Stream, + w: weights.Weights, + shape_p: fw.Shape, + shape_d: fw.Shape, + bp: fw.Buffers, + bd: fw.Buffers, + parts: std.ArrayList(cuda.DeviceBuffer) = .empty, // the partials bp and bd share (one stream runs both in order) + st: ?fw.State = null, // every slot's caches, made by reserve + seqs: []Seq = &.{}, + slot: u32 = 0, + capacity: usize, + exchange: fw.Exchange = .local, + picks: cuda.DeviceBuffer, // every rank's (value, id) of each row's greedy pick: fp32 then i32, [world][rows] + picks_host: []u8, + smp: sampler.Sampler, + spans: []shard.Span, // every rank's vocabulary span + graphs: cuda.graph_cache.Cache(Key), + gengine: cuda.graph_cache.CudaEngine, + states: kept.Store, + checkpoint_digest: [32]u8 = @splat(0), + vision: ?pictures.Limits = null, // images on (--vision): every rank's rows a slot, rank 0's tower + tower: ?*vision.Tower = null, + rows: []pictures.Rows = &.{}, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, rank: usize, world: usize, o: Options) !*Engine { + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + const c = try cfg.Config.read(gpa, io, dir); + var stream = try cuda.Stream.init(d, false); + errdefer stream.deinit(); + var m = try fw.Modules.load(d); + errdefer m.deinit(); + e.* = .{ .gpa = gpa, .io = io, .d = d, .c = c, .m = m, .stream = stream, .w = undefined, .shape_p = undefined, .shape_d = undefined, .bp = undefined, .bd = undefined, .capacity = o.capacity, .picks = undefined, .picks_host = &.{}, .smp = undefined, .spans = &.{}, .graphs = undefined, .gengine = .{ .d = d }, .states = .{ .gpa = gpa } }; + e.w = try weights.load(gpa, io, d, &e.m.dense, stream, dir, c, rank, world); + errdefer e.w.deinit(); + const heads = e.w.share.heads.len(); + const kv = e.w.share.kv.len(); + e.shape_p = .{ .rows = prompt_rows, .context = o.capacity, .heads = heads, .kv = kv }; + e.shape_d = .{ .rows = shared_rows, .context = o.capacity, .heads = heads, .kv = kv, .ring_rows = prompt_rows }; + errdefer for (e.parts.items) |*b| b.free(); + const slots = @max(prompt_rows * heads * prompt_parts, shared_rows * heads * fw.stride(&e.c, o.capacity - 1)); + const shared = try fw.partialsFor(d, &e.parts, gpa, slots); + e.bp = try fw.Buffers.init(gpa, d, &e.w, e.shape_p, shared); + errdefer e.bp.deinit(); + e.bd = try fw.Buffers.init(gpa, d, &e.w, e.shape_d, shared); + errdefer e.bd.deinit(); + for (e.w.layers) |l| for ([_]cuda.exl3.Weight{ l.attn.q, l.attn.k, l.attn.v, l.attn.r, l.attn.gate, l.attn.o }) |x| try e.m.dense.reserve(stream, x); + try e.m.dense.reserve(stream, e.w.head); // scratch grown now, so nothing allocates inside a graph capture + e.m.prompt = @import("prompt_dense.zig").Prompt.of(gpa, d, e.m.ops.prompt_tail, prompt_rows, e.w.layers) catch |err| blk: { // without cuBLASLt, prompt rows keep the decode kernels + std.log.warn("inkling2: prompt projections on the decode kernels ({s})", .{@errorName(err)}); + break :blk null; + }; + for (e.w.layers) |l| for ([_]cuda.exl3.Weight{ l.attn.k, l.attn.v, l.attn.r }) |x| try e.m.side.dense.reserve(stream, x); + e.vision = o.vision; + if (o.vision != null and rank == 0) e.tower = try vision.Tower.load(gpa, io, d, dir, c.vision, pictures.picture_tokens); + errdefer if (e.tower) |t| t.deinit(); + e.picks = try cuda.DeviceBuffer.alloc(d, world * pickStride(shared_rows)); + errdefer e.picks.free(); + e.picks_host = try gpa.alloc(u8, world * pickStride(shared_rows)); + errdefer gpa.free(e.picks_host); + e.smp = try sampler.Sampler.init(d, e.w.padded_vocab, shared_rows); + errdefer e.smp.deinit(); + e.spans = try gpa.alloc(shard.Span, world); + for (e.spans, 0..) |*sp, q| sp.* = (try shard.Share.of(&e.c, e.w.padded_vocab, q, world)).vocab; + e.graphs = .init(gpa, e.gengine.engine(), .{}); + e.graphs.name = "inkling2 decode"; + try e.stream.synchronize(); + return e; + } + + pub fn deinit(e: *Engine) void { + e.stream.synchronize() catch {}; + e.graphs.deinit(); + e.states.deinit(); + if (e.tower) |t| t.deinit(); + pictures.freeRows(e.gpa, e.rows); + if (e.st) |*s| s.deinit(); + e.gpa.free(e.seqs); + e.gpa.free(e.spans); + e.smp.deinit(); + e.gpa.free(e.picks_host); + e.picks.free(); + e.bd.deinit(); + e.bp.deinit(); + for (e.parts.items) |*b| b.free(); + e.parts.deinit(e.gpa); + e.w.deinit(); + e.m.deinit(); + e.stream.deinit(); + const gpa = e.gpa; + gpa.destroy(e); + } + + /// Bytes one more stream takes on this rank: its slot's rings and conv states, its image rows. + pub fn seqBytes(e: *const Engine) u64 { + const rows: u64 = if (e.vision) |l| pictures.slotBytes(l, e.c.hidden) else 0; + return fw.slotBytes(&e.c, e.shape_d) + rows; + } + + /// The largest all-gather a rank sends (a prompt call's fp32 partial): RoCE writes take every gather up to it. + pub fn roceBytes(e: *const Engine) usize { + return prompt_rows * @as(usize, e.c.hidden) * 4; + } + + fn convBytes(e: *const Engine) usize { + return @as(usize, e.c.layers) * 2 * 3 * (e.shape_d.kv * e.c.head_dim + e.c.hidden) * 4; + } + + /// Every slot's caches for `slots` streams, made once (the host's admission decides how many). + pub fn reserve(e: *Engine, slots: usize) !void { + if (e.st != null) return if (e.seqs.len == slots) {} else error.Inkling2Reserved; + e.st = try fw.State.init(e.gpa, e.d, &e.c, e.shape_d, slots); + errdefer { + e.st.?.deinit(); + e.st = null; + } + if (e.vision) |l| e.rows = try pictures.makeRows(e.gpa, e.d, l, slots, e.c.hidden); + e.seqs = try e.gpa.alloc(Seq, slots); + @memset(e.seqs, .{}); + } + + pub fn slotCount(e: *const Engine) usize { + return e.seqs.len; + } + + pub fn bind(e: *Engine, slot: u32) !void { + if (slot >= e.seqs.len) return error.Inkling2NoSlot; + e.slot = slot; + } + + /// The bound slot's committed length: the pending token sits there, a window's row r draws position pos + 1 + r. + pub fn pos(e: *const Engine) usize { + return e.st.?.pos[e.slot]; + } + + /// A new request on the bound slot with `sampling` (null or temperature 0: greedy). + pub fn begin(e: *Engine, s: ?sampler.Sampling) void { + e.seqs[e.slot] = .{ .sampling = sampler.check(s) }; + if (e.rows.len > 0) e.rows[e.slot].spans.clearRetainingCapacity(); // a new request splices nothing until told + } + + /// The bound slot's pictures for its next prompt pass: rank 0 encodes them (`pics`), every rank gets the rows. + pub fn images(e: *Engine, pics: ?[]const image.Prepared, spans: []const vision.Span) !void { + const l = e.vision orelse return error.NoVision; + if (e.rows.len == 0) return error.Inkling2Reserved; + const total = try pictures.checkSpans(spans, l); + const r = &e.rows[e.slot]; + r.spans.clearRetainingCapacity(); + if (e.tower) |t| { + const ps = pics orelse return error.ImagePlaceholders; + if (ps.len != spans.len) return error.ImagePlaceholders; + for (ps, spans) |p, sp| try t.encode(e.stream, p, r.buf.ptr + @as(u64, sp.row) * e.c.hidden * 2); + } else if (e.exchange == .local) return error.NoVision; + switch (e.exchange) { + .local => {}, + .nccl => |x| try x.lib.check(x.lib.api.ncclBroadcast(r.buf.ptr, r.buf.ptr, @as(usize, total) * e.c.hidden * 2, .u8, 0, x.comm, e.stream.handle), "ncclBroadcast"), + } + try r.spans.appendSlice(e.gpa, spans); + } + + fn forward(e: *Engine, b: *fw.Buffers, shape: fw.Shape) fw.Forward { + return .{ .d = e.d, .m = &e.m, .w = &e.w, .b = b, .shape = shape, .stream = e.stream, .exchange = e.exchange }; + } + + /// One chunk of the bound slot's prompt from `start` (0: a fresh pass); the first token once it ends the prompt. + pub fn prefillChunk(e: *Engine, ids: []const u32, start: usize) !?u32 { + const st = &e.st.?; + if (ids.len == 0 or ids.len + window_rows >= e.capacity) return error.PromptTooLong; + if (start >= ids.len or start % prompt_rows != 0) return error.BadChunk; + if (start == 0) try st.clearSlot(&e.c, e.d, e.slot, e.stream) else if (start != st.pos[e.slot]) return error.BadChunk; + e.states.overwrite(e.slot, start); // states on this slot past `start` lose their rows to this pass + const end = @min(ids.len, start + prompt_rows); + var f = e.forward(&e.bp, e.shape_p); + f.last_logits = true; + // a deep call writes partials for every global chunk: fewer rows a call, the same bits a row + const most = @max(1, e.bp.parts.slots / (e.shape_p.heads * fw.stride(&e.c, end - 1))); + var at = start; + var n: usize = 0; + while (at < end) : (at += n) { + n = @min(end - at, most); + const item = [_]fw.Item{.{ .slot = e.slot, .ids = @ptrCast(ids[at..][0..n]) }}; + var g = f; + if (e.rows.len > 0 and e.rows[e.slot].spans.items.len > 0) g.images = .{ .rows = e.rows[e.slot].buf.ptr, .spans = e.rows[e.slot].spans.items, .lo = at }; + try g.run(st, &item); + } + if (end < ids.len) return null; + var t: [1]u32 = undefined; + try e.draw(&e.bp, n - 1, 1, ids.len, e.seqs[e.slot].sampling, &t); + return t[0]; + } + + /// Several streams' rows in one forward (each on its own slot), graphed. + pub fn verifyShared(e: *Engine, parts: []const Part) !void { + const st = &e.st.?; + if (parts.len == 0 or parts.len > max_shared) return error.WindowTooWide; + var items: [max_shared]fw.Item = undefined; + var ids: [shared_rows]i32 = undefined; + var rows: usize = 0; + for (parts, 0..) |p, i| { + if (p.ids.len == 0 or p.ids.len > window_rows or rows + p.ids.len > shared_rows) return error.WindowTooWide; + for (parts[0..i]) |q| if (q.slot == p.slot) return error.SlotTwice; + if (p.slot >= e.seqs.len) return error.Inkling2NoSlot; + if (st.pos[p.slot] + p.ids.len + 1 > e.capacity) return error.ContextFull; + for (p.ids, 0..) |t, r| ids[rows + r] = @intCast(t); + items[i] = .{ .slot = p.slot, .ids = ids[rows..][0..p.ids.len] }; + rows += p.ids.len; + } + const f = e.forward(&e.bd, e.shape_d); + const plan = try f.stage(st, items[0..parts.len]); + const Body = struct { + f: fw.Forward, + st: *const fw.State, + p: fw.Plan, + fn run(ctx: *anyopaque, _: cuda.Stream) anyerror!void { + const b: *@This() = @ptrCast(@alignCast(ctx)); + try b.f.launch(b.st, b.p); + } + }; + var body: Body = .{ .f = f, .st = st, .p = plan }; + const key: Key = .{ .n = @intCast(plan.n), .ni = @intCast(plan.ni), .nt = @intCast(plan.nt), .stride = plan.stride }; + const print = cuda.graph_cache.fingerprintOf(&.{ st.kc[0], e.bd.ids.ptr, e.bd.parts.o }); + _ = try e.graphs.run(key, e.stream, print, .{ .ctx = &body, .run = Body.run }); + fw.Forward.advance(st, items[0..parts.len]); + var row: usize = 0; + for (parts) |p| { + e.slot = p.slot; + try e.draw(&e.bd, row, p.ids.len, st.pos[p.slot] - p.ids.len + 1, e.seqs[p.slot].sampling, p.out[0..p.ids.len]); + row += p.ids.len; + } + } + + /// Rows of this rank's logits (from row `row0` of `b`) to tokens at first, first + 1, ...: sampled or greedy. + fn draw(e: *Engine, b: *fw.Buffers, row0: usize, rows: usize, first: u64, sm: ?sampler.Sampling, out: []u32) !void { + const sh = e.w.share; + const n = sh.vocab.len(); + const real = @min(n, @as(usize, e.c.real_vocab) -| sh.vocab.lo); + const logits = b.logits.ptr + row0 * n * 4; + if (sm) |s| { + try ops.tobf(&e.m.ops, e.stream, logits, rows, n, real, e.smp.full.ptr, e.smp.vocab, sh.vocab.lo, n); + try e.smp.draw(e.stream, e.exchange, e.spans, rows, first, sampler.rule(s), out); + return e.gathered(); + } + const stride = pickStride(rows); + const vals = e.picks.ptr + sh.rank * stride; + try ops.top1(&e.m.ops, e.stream, logits, rows, n, real, sh.vocab.lo, vals, vals + rows * 4); + switch (e.exchange) { + .local => {}, + .nccl => |x| if (x.group) |g| try g.allGather(e.stream, vals, e.picks.ptr, stride) else try x.lib.check(x.lib.api.ncclAllGather(vals, e.picks.ptr, stride, .u8, x.comm, e.stream.handle), "ncclAllGather"), + } + try e.stream.synchronize(); + try e.gathered(); + const bytes = e.picks_host[0 .. sh.world * stride]; + try e.picks.download(0, bytes); + for (0..rows) |r| { + var best: f32 = -std.math.inf(f32); + var id: u32 = 0; + for (0..sh.world) |q| { + const at = q * stride; + const v: f32 = @bitCast(std.mem.readInt(u32, bytes[at + r * 4 ..][0..4], .little)); + const i = std.mem.readInt(u32, bytes[at + rows * 4 + r * 4 ..][0..4], .little); + if (v > best or (v == best and i < id)) { + best = v; + id = i; + } + } + out[r] = id; + } + } + + /// After a synchronize: a RoCE gather that failed since the last one (its rows hold nothing valid) is an error. + fn gathered(e: *const Engine) !void { + switch (e.exchange) { + .local => {}, + .nccl => |x| if (x.group) |g| try g.check(), + } + } + + /// Bytes a kept state takes on this rank: the slot's sliding rings and conv states (global rows stay in place). + pub fn stateBytes(e: *const Engine) u64 { + return kept.bytes(&e.c, &e.st.?, e.convBytes()); + } + + /// The bound slot's state at its length kept under `id` (every rank keeps the same id). + pub fn keepAs(e: *Engine, id: u64, at: usize) !void { + if (at == 0 or at != e.pos()) return error.BadKeep; + try e.states.save(e.d, e.stream, &e.c, &e.st.?, e.slot, id, at, e.convBytes()); + } + + /// The bound slot restored to state `id` (it must be the state's slot, still holding its rows). + pub fn restoreState(e: *Engine, id: u64) !void { + try e.states.restore(e.d, e.stream, &e.c, &e.st.?, e.slot, id); + } + + pub fn dropState(e: *Engine, id: u64) void { + e.stream.synchronize() catch {}; + e.states.drop(id); + } +}; + +/// A rank's greedy picks of `rows` rows (fp32 values, then i32 ids) padded to 16 bytes: the RoCE gather takes them. +fn pickStride(rows: usize) usize { + return std.mem.alignForward(usize, rows * 8, 16); +} diff --git a/zig/src/families/inkling2/engine_main.zig b/zig/src/families/inkling2/engine_main.zig new file mode 100644 index 00000000000..cedb3cfbb35 --- /dev/null +++ b/zig/src/families/inkling2/engine_main.zig @@ -0,0 +1,153 @@ +//! tf-inkling2-engine: the serving engine's checks on one or two ranks (both run the same loop, no plan words). +const std = @import("std"); +const cuda = @import("cuda"); +const ink = @import("inkling2"); + +const usage = "usage: tf-inkling2-engine graphs|greedy [context] [new]\n" ++ + " graphs: decode rows eager in some slots and graphed in others on the same rows; logits must match bit for bit\n" ++ + " greedy: each text's prompt pass then greedy decode rows, eager (writes greedy.json: name -> tokens)\n" ++ + " two ranks: TF_INKLING2_RANK, TF_INKLING2_WORLD and NCCL_COMM_ID on both\n"; + +const Text = struct { name: []const u8, ids: []u32 }; + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len < 5) { + std.debug.print("{s}", .{usage}); + return 2; + } + const graphs = std.mem.eql(u8, args[1], "graphs"); + if (!graphs and !std.mem.eql(u8, args[1], "greedy")) { + std.debug.print("{s}", .{usage}); + return 2; + } + const text = try std.Io.Dir.cwd().readFileAlloc(io, args[3], a, .limited(1 << 26)); + var doc = try std.json.parseFromSlice(std.json.Value, a, text, .{}); + defer doc.deinit(); + var list: std.ArrayList(Text) = .empty; + var it = doc.value.object.iterator(); + while (it.next()) |e| { + const v = e.value_ptr.array.items; + const ids = try a.alloc(u32, v.len); + for (v, ids) |x, *id| id.* = @intCast(x.integer); + try list.append(a, .{ .name = e.key_ptr.*, .ids = ids }); + } + const context = if (args.len > 5) try std.fmt.parseInt(usize, args[5], 10) else 32768; + const new = if (args.len > 6) try std.fmt.parseInt(usize, args[6], 10) else 64; + + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + if (try ctx.capability() != 121) return error.Inkling2RequiresSm121; + const place = try ink.admit.place(); + var group: ?cuda.tp_group.Group = null; + defer if (group) |*g| g.close(); // after the engine (its graphs hold the comm's kernels), as the server closes + const e = try ink.engine.Engine.init(gpa, io, &driver, args[2], place.rank, place.world, .{ .capacity = ink.native_exl3.capacity(context) }); + defer e.deinit(); + if (place.world > 1) { + group = try cuda.tp_group.Group.open(&driver, place.rank, place.world); + try group.?.openRoce(gpa, io, &driver, e.stream, e.roceBytes()); + e.exchange = .{ .nccl = .{ .lib = &group.?.lib, .comm = group.?.comm, .group = &group.? } }; + } + try e.reserve(16); + try std.Io.Dir.cwd().createDirPath(io, args[4]); + var out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + defer out.close(io); + const r0 = place.rank == 0; + if (!graphs) { + e.graphs.settings.on = false; + var json: std.ArrayList(u8) = .empty; + try json.appendSlice(a, "{"); + for (list.items, 0..) |t, i| { + const toks = try greedy(e, a, t.ids, new); + try json.print(a, "{s}\"{s}\": [", .{ if (i > 0) ", " else "", t.name }); + for (toks, 0..) |x, j| try json.print(a, "{s}{d}", .{ if (j > 0) ", " else "", x }); + try json.appendSlice(a, "]"); + if (r0) std.debug.print("{s}: {d} prompt tokens, {d} greedy tokens\n", .{ t.name, t.ids.len, toks.len }); + } + try json.appendSlice(a, "}\n"); + if (r0) try out.writeFile(io, .{ .sub_path = "greedy.json", .data = json.items }); + return 0; + } + // cases: k streams, `steps` decode rows each; a text of 16,380+ tokens also crosses a global chunk + const Case = struct { k: usize, steps: usize, at: usize }; + var cases: std.ArrayList(Case) = .empty; + for ([_]usize{ 1, 2, 3, 4, 8 }) |k| try cases.append(a, .{ .k = k, .steps = 6, .at = 0 }); + for (list.items) |t| if (t.ids.len >= 16390) { + try cases.append(a, .{ .k = 1, .steps = 8, .at = 16380 }); + try cases.append(a, .{ .k = 2, .steps = 8, .at = 16380 }); + break; + }; + var pass: usize = 0; + var total: usize = 0; + for (cases.items) |cs| { + const diff = try graphCase(e, a, list.items, cs.k, cs.steps, cs.at); + total += cs.steps; + pass += cs.steps - diff; + if (r0) std.debug.print("case {d} streams from {s}: {d}/{d} steps equal\n", .{ cs.k, if (cs.at > 0) "16380" else "prompt end", cs.steps - diff, cs.steps }); + } + const st = e.graphs.stats; + if (r0) std.debug.print("graphs: {d}/{d} steps bit-identical; captured {d}, replayed {d}, eager {d}\n", .{ pass, total, st.captured, st.replayed, st.eager }); + return if (pass == total) 0 else 1; +} + +/// A text's prompt pass on the bound slot then `n` greedy tokens, one decode row at a time. +fn greedy(e: *ink.engine.Engine, a: std.mem.Allocator, ids: []const u32, n: usize) ![]u32 { + try e.bind(0); + e.begin(null); + var at: usize = 0; + var tok: u32 = while (true) : (at += ink.engine.prompt_rows) { + if (try e.prefillChunk(ids, at)) |t| break t; + }; + const toks = try a.alloc(u32, n); + for (toks) |*x| { + x.* = tok; + var o: [1]u32 = undefined; + try e.verifyShared(&.{.{ .slot = 0, .ids = &.{tok}, .out = &o }}); + tok = o[0]; + } + return toks; +} + +/// One case: the same streams in slots 0..k (eager) and k..2k (graphed); returns the steps whose logits differ. +fn graphCase(e: *ink.engine.Engine, a: std.mem.Allocator, texts: []const Text, k: usize, steps: usize, at: usize) !usize { + var pend: [8]u32 = undefined; + var src: [8][]const u32 = undefined; + var long: ?[]const u32 = null; + for (texts) |t| if (t.ids.len >= 16390) { + long = t.ids; + }; + for (0..k) |i| { + src[i] = if (at > 0) long.?[0..at] else texts[i % texts.len].ids; + for ([_]usize{ i, k + i }) |slot| { + try e.bind(@intCast(slot)); + e.begin(null); + var p: usize = 0; + pend[i] = while (true) : (p += ink.engine.prompt_rows) { + if (try e.prefillChunk(src[i], p)) |t| break t; + }; + } + } + const nv = e.w.share.vocab.len(); + var diff: usize = 0; + for (0..steps) |_| { + var outs: [2][8][1]u32 = undefined; + var logits: [2][]u8 = undefined; + for (0..2) |arm| { + var parts: [8]ink.engine.Part = undefined; + for (0..k) |i| parts[i] = .{ .slot = @intCast(arm * k + i), .ids = pend[i..][0..1], .out = &outs[arm][i] }; + e.graphs.settings.on = arm == 1; + try e.verifyShared(parts[0..k]); + try e.stream.synchronize(); + logits[arm] = try a.alloc(u8, k * nv * 4); + try e.bd.logits.download(0, logits[arm]); + } + if (!std.mem.eql(u8, logits[0], logits[1])) diff += 1; + for (0..k) |i| pend[i] = outs[0][i][0]; + } + return diff; +} diff --git a/zig/src/families/inkling2/follow.zig b/zig/src/families/inkling2/follow.zig new file mode 100644 index 00000000000..c3326ccfdf0 --- /dev/null +++ b/zig/src/families/inkling2/follow.zig @@ -0,0 +1,291 @@ +//! TP over processes: rank 0's Leader sends each step (a header, then ids) by NCCL first; the other ranks `follow`. +const std = @import("std"); +const cuda = @import("cuda"); +const engine = @import("engine.zig"); +const ops = @import("ops.zig"); +const sampler = @import("sampler.zig"); +const Engine = engine.Engine; +const image = @import("image.zig"); +const vision = @import("vision.zig"); +const pictures = @import("pictures.zig"); + +pub const Kind = enum(u32) { begin = 1, chunk, shared, release, idle, end, save, drop, reserve, images }; + +/// One step as it crosses: 64 bytes, then `n` u32 ids. NCCL waits as long as it takes, so a follower idles safely. +pub const Header = extern struct { + kind: u32, + n: u32 = 0, // ids that follow + depth: u32 = 0, // shared: its parts; chunk: where it starts + flags: u32 = 0, // begin: 1 sampled + a: u64 = 0, // chunk: the prompt's length; save: the state's id; reserve: slots + seed: u64 = 0, // chunk: a kept state's id to resume from (0: none); save: its position + temperature: f64 = 0, + top_p: f64 = 0, + min_p: f64 = 0, + top_k: u32 = 0, + slot: u32 = 0, // the stream's slot the step runs on + + comptime { + std.debug.assert(@sizeOf(Header) == 64); + } +}; + +pub const put_ids = 96 - 16; + +pub const Link = struct { + lib: *const cuda.nccl.Library, + comm: cuda.nccl.Comm, + stream: cuda.Stream, + buf: cuda.DeviceBuffer, // header, then ids + ids: []u32, // host copy of the last step's ids + gpa: std.mem.Allocator, + asleep: bool = false, // rank 0: the other ranks sleep on their lines (cuda.tp_watch) until its next step + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, lib: *const cuda.nccl.Library, comm: cuda.nccl.Comm, stream: cuda.Stream, max_ids: usize) !Link { + var buf = try cuda.DeviceBuffer.alloc(d, 64 + max_ids * 4); + errdefer buf.free(); + return .{ .lib = lib, .comm = comm, .stream = stream, .buf = buf, .ids = try gpa.alloc(u32, max_ids), .gpa = gpa }; + } + + pub fn deinit(l: *Link) void { + l.gpa.free(l.ids); + l.buf.free(); + } + + fn post(l: *Link, bytes: usize) !void { + try l.lib.check(l.lib.api.ncclBroadcast(l.buf.ptr, l.buf.ptr, bytes, .u8, 0, l.comm, l.stream.handle), "ncclBroadcast"); + } + + /// Rank 0: the step, then its ids, to every rank in two broadcasts; up to `put_ids` ids by a kernel, unwaited. + pub fn send(l: *Link, k: *const ops.Kernels, h: Header, ids: []const u32) !void { + if (ids.len > l.ids.len) return error.TooManyIds; + var hh = h; + hh.n = @intCast(ids.len); + if (ids.len <= put_ids) { + var w: ops.Words = undefined; + @memcpy(w.w[0..16], std.mem.bytesAsSlice(u32, std.mem.asBytes(&hh))); + @memcpy(w.w[16..][0..ids.len], ids); + try ops.putWords(k, l.stream, l.buf.ptr, 16 + ids.len, w); + } else { + try l.buf.uploadAsync(0, std.mem.asBytes(&hh), l.stream.handle); + try l.buf.uploadAsync(64, std.mem.sliceAsBytes(ids), l.stream.handle); + } + try l.post(64); + if (ids.len > 0) try l.post(64 + ids.len * 4); + if (ids.len > put_ids) try l.stream.synchronize(); // the host ids' upload is done before they change + } + + /// Other ranks: the next step and its ids (valid until the next receive). + pub fn receive(l: *Link) !struct { h: Header, ids: []const u32 } { + try l.post(64); + try l.stream.synchronize(); + var h: Header = undefined; + try l.buf.download(0, std.mem.asBytes(&h)); + if (h.n > l.ids.len) return error.TooManyIds; + if (h.n > 0) { + try l.post(64 + h.n * 4); + try l.stream.synchronize(); + try l.buf.download(64, std.mem.sliceAsBytes(l.ids[0..h.n])); + } + return .{ .h = h, .ids = l.ids[0..h.n] }; + } +}; + +/// A kept prompt state: its id (the same on every rank) and the position it stands at. +pub const Kept = struct { id: u64, at: u32 }; + +/// Rank 0's engine: every step goes to the other ranks first. +pub const Leader = struct { + e: *Engine, + link: ?*Link, // null: one rank + next_id: u64 = 1, + dropped: std.ArrayList(u64) = .empty, // ids dropped since the other ranks last heard + + pub fn deinit(x: *Leader) void { + x.dropped.deinit(x.e.gpa); + } + + fn send(x: *Leader, h: Header, ids: []const u32) !void { + const l = x.link orelse return; + if (h.kind != @backingInt(Kind.drop)) try x.flush(); + var hh = h; + hh.slot = x.e.slot; + if (l.asleep) { + cuda.tp_watch.wake(); + l.asleep = false; + } + try l.send(&x.e.m.ops, hh, ids); + } + + /// States rank 0 dropped since the last step, so the other ranks free theirs too. + fn flush(x: *Leader) anyerror!void { + const d = &x.dropped; + while (d.items.len > 0) { + const n = @min(d.items.len, put_ids / 2); + var ids: [put_ids]u32 = undefined; + for (d.items[0..n], 0..) |id, i| ids[2 * i ..][0..2].* = .{ @truncate(id), @truncate(id >> 32) }; + try x.send(.{ .kind = @backingInt(Kind.drop) }, ids[0 .. 2 * n]); + d.replaceRangeAssumeCapacity(0, n, &.{}); + } + } + + /// Every rank's caches for `slots` streams. + pub fn reserve(x: *Leader, slots: usize) !void { + try x.send(.{ .kind = @backingInt(Kind.reserve), .a = slots }, &.{}); + try x.e.reserve(slots); + } + + /// The bound slot's state at `at` kept on every rank under one new id. + pub fn save(x: *Leader, at: usize) !Kept { + const id = x.next_id; + x.next_id += 1; // an id is used once, even when this rank's copy then fails + if (at == 0 or at != x.e.pos()) return error.BadKeep; + try x.send(.{ .kind = @backingInt(Kind.save), .a = id, .seed = at }, &.{}); + x.e.keepAs(id, at) catch |err| { + x.drop(id); + return err; + }; + return .{ .id = id, .at = @intCast(at) }; + } + + /// A state rank 0's store let go: freed here now, on the other ranks at the next step. + pub fn drop(x: *Leader, id: u64) void { + x.e.dropState(id); + if (x.link != null) x.dropped.append(x.e.gpa, id) catch {}; + } + + /// No stream is left: the other ranks sleep on their lines until the next step instead of spinning in NCCL. + pub fn idle(x: *Leader) !void { + const l = x.link orelse return; + if (l.asleep or !cuda.tp_watch.open()) return; + try x.send(.{ .kind = @backingInt(Kind.idle) }, &.{}); + l.asleep = true; + } + + pub fn bind(x: *Leader, slot: u32) !void { + try x.e.bind(slot); + } + + pub fn release(x: *Leader, slot: u32) !void { + try x.e.bind(slot); + try x.send(.{ .kind = @backingInt(Kind.release) }, &.{}); + } + + pub fn begin(x: *Leader, s: ?sampler.Sampling) !void { + const c = sampler.check(s); + var h: Header = .{ .kind = @backingInt(Kind.begin) }; + if (c) |v| { + h.flags = 1; + h.seed = v.seed; + h.temperature = v.temperature; + h.top_p = v.top_p; + h.min_p = v.min_p; + h.top_k = v.top_k; + } + try x.send(h, &.{}); + x.e.begin(c); + } + + /// A prompt chunk on every rank, kept state `from` restored first; the first token once it ends the prompt. + pub fn chunk(x: *Leader, ids: []const u32, start: usize, from: ?u64, cancel: ?engine.Cancel) !?u32 { + if (start >= ids.len) return error.BadChunk; + const part = ids[start..@min(ids.len, start + engine.prompt_rows)]; + // rank 0's cancel decides before the step goes out: every rank runs a chunk it is sent + if (cancel) |c| if (c.check(c.ptr)) return error.Cancelled; + if (from) |id| { + const w = x.e.states.where(id) orelse return error.SnapshotStale; + if (w.at != start or w.slot != x.e.slot) return error.BadChunk; + } else if (start % engine.prompt_rows != 0 or (start != 0 and start != x.e.pos())) return error.BadChunk; + try x.send(.{ .kind = @backingInt(Kind.chunk), .depth = @intCast(start), .a = ids.len, .seed = from orelse 0 }, part); + if (from) |id| try x.e.restoreState(id); + return x.e.prefillChunk(ids, start); + } + + /// Several streams' rows in one forward on every rank: parts' slots and rows, then ids. + pub fn verifyShared(x: *Leader, parts: []const engine.Part) !void { + if (parts.len == 0 or parts.len > engine.max_shared) return error.WindowTooWide; + var buf: [2 * engine.max_shared + engine.shared_rows]u32 = undefined; + var n: usize = 2 * parts.len; + for (parts, 0..) |p, i| { + if (n + p.ids.len > buf.len or p.ids.len == 0 or p.ids.len > engine.window_rows) return error.WindowTooWide; + for (parts[0..i]) |q| if (q.slot == p.slot) return error.SlotTwice; + buf[2 * i] = p.slot; + buf[2 * i + 1] = @intCast(p.ids.len); + @memcpy(buf[n..][0..p.ids.len], p.ids); + n += p.ids.len; + } + try x.send(.{ .kind = @backingInt(Kind.shared), .depth = @intCast(parts.len) }, buf[0..n]); + try x.e.verifyShared(parts); + } + + /// The bound slot's pictures on every rank: their spans go out first, then rank 0 encodes and sends the rows. + pub fn images(x: *Leader, pics: []const image.Prepared, spans: []const vision.Span) !void { + var words: [3 * 64]u32 = undefined; + _ = try pictures.checkSpans(spans, x.e.vision orelse return error.NoVision); + try x.send(.{ .kind = @backingInt(Kind.images), .depth = @intCast(spans.len) }, try pictures.toWords(spans, &words)); + try x.e.images(pics, spans); + } + + pub fn end(x: *Leader) !void { + try x.send(.{ .kind = @backingInt(Kind.end) }, &.{}); + } +}; + +/// A rank other than 0 runs rank 0's steps until it ends (rank 0 decides cancels before it sends a step). +pub fn follow(e: *Engine, link: *Link) !void { + cuda.tp_watch.sleep(e.io); + while (true) { + const step = try link.receive(); + const h = step.h; + const kind: Kind = @fromBackingInt(@intCast(h.kind)); + if (kind == .begin or kind == .chunk or kind == .save or kind == .images) try e.bind(h.slot); + switch (kind) { + .reserve => try e.reserve(@intCast(h.a)), + .begin => e.begin(if (h.flags & 1 != 0) .{ .seed = h.seed, .temperature = h.temperature, .top_p = h.top_p, .min_p = h.min_p, .top_k = h.top_k } else null), + .chunk => { + // the prompt's ids past this chunk are not needed here: the chunk's own rows carry its positions + const ids = try e.gpa.alloc(u32, h.a); + defer e.gpa.free(ids); + @memset(ids, 0); + @memcpy(ids[h.depth..][0..step.ids.len], step.ids); + if (h.seed != 0) try e.restoreState(h.seed); + _ = try e.prefillChunk(ids, h.depth); + }, + .shared => { + const k = h.depth; + if (k == 0 or k > engine.max_shared or step.ids.len < 2 * k) return error.BadStep; + var parts: [engine.max_shared]engine.Part = undefined; + var outs: [engine.shared_rows]u32 = undefined; + var at: usize = 2 * k; + var row: usize = 0; + for (parts[0..k], 0..) |*p, i| { + const n = step.ids[2 * i + 1]; + if (at + n > step.ids.len or row + n > outs.len) return error.BadStep; + p.* = .{ .slot = step.ids[2 * i], .ids = step.ids[at..][0..n], .out = outs[row..][0..n] }; + at += n; + row += n; + } + try e.verifyShared(parts[0..k]); + }, + .images => { + var spans: [64]vision.Span = undefined; + try e.images(null, try pictures.fromWords(step.ids, &spans)); + }, + .release => {}, + .save => try e.keepAs(h.a, @intCast(h.seed)), + .drop => { + var i: usize = 0; + while (i + 1 < step.ids.len) : (i += 2) e.dropState(@as(u64, step.ids[i]) | @as(u64, step.ids[i + 1]) << 32); + }, + .idle => cuda.tp_watch.sleep(e.io), + .end => return cuda.tp_watch.ended(), + } + } +} + +test "a step's header is 64 bytes and keeps its fields" { + const h: Header = .{ .kind = @backingInt(Kind.shared), .n = 3, .depth = 2, .flags = 1, .a = 7, .seed = 1 << 62, .temperature = 0.6, .top_p = 0.95, .top_k = 20 }; + var back: Header = undefined; + @memcpy(std.mem.asBytes(&back), std.mem.asBytes(&h)); + try std.testing.expectEqual(h, back); +} diff --git a/zig/src/families/inkling2/forward.zig b/zig/src/families/inkling2/forward.zig new file mode 100644 index 00000000000..eca983c9556 --- /dev/null +++ b/zig/src/families/inkling2/forward.zig @@ -0,0 +1,515 @@ +//! Inkling 2's decoder forward on one rank: streams' rows (prompt chunks or decode rows) to softcapped logits. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("shape.zig"); +const kernels = @import("kernels.zig"); +const ops = @import("ops.zig"); +const experts = @import("experts.zig"); +const weights = @import("pack_weights.zig"); +const vision = @import("vision.zig"); +const prompt_dense = @import("prompt_dense.zig"); + +const Buf = cuda.DeviceBuffer; + +/// The kernels a forward launches: main's dense and grouped EXL3, the family's attention and glue. +pub const Modules = struct { + dense: cuda.exl3.Dense, + experts: experts.Kernels, + attn: kernels.Kernels, + ops: ops.Kernels, + side: Side, + prompt: ?prompt_dense.Prompt = null, // prompt rows' dense projections (Engine.init sets it once the weights load) + + pub fn load(d: *const cuda.Driver) !Modules { + var dense = try cuda.exl3.Dense.load(d); + errdefer dense.unload(); + var ex = try experts.Kernels.load(d); + errdefer ex.unload(); + var attn = try kernels.Kernels.load(d); + errdefer attn.unload(); + var o = try ops.Kernels.load(d); + errdefer o.unload(); + return .{ .dense = dense, .experts = ex, .attn = attn, .ops = o, .side = try Side.init(d) }; + } + + pub fn deinit(m: *Modules) void { + if (m.prompt) |*p| p.deinit(); + m.side.deinit(); + m.ops.unload(); + m.attn.unload(); + m.experts.unload(); + m.dense.unload(); + } +}; + +/// A layer's narrow projections (r, k, v, row dots) run here beside q and the gate, on their own EXL3 scratch. +pub const Side = struct { + stream: cuda.Stream, + fork: cuda.Event, + join: cuda.Event, + dense: cuda.exl3.Dense, + + fn init(d: *const cuda.Driver) !Side { + var st = try cuda.Stream.init(d, true); + errdefer st.deinit(); + var fork = try cuda.Event.init(d, false); + errdefer fork.deinit(); + var join = try cuda.Event.init(d, false); + errdefer join.deinit(); + return .{ .stream = st, .fork = fork, .join = join, .dense = try cuda.exl3.Dense.load(d) }; + } + + fn deinit(x: *Side) void { + x.dense.unload(); + x.join.deinit(); + x.fork.deinit(); + x.stream.deinit(); + } +}; + +/// The geometry a stream's caches and a call's scratch are sized for. +pub const Shape = struct { + rows: usize, // most rows a call takes + context: usize, // most positions a stream reaches + heads: usize, // the rank's query heads + kv: usize, // the rank's key heads + ring_rows: usize = 0, // rows a call may write into a sliding ring (0: rows) + + pub fn sliding(s: Shape, c: *const cfg.Config) kernels.Layer { + return kernels.Layer.sliding(c.window, @intCast(if (s.ring_rows > 0) s.ring_rows else s.rows)); + } + + pub fn global(s: Shape) kernels.Layer { + return kernels.Layer.global(@intCast(s.context)); + } + + fn layer(s: Shape, c: *const cfg.Config, i: usize) kernels.Layer { + return if (c.layer[i] == .sliding) s.sliding(c) else s.global(); + } +}; + +/// Partials a (row, head) needs for a call whose rows reach `last_pos`: a sliding window's, or the global chunks'. +pub fn stride(c: *const cfg.Config, last_pos: usize) u32 { + const sl = kernels.Layer.sliding(c.window, 1); + return @max(kernels.slotsFor(sl, 1), kernels.chunks(last_pos, kernels.global_chunk)); +} + +/// Bytes of one cache slot of a stream: K and V rings a layer plus four conv states (the per-stream cost). +pub fn slotBytes(c: *const cfg.Config, s: Shape) u64 { + var total: u64 = 0; + for (0..c.layers) |i| { + total += 2 * @as(u64, s.layer(c, i).cacheBytes(s.kv)); + total += 2 * 3 * @as(u64, s.kv) * c.head_dim * 4 + 2 * 3 * @as(u64, c.hidden) * 4; + } + return total; +} + +fn alloc(d: *const cuda.Driver, list: *std.ArrayList(Buf), gpa: std.mem.Allocator, bytes: usize) !u64 { + var b = try Buf.alloc(d, @max(bytes, 256)); + errdefer b.free(); + try b.fill8(0, null); + try list.append(gpa, b); + return b.ptr; +} + +/// `slots` streams' caches and conv states: K and V rings a layer, the last three inputs of each short convolution. +pub const State = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(Buf) = .empty, + kc: []u64 = &.{}, + vc: []u64 = &.{}, + conv: [][4]u64 = &.{}, // k, v (fp32 [slots][3][kv * 128]) and attention, MLP (fp32 [slots][3][hidden]) a layer + pos: []usize = &.{}, // positions each slot's caches hold + ring: [2]usize = .{ 0, 0 }, // sliding and global ring slots a key head + kv: usize = 0, + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, c: *const cfg.Config, s: Shape, slots: usize) !State { + var st: State = .{ .gpa = gpa, .kv = s.kv }; + errdefer st.deinit(); + st.kc = try gpa.alloc(u64, c.layers); + st.vc = try gpa.alloc(u64, c.layers); + st.conv = try gpa.alloc([4]u64, c.layers); + st.pos = try gpa.alloc(usize, slots); + @memset(st.pos, 0); + st.ring = .{ s.sliding(c).ring, s.global().ring }; + for (0..c.layers) |i| { + const l = s.layer(c, i); + st.kc[i] = try alloc(d, &st.bufs, gpa, slots * l.cacheBytes(s.kv)); + st.vc[i] = try alloc(d, &st.bufs, gpa, slots * l.cacheBytes(s.kv)); + for (0..2) |j| st.conv[i][j] = try alloc(d, &st.bufs, gpa, slots * 3 * s.kv * c.head_dim * 4); + for (2..4) |j| st.conv[i][j] = try alloc(d, &st.bufs, gpa, slots * 3 * @as(usize, c.hidden) * 4); + } + return st; + } + + pub fn cache(st: *const State, i: usize) kernels.Cache { + return .{ .k = st.kc[i], .v = st.vc[i] }; + } + + /// Back to empty streams: caches and conv states zeroed. + pub fn reset(st: *State) !void { + for (st.bufs.items) |b| try b.fill8(0, null); + @memset(st.pos, 0); + } + + /// One slot's conv states zeroed on `s` (a fresh pass; its rings are only read at positions it writes). + pub fn clearSlot(st: *State, c: *const cfg.Config, d: *const cuda.Driver, slot: usize, s: cuda.Stream) !void { + for (st.conv) |cv| for (cv, 0..) |base, j| { + const n = 3 * (if (j < 2) st.kv * c.head_dim else @as(usize, c.hidden)) * 4; + const view: Buf = .{ .d = d, .ptr = base + slot * n, .len = n, .borrowed = true }; + try view.fill8(0, s.handle); + }; + st.pos[slot] = 0; + } + + pub fn deinit(st: *State) void { + for (st.bufs.items) |*b| b.free(); + st.bufs.deinit(st.gpa); + st.gpa.free(st.kc); + st.gpa.free(st.vc); + st.gpa.free(st.conv); + st.gpa.free(st.pos); + } +}; + +/// Rows a grouped-experts call takes: its grouping kernel holds rows x 8 picks in 64 KiB of shared memory. +const expert_rows = 2048; + +/// Most streams one call takes. +pub const max_items = 64; + +/// One stream's rows in a call: its slot and the ids at its next positions. +pub const Item = struct { slot: usize, ids: []const i32 }; + +/// Attention partials a call's rows write: `slots` (row, head, chunk) entries, fp32 sums, each chunk's max and total. +pub const Partials = struct { o: u64, ml: u64, slots: usize }; + +/// A call's scratch, sized for Shape.rows rows; the partials may be another Buffers' (one stream runs them in order). +pub const Buffers = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(Buf) = .empty, + ids: Buf = undefined, // int32 rows, then pos, seg_of, the segments and the tiles + x: u64 = 0, // bf16 [rows][hidden]: the residual stream between layers + resid: u64 = 0, // fp32 [rows][hidden]: the residual inside a layer + blocks: u64 = 0, // bf16 [8][rows][hidden]: the completed blocks' inputs of these rows + normed: u64 = 0, // bf16 [3][rows][hidden] + q: u64 = 0, + r: u64 = 0, + gate: u64 = 0, + kf: u64 = 0, + vf: u64 = 0, + kraw: u64 = 0, + vraw: u64 = 0, + dk: u64 = 0, + dv: u64 = 0, + sink: u64 = 0, + qo: u64 = 0, + relo: u64 = 0, + tab: u64 = 0, + parts: Partials = .{ .o = 0, .ml = 0, .slots = 0 }, + att: u64 = 0, + ao: u64 = 0, + scores: u64 = 0, + pick: u64 = 0, + wts: u64 = 0, + moe: u64 = 0, + gathered: u64 = 0, // fp32 [world][rows][hidden]: every rank's partial of a site (world > 1) + exs: cuda.exl3_experts.Scratch = undefined, + logits: Buf = undefined, // fp32 [rows][padded vocab of the rank] + + /// Scratch for `s.rows` rows; `shared` partials, else its own for every row at the shape's context. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const weights.Weights, s: Shape, shared: ?Partials) !Buffers { + const c = &w.config; + var b: Buffers = .{ .gpa = gpa }; + errdefer b.deinit(); + const n = s.rows; + const h: usize = c.hidden; + const hd: usize = c.head_dim; + const A = struct { + fn f(bb: *Buffers, dd: *const cuda.Driver, bytes: usize) !u64 { + return alloc(dd, &bb.bufs, bb.gpa, bytes); + } + }.f; + b.ids = try Buf.alloc(d, stageBytes(n, max_items, kernels.tileCount(n, c.group()) + max_items)); + b.x = try A(&b, d, n * h * 2); + b.resid = try A(&b, d, n * h * 4); + b.blocks = try A(&b, d, ops.max_blocks * n * h * 2); + b.normed = try A(&b, d, 3 * n * h * 2); + b.q = try A(&b, d, n * s.heads * hd * 2); + b.r = try A(&b, d, n * s.heads * c.d_rel * 2); + b.gate = try A(&b, d, n * s.heads * hd * 2); + b.kf = try A(&b, d, n * s.kv * hd * 4); + b.vf = try A(&b, d, n * s.kv * hd * 4); + b.kraw = try A(&b, d, n * s.kv * hd * 2); + b.vraw = try A(&b, d, n * s.kv * hd * 2); + b.dk = try A(&b, d, n * s.kv * c.conv * 4); + b.dv = try A(&b, d, n * s.kv * c.conv * 4); + b.sink = try A(&b, d, n * s.heads * 2); + b.qo = try A(&b, d, n * s.heads * hd * 2); + b.relo = try A(&b, d, n * s.heads * c.d_rel * 2); + b.tab = try A(&b, d, kernels.tableBytes(n, @intCast(s.heads))); + b.parts = shared orelse blk: { + const slots = n * s.heads * stride(c, s.context - 1); + break :blk .{ .o = try A(&b, d, slots * hd * 4), .ml = try A(&b, d, slots * 8), .slots = slots }; + }; + b.att = try A(&b, d, n * s.heads * hd * 2); + b.ao = try A(&b, d, n * h * 4); + b.scores = try A(&b, d, n * @as(usize, c.experts) * 4); + b.pick = try A(&b, d, n * c.topk * 4); + b.wts = try A(&b, d, n * c.topk * 4); + b.moe = try A(&b, d, n * h * 4); + if (w.share.world > 1) b.gathered = try A(&b, d, w.share.world * n * h * 4); + const el = w.layers[0].experts; + b.exs = try cuda.exl3_experts.scratch(try A(&b, d, try experts.scratchBytes(el, @min(n, expert_rows), c.topk)), el, @min(n, expert_rows), c.topk); + b.logits = try Buf.alloc(d, n * w.share.vocab.len() * 4); + return b; + } + + pub fn deinit(b: *Buffers) void { + for (b.bufs.items) |*x| x.free(); + b.bufs.deinit(b.gpa); + if (b.ids.len != 0) b.ids.free(); + if (b.logits.len != 0) b.logits.free(); + } +}; + +/// Partials for `rows` rows of `heads` heads at `context`, to share between a rank's Buffers. +pub fn partialsFor(d: *const cuda.Driver, list: *std.ArrayList(Buf), gpa: std.mem.Allocator, slots: usize) !Partials { + return .{ .o = try alloc(d, list, gpa, slots * kernels.head_dim * 4), .ml = try alloc(d, list, gpa, slots * 8), .slots = slots }; +} + +/// How the ranks' partials (after o_proj and the experts) meet: one rank alone, or gathered in rank order. +pub const Exchange = union(enum) { + local, + nccl: struct { lib: *const cuda.nccl.Library, comm: cuda.nccl.Comm, group: ?*const cuda.tp_group.Group = null }, +}; + +/// A conv input made of `parts` fp32 rank partials, `stride` elements apart. +const Parts = struct { x: u64, parts: i32, stride: i64 }; + +/// Where a call's staged words sit in Buffers.ids: ids, pos, seg_of (int32 a row), then segments and tiles. +const Layout = struct { segs: [2]usize, conv: usize, tiles: usize, end: usize }; + +fn layout(n: usize, ni: usize, nt: usize) Layout { + const at0 = std.mem.alignForward(usize, n * 12, 16); + const seg = ni * @sizeOf(kernels.Seg); + return .{ .segs = .{ at0, at0 + seg }, .conv = at0 + 2 * seg, .tiles = at0 + 2 * seg + ni * 16, .end = at0 + 2 * seg + ni * 16 + nt * @sizeOf(kernels.Tile) }; +} + +fn stageBytes(n: usize, ni: usize, nt: usize) usize { + return layout(n, ni, nt).end + 256; +} + +/// A prompt call's image rows (bf16 [tokens][hidden]) and spans; its rows stand at prompt positions lo, lo + 1, ... +pub const Images = struct { rows: u64, spans: []const vision.Span, lo: usize }; + +/// A staged call: its rows, streams, tiles, the latest row's position and the partials' stride. +pub const Plan = struct { n: usize, ni: usize, nt: usize, last: usize, stride: u32 }; + +pub const Forward = struct { + d: *const cuda.Driver, + m: *Modules, + w: *const weights.Weights, + b: *Buffers, + shape: Shape, + stream: cuda.Stream, + exchange: Exchange = .local, + images: ?Images = null, // a prompt call's pictures: its one stream's rows from prompt position `lo` + last_logits: bool = false, // the head on the call's last row only (a prompt chunk draws from it alone) + + /// Where a site's fp32 partial of `n` rows goes: this rank's slot of the gathered buffer, or `own` at one rank. + fn slot(f: Forward, own: u64, n: usize) u64 { + if (f.w.share.world == 1) return own; + return f.b.gathered + f.w.share.rank * n * f.w.config.hidden * 4; + } + + /// Every rank's partial into every rank's gathered buffer (RoCE writes when they fit); convs add them in order. + fn gather(f: Forward, n: usize) !Parts { + const h: usize = f.w.config.hidden; + switch (f.exchange) { + .local => return error.Inkling2NoExchange, + .nccl => |x| if (x.group) |g| try g.allGather(f.stream, f.slot(0, n), f.b.gathered, n * h * 4) else try x.lib.check(x.lib.api.ncclAllGather(f.slot(0, n), f.b.gathered, n * h, .f32, x.comm, f.stream.handle), "ncclAllGather"), + } + return .{ .x = f.b.gathered, .parts = @intCast(f.w.share.world), .stride = @intCast(n * h) }; + } + + /// The conv input of a partial site: the local buffer at one rank, else the gathered parts. + fn summed(f: Forward, own: u64, n: usize) !Parts { + if (f.w.share.world == 1) return .{ .x = own, .parts = 1, .stride = 0 }; + return f.gather(n); + } + + fn dense(f: Forward, wt: cuda.exl3.Weight, x: u64, rows: usize, y: u64, dt: cuda.exl3.DType) !void { + try f.proj(f.stream, &f.m.dense, wt, x, rows, y, dt); + } + + /// A projection of bf16 rows: prompt rows by the GEMM where it takes the weight, else the decode kernels. + fn proj(f: Forward, s: cuda.Stream, de: *cuda.exl3.Dense, wt: cuda.exl3.Weight, x: u64, rows: usize, y: u64, dt: cuda.exl3.DType) !void { + if (f.m.prompt) |*p| if (dt != .f16 and p.takes(wt, rows)) return p.run(s, wt, x, rows, y, dt == .f32); + try de.decode(s, wt, x, .bf16, rows, y, dt); + } + + /// Each item's ids at its stream's next positions through every layer; the rows' logits land in b.logits. + pub fn run(f: Forward, st: *State, items: []const Item) !void { + const p = try f.stage(st, items); + try f.launch(st, p); + advance(st, items); + } + + /// The items' streams stand past their rows. + pub fn advance(st: *State, items: []const Item) void { + for (items) |it| st.pos[it.slot] += it.ids.len; + } + + /// The call's ids, positions, segments and tiles uploaded (after the stream drains); launch runs on them. + pub fn stage(f: Forward, st: *const State, items: []const Item) !Plan { + const c = &f.w.config; + var n: usize = 0; + for (items) |it| { + if (it.ids.len == 0 or st.pos[it.slot] + it.ids.len > f.shape.context) return error.Inkling2Rows; + n += it.ids.len; + } + if (n == 0 or n > f.shape.rows or items.len > max_items) return error.Inkling2Rows; + const gpa = f.w.gpa; + var host: std.ArrayList(u8) = .empty; + defer host.deinit(gpa); + for (items) |it| try host.appendSlice(gpa, std.mem.sliceAsBytes(it.ids)); + for (items) |it| for (0..it.ids.len) |i| try host.appendSlice(gpa, std.mem.asBytes(&@as(i32, @intCast(st.pos[it.slot] + i)))); + for (items, 0..) |it, j| for (0..it.ids.len) |_| try host.appendSlice(gpa, std.mem.asBytes(&@as(i32, @intCast(j)))); + var segs: [2][max_items]kernels.Seg = undefined; + var cs: [max_items][4]i32 = undefined; + var last: usize = 0; + var row0: usize = 0; + const per = [2]usize{ f.shape.kv * st.ring[0] * c.head_dim, f.shape.kv * st.ring[1] * c.head_dim }; + for (items, 0..) |it, j| { + const p0 = st.pos[it.slot]; + for (0..2) |r| segs[r][j] = .{ .row0 = @intCast(row0), .n = @intCast(it.ids.len), .p0 = @intCast(p0), .off = @intCast(it.slot * per[r]) }; + cs[j] = .{ @intCast(row0), @intCast(it.ids.len), @intCast(it.slot), 0 }; + last = @max(last, p0 + it.ids.len - 1); + row0 += it.ids.len; + } + const ni = items.len; + var tl: [8192]kernels.Tile = undefined; + const nt = try kernels.tiles(segs[0][0..ni], c.group(), &tl); + const lay = layout(n, ni, nt); + try host.appendNTimes(gpa, 0, lay.segs[0] - host.items.len); + try host.appendSlice(gpa, std.mem.sliceAsBytes(segs[0][0..ni])); + try host.appendSlice(gpa, std.mem.sliceAsBytes(segs[1][0..ni])); + try host.appendSlice(gpa, std.mem.sliceAsBytes(cs[0..ni])); + try host.appendSlice(gpa, std.mem.sliceAsBytes(tl[0..nt])); + std.debug.assert(host.items.len == lay.end); + const p: Plan = .{ .n = n, .ni = ni, .nt = nt, .last = last, .stride = stride(c, last) }; + if (n * f.shape.heads * p.stride > f.b.parts.slots) return error.Inkling2Partials; + try f.stream.synchronize(); // the previous call's kernels may still read the staged rows + try f.b.ids.upload(0, host.items); + return p; + } + + /// A staged call's kernels only (no host work): a graph captures exactly this. + pub fn launch(f: Forward, st: *const State, p: Plan) !void { + const c = &f.w.config; + const n = p.n; + const h: usize = c.hidden; + const s = f.stream; + const k = &f.m.ops; + const b = f.b; + const base = b.ids.ptr; + const lay = layout(n, p.ni, p.nt); + var rows_by: [2]kernels.Rows = undefined; + for (&rows_by, lay.segs) |*r, at| r.* = .{ .rows = @intCast(n), .heads = @intCast(f.shape.heads), .kv_heads = @intCast(f.shape.kv), .pos = base + n * 4, .seg_of = base + n * 8, .segs = base + at, .tiles = base + lay.tiles, .n_tiles = @intCast(p.nt), .last_pos = @intCast(p.last), .streams = @intCast(p.ni) }; + const conv_segs = base + lay.conv; + const streams = p.ni; + try ops.embed(k, s, base, n, f.w.embed, f.w.embed_norm, b.x, h, c.eps); + if (f.images) |im| try vision.splice(f.d, s, c.hidden, im.rows, im.spans, im.lo, im.lo + n, b.x); + var nb: usize = 0; + const hd: usize = c.head_dim; + const kvw = f.shape.kv * hd; + for (f.w.layers, 0..) |*l, i| { + const global = l.kind == .global; + var mix: ops.MixArgs = .{ .partial = b.x, .query = l.attn_query, .out = b.normed, .n_blocks = @intCast(nb), .partial_bf16 = 1, .nq = @intCast(l.nq), .rows = @intCast(n), .c = @intCast(h), .eps = c.eps }; + for (0..nb) |j| mix.blocks[j] = b.blocks + j * n * h * 2; + mix.norm = l.norms; + try ops.mix(k, s, mix); + const xq = b.normed; + const xk = if (global) b.normed + n * h * 2 else xq; + const xv = if (global) b.normed + 2 * n * h * 2 else xq; + const a = &l.attn; + const sd = &f.m.side; + // prompt rows run the narrow projections on the main stream: one GEMM scratch, and they fill the GPU alone + const ss = if (f.m.prompt != null and n >= prompt_dense.min_rows) s else sd.stream; + try sd.fork.record(s); + try ss.wait(sd.fork); + try f.proj(ss, &sd.dense, a.r, xq, n, b.r, .bf16); + try f.proj(ss, &sd.dense, a.k, xk, n, b.kf, .f32); + try f.proj(ss, &sd.dense, a.v, xv, n, b.vf, .f32); + try ops.rowdot(k, ss, xq, a.sink, b.sink, n, f.shape.heads, h, true, false); + if (global) { + try ops.rowdot(k, ss, xk, a.k_proj, b.dk, n, f.shape.kv * c.conv, h, false, false); + try ops.rowdot(k, ss, xv, a.v_proj, b.dv, n, f.shape.kv * c.conv, h, false, false); + } + try sd.join.record(ss); + try f.dense(a.q, xq, n, b.q, .bf16); + try f.dense(a.gate, xq, n, b.gate, .bf16); + try s.wait(sd.join); + const cv = st.conv[i]; + try ops.conv(k, s, .{ .x = b.kf, .state = cv[0], .w = a.k_conv, .dyn = if (global) b.dk else 0, .heads = @intCast(f.shape.kv), .c = @intCast(kvw), .rows = @intCast(n), .mode = 0, .out = b.kraw, .segs = conv_segs, .state_stride = @intCast(3 * kvw) }, streams); + try ops.conv(k, s, .{ .x = b.vf, .state = cv[1], .w = a.v_conv, .dyn = if (global) b.dv else 0, .heads = @intCast(f.shape.kv), .c = @intCast(kvw), .rows = @intCast(n), .mode = 0, .out = b.vraw, .segs = conv_segs, .state_stride = @intCast(3 * kvw) }, streams); + var lay_i = f.shape.layer(c, i); + lay_i.ring = @intCast(st.ring[@intFromBool(global)]); // the caches' rings, whatever rows this call's scratch holds + const rows = rows_by[@intFromBool(global)]; + const prep: kernels.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = c.log_floor, .alpha = c.log_alpha, .eps = c.eps }; + try kernels.prep(&f.m.attn, s, rows, lay_i, prep, .{ b.q, b.kraw, b.vraw, b.r }, .{ a.q_scale, a.rel_scale }, b.qo, b.relo, st.cache(i)); + try kernels.relTable(&f.m.attn, s, rows, b.relo, a.rel_proj, b.tab); + try kernels.attend(&f.m.attn, s, rows, lay_i, p.stride, b.parts.slots, b.qo, st.cache(i), b.tab, b.parts.o, b.parts.ml, b.sink, b.gate, b.att); + try f.dense(a.o, b.att, n, f.slot(b.ao, n), .f32); + const ao = try f.summed(b.ao, n); + const boundary = i % c.block_layers == 0; + if (boundary) { + if (nb == ops.max_blocks) return error.Inkling2Blocks; + try copy(f.d, b.blocks + nb * n * h * 2, b.x, n * h * 2, s); + nb += 1; + } + try ops.conv(k, s, .{ .x = ao.x, .parts = ao.parts, .part_stride = ao.stride, .state = cv[2], .w = l.attn_conv, .base = if (boundary) 0 else b.x, .resid = b.resid, .round_in = 1, .c = @intCast(h), .rows = @intCast(n), .mode = 1, .segs = conv_segs, .state_stride = @intCast(3 * h) }, streams); + var mm: ops.MixArgs = .{ .partial = b.resid, .query = l.mlp_query, .out = b.normed, .n_blocks = @intCast(nb), .partial_bf16 = 0, .nq = 1, .rows = @intCast(n), .c = @intCast(h), .eps = c.eps }; + for (0..nb) |j| mm.blocks[j] = b.blocks + j * n * h * 2; + mm.norm[0] = l.mlp_norm; + try ops.mix(k, s, mm); + try ops.rowdot(k, s, b.normed, l.router, b.scores, n, c.experts, h, false, true); + try ops.topk(k, s, b.scores, l.bias, b.pick, b.wts, n, c.experts, c.topk, c.route_scale); + const out = f.slot(b.moe, n); + var r0: usize = 0; + while (r0 < n) : (r0 += expert_rows) { + const w = @min(expert_rows, n - r0); + const caps: experts.Caps = .{ .gate = c.gate_softcap, .up = c.up_softcap }; + const sel = r0 * c.topk * 4; + try experts.run(&f.m.experts, s, l.experts, caps, l.bits, b.normed + r0 * h * 2, h, .bf16, b.pick + sel, b.wts + sel, w, out + r0 * h * 4, b.exs); + } + const mo = try f.summed(b.moe, n); + try ops.conv(k, s, .{ .x = mo.x, .parts = mo.parts, .part_stride = mo.stride, .state = cv[3], .w = l.mlp_conv, .resid = b.resid, .out = b.x, .round_in = 1, .c = @intCast(h), .rows = @intCast(n), .mode = 2, .segs = conv_segs, .state_stride = @intCast(3 * h) }, streams); + } + var fm: ops.MixArgs = .{ .partial = b.x, .query = f.w.out_query, .out = b.normed, .n_blocks = @intCast(nb), .partial_bf16 = 1, .nq = 1, .rows = @intCast(n), .c = @intCast(h), .eps = c.eps }; + for (0..nb) |j| fm.blocks[j] = b.blocks + j * n * h * 2; + fm.norm[0] = f.w.norm; + try ops.mix(k, s, fm); + const nv = f.w.share.vocab.len(); + const hr: usize = if (f.last_logits) n - 1 else 0; // rows before hr keep no logits + try f.dense(f.w.head, b.normed + hr * h * 2, n - hr, b.logits.ptr + hr * nv * 4, .f32); + try ops.softcap(k, s, b.logits.ptr + hr * nv * 4, (n - hr) * nv, c.logit_softcap); + } +}; + +fn copy(d: *const cuda.Driver, dst: u64, src: u64, bytes: usize, s: cuda.Stream) !void { + const view: Buf = .{ .d = d, .ptr = dst, .len = bytes, .borrowed = true }; + try view.copyFrom(0, src, bytes, s.handle); +} + +test "forward: a staged call's words sit where launch reads them" { + const l = layout(3, 2, 2); + try std.testing.expectEqual(@as(usize, 48), l.segs[0]); + try std.testing.expectEqual(@as(usize, 48 + 2 * 2 * 24), l.conv); // two segment arrays (sliding, global) + try std.testing.expectEqual(@as(usize, 48 + 2 * 2 * 24 + 2 * 16), l.tiles); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(kernels.Seg)); + const c: cfg.Config = .{}; + try std.testing.expectEqual(@as(u32, 5), stride(&c, 100)); + try std.testing.expectEqual(@as(u32, 64), stride(&c, 1048575)); +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index c7086e916cf..aea5de47631 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -14,6 +14,17 @@ 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"); +pub const pictures = @import("pictures.zig"); +pub const chat = @import("chat.zig"); +pub const admit = @import("admit.zig"); +pub const forward = @import("forward.zig"); +pub const prompt_dense = @import("prompt_dense.zig"); +pub const sampler = @import("sampler.zig"); +pub const kept = @import("kept.zig"); +pub const engine = @import("engine.zig"); +pub const follow = @import("follow.zig"); +pub const lanes = @import("lanes.zig"); +pub const native_exl3 = @import("native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -34,4 +45,15 @@ test { _ = loop_model; _ = loop_math_cuda; _ = @import("shared_kernels_test.zig"); + _ = pictures; + _ = chat; + _ = admit; + _ = forward; + _ = prompt_dense; + _ = sampler; + _ = kept; + _ = engine; + _ = follow; + _ = lanes; + _ = native_exl3; } diff --git a/zig/src/families/inkling2/kept.zig b/zig/src/families/inkling2/kept.zig new file mode 100644 index 00000000000..e85494e08c9 --- /dev/null +++ b/zig/src/families/inkling2/kept.zig @@ -0,0 +1,122 @@ +//! Kept prompt states: a slot's sliding rings and conv states copied out; its global rows stay in the slot. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("shape.zig"); +const fw = @import("forward.zig"); + +/// One kept state: the slot whose global rows it needs, where it stands, its copy (null once a pass overwrote it). +const Snap = struct { slot: usize, at: usize, buf: ?cuda.DeviceBuffer }; + +/// Bytes a state takes on this rank: every sliding layer's K and V ring of one slot, then its conv states. +pub fn bytes(c: *const cfg.Config, st: *const fw.State, conv: usize) u64 { + var total: u64 = conv; + for (0..c.layers) |i| { + if (c.layer[i] == .sliding) total += 2 * ringBytes(c, st); + } + return total; +} + +fn ringBytes(c: *const cfg.Config, st: *const fw.State) usize { + return st.kv * st.ring[0] * c.head_dim * 2; +} + +/// States by id (the same ids on every rank); each names the slot that holds its global rows. +pub const Store = struct { + gpa: std.mem.Allocator, + map: std.AutoHashMapUnmanaged(u64, Snap) = .empty, + + pub fn deinit(s: *Store) void { + var it = s.map.valueIterator(); + while (it.next()) |x| if (x.buf) |*b| b.free(); + s.map.deinit(s.gpa); + } + + /// The slot's state at `at` copied under `id`. + pub fn save(s: *Store, d: *const cuda.Driver, stream: cuda.Stream, c: *const cfg.Config, st: *const fw.State, slot: usize, id: u64, at: usize, conv: usize) !void { + if (s.map.contains(id)) return error.BadKeep; + var buf = try cuda.DeviceBuffer.alloc(d, bytes(c, st, conv)); + errdefer buf.free(); + try copy(d, stream, c, st, slot, buf.ptr, true); + try stream.synchronize(); + try s.map.put(s.gpa, id, .{ .slot = slot, .at = at, .buf = buf }); + } + + /// State `id` back into `slot` (its own, its global rows still there): rings, conv states and length. + pub fn restore(s: *Store, d: *const cuda.Driver, stream: cuda.Stream, c: *const cfg.Config, st: *fw.State, slot: usize, id: u64) !void { + const x = s.map.get(id) orelse return error.SnapshotStale; + const buf = x.buf orelse return error.SnapshotStale; + if (x.slot != slot) return error.SnapshotElsewhere; + try copy(d, stream, c, st, slot, buf.ptr, false); + st.pos[slot] = x.at; + } + + /// A pass on `slot` from `from` rewrites its rows past it: the states that need them go (their ids stay, stale). + pub fn overwrite(s: *Store, slot: usize, from: usize) void { + var it = s.map.valueIterator(); + while (it.next()) |x| if (x.slot == slot and x.at > from) if (x.buf) |*b| { + b.free(); + x.buf = null; + }; + } + + pub fn drop(s: *Store, id: u64) void { + const kv = s.map.fetchRemove(id) orelse return; + if (kv.value.buf) |b| { + var bb = b; + bb.free(); + } + } + + /// Whether `id` is kept and still valid. + pub fn holds(s: *const Store, id: u64) bool { + const x = s.map.get(id) orelse return false; + return x.buf != null; + } + + /// The slot and position of a valid state `id`. + pub fn where(s: *const Store, id: u64) ?struct { slot: usize, at: usize } { + const x = s.map.get(id) orelse return null; + if (x.buf == null) return null; + return .{ .slot = x.slot, .at = x.at }; + } + + /// Valid states on `slot` (a fresh pass there ends them all). + pub fn on(s: *const Store, slot: usize) usize { + var n: usize = 0; + var it = s.map.valueIterator(); + while (it.next()) |x| n += @intFromBool(x.slot == slot and x.buf != null); + return n; + } +}; + +/// The slot's rings and conv states to (out) or from `buf`, layer after layer. +fn copy(d: *const cuda.Driver, stream: cuda.Stream, c: *const cfg.Config, st: *const fw.State, slot: usize, buf: u64, out: bool) !void { + const rb = ringBytes(c, st); + var off: u64 = 0; + for (0..c.layers) |i| { + if (c.layer[i] != .sliding) continue; + for ([_]u64{ st.kc[i], st.vc[i] }) |base| { + const src = base + slot * rb; + try move(d, stream, if (out) buf + off else src, if (out) src else buf + off, rb); + off += rb; + } + } + for (st.conv) |cv| for (cv, 0..) |base, j| { + const n = 3 * (if (j < 2) st.kv * c.head_dim else @as(usize, c.hidden)) * 4; + const src = base + slot * n; + try move(d, stream, if (out) buf + off else src, if (out) src else buf + off, n); + off += n; + }; +} + +fn move(d: *const cuda.Driver, stream: cuda.Stream, dst: u64, src: u64, n: usize) !void { + try d.check(d.api.cuMemcpyDtoDAsync_v2(dst, src, n, stream.handle), "cuMemcpyDtoDAsync"); +} + +test "kept: a state at 1M holds 40 sliding layers' rings of a slot, not the global rows" { + var c: cfg.Config = .{}; + for (0..c.layers) |i| c.layer[i] = if (i % 6 == 5) .global else .sliding; + const st: fw.State = .{ .gpa = std.testing.allocator, .ring = .{ 3072, 1048576 }, .kv = 4 }; + // 40 layers x K and V x 4 key heads x 3,072 slots x 128 x 2 B = 240 MiB, plus the conv states + try std.testing.expectEqual(@as(u64, 240 << 20) + 7, bytes(&c, &st, 7)); +} diff --git a/zig/src/families/inkling2/lanes.zig b/zig/src/families/inkling2/lanes.zig new file mode 100644 index 00000000000..435da0a3aae --- /dev/null +++ b/zig/src/families/inkling2/lanes.zig @@ -0,0 +1,267 @@ +//! Inkling 2's lane backend: a slot per stream, decode rows shared across streams in one forward, chunked prompts. +const std = @import("std"); +const lanes = @import("lanes"); +const engine = @import("engine.zig"); +const follow = @import("follow.zig"); +const image = @import("image.zig"); +const pictures = @import("pictures.zig"); + +const be = lanes.backend; + +/// First tokens a handle names. +const ring = 1024; +pub const max_rows = engine.window_rows; + +/// A stream's place in the backend: its slot and its first token. +const Lane = struct { + slot: u32, + first: ?u64 = null, + fill: ?usize = null, // a prompt pass going a chunk at a time: where its next chunk starts + pictures: bool = false, // an image prompt: never resumed from or kept in the prompt cache +}; + +pub const Lanes = struct { + x: follow.Leader, + lanes: std.AutoHashMapUnmanaged(*const lanes.Stream, Lane) = .empty, + drawn: [ring]u32 = undefined, + next: u64 = 0, + shared: u64 = 0, // forwards that held several streams' windows + + pub fn deinit(self: *Lanes) void { + self.lanes.deinit(self.x.e.gpa); + self.x.deinit(); + } + + pub fn backend(self: *Lanes) be.Backend { + return .{ .ptr = self, .vtable = &vt }; + } + + const vt: be.Backend.VTable = .{ + .prefill = prefillFn, + .prefill_step = prefillStepFn, + .cancel_prefill = cancelPrefillFn, + .first = firstFn, + .queue = queueFn, + .read = readFn, + .verify = verifyFn, + .keep = keepFn, + .draft = draftFn, + .release = releaseFn, + }; + + /// Round facts: one row a stream, no drafts, several streams' rows in one shared forward. + pub fn facts(self: *const Lanes) lanes.Model { + _ = self; + return .{ + .copy_drafts = false, + .exact_width = max_rows, + .gpu_tokens = false, + .speculate = false, + .speculate_early = false, + .drafts = 0, + .plain_share = true, // one-row windows of several streams share a forward + .hidden_rows = true, + .batch_rows = engine.shared_rows, + .max_streams = engine.max_shared, + }; + } + + fn of(ptr: *anyopaque) *Lanes { + return @ptrCast(@alignCast(ptr)); + } + + fn take(self: *Lanes, token: u32) u64 { + const h = self.next; + self.drawn[h % ring] = token; + self.next += 1; + return h; + } + + fn taken(self: *const Lanes, slot: usize) bool { + var it = self.lanes.valueIterator(); + while (it.next()) |l| if (l.slot == slot) return true; + return false; + } + + /// A free slot: the kept state's when it is free, else the free one holding the fewest kept states. + fn pick(self: *const Lanes, s: *const lanes.Stream) !u32 { + if (s.reuse.saved) |saved| { + const k: *const follow.Kept = @ptrCast(@alignCast(saved)); + if (self.x.e.states.where(k.id)) |w| if (!self.taken(w.slot)) return @intCast(w.slot); + } + var best: ?u32 = null; + var held: usize = std.math.maxInt(usize); + for (0..self.x.e.slotCount()) |i| { + if (self.taken(i)) continue; + const n = self.x.e.states.on(i); + if (n < held) { + held = n; + best = @intCast(i); + } + } + return best orelse error.NoFreeSlot; + } + + /// The stream's slot bound. + fn bind(self: *Lanes, s: *const lanes.Stream) !*Lane { + const l = self.lanes.getPtr(s) orelse return error.UnknownStream; + try self.x.bind(l.slot); + return l; + } + + fn cancelled(ptr: ?*anyopaque) bool { + return @as(*lanes.Stream, @ptrCast(@alignCast(ptr.?))).isCancelled(); + } + + /// A prompt pass begins: the stream's slot claimed and bound; where it resumes (a kept state in this slot). + fn opening(self: *Lanes, s: *lanes.Stream) !?follow.Kept { + const ids = s.prompt(); + if (ids.len + s.max_new + max_rows >= self.x.e.capacity) return error.PromptTooLong; + if (s.images.len > 0 and self.x.e.vision == null) return error.NoVision; + const gop = try self.lanes.getOrPut(self.x.e.gpa, s); + if (!gop.found_existing) gop.value_ptr.* = .{ .slot = try self.pick(s) }; + const l = gop.value_ptr; + l.fill = null; + l.first = null; + l.pictures = s.images.len > 0; + errdefer _ = self.lanes.remove(s); + try self.x.bind(l.slot); + try self.x.begin(s.sampling); + s.cached = 0; + if (l.pictures) { + // every picture shares the placeholder id, so a kept state cannot tell two pictures apart + var pics: [64]image.Prepared = undefined; + const spans = try pictures.fromRequest(self.x.e.gpa, ids, s.images, &pics); + defer self.x.e.gpa.free(spans); + try self.x.images(pics[0..s.images.len], spans); + return null; + } + return if (s.prompt_logprobs != null) null else self.resumeFrom(s, ids.len, l.slot); + } + + /// The stream's kept state, where its pass starts (null: none, off the grid, another slot's, or overwritten). + fn resumeFrom(self: *Lanes, s: *lanes.Stream, len: usize, slot: u32) ?follow.Kept { + const saved = s.reuse.saved orelse return null; + const k: *const follow.Kept = @ptrCast(@alignCast(saved)); + const w = self.x.e.states.where(k.id); + if (k.at != s.reuse.at or k.at == 0 or k.at >= len or k.at % engine.prompt_rows != 0 or w == null or w.?.slot != slot) { + s.reuse_failed = true; + s.reuse_error = if (k.at == 0 or k.at >= len) error.SnapshotNotPrefix else if (k.at != s.reuse.at or k.at % engine.prompt_rows != 0) error.SnapshotOutOfStep else error.SnapshotStale; + return null; + } + s.cached = k.at; + return k.*; + } + + /// The prompt pass stands at `at` (a chunk start): the store keeps the state there when it marked it. + fn mark(s: *lanes.Stream, at: usize) void { + if (at == 0) return; + const hook = s.reuse.hook orelse return; + if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) == null) return; + hook.at(hook.ptr, s, @intCast(at)); + } + + fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + const self = of(ptr); + const from = try self.opening(s); + var at: usize = if (from) |r| r.at else 0; + var resume_id: ?u64 = if (from) |r| r.id else null; + const keeps = !self.lanes.getPtr(s).?.pictures; + while (true) : (at += engine.prompt_rows) { + if (resume_id == null and keeps) mark(s, at); + if (try self.x.chunk(s.prompt(), at, resume_id, .{ .ptr = s, .check = cancelled })) |first| { + self.lanes.getPtr(s).?.first = self.take(first); + return; + } + resume_id = null; + } + } + + /// One chunk of the stream's prompt pass (other rounds run between); true once the first token is drawn. + fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const self = of(ptr); + const going: ?usize = if (self.lanes.getPtr(s)) |l| l.fill else null; + const from = if (going == null) try self.opening(s) else null; + const l = self.lanes.getPtr(s).?; + if (going != null) try self.x.bind(l.slot); + const at = going orelse if (from) |r| r.at else 0; + errdefer l.fill = null; + if (from == null and !l.pictures) mark(s, at); + if (try self.x.chunk(s.prompt(), at, if (from) |r| r.id else null, .{ .ptr = s, .check = cancelled })) |first| { + l.first = self.take(first); + l.fill = null; + return true; + } + l.fill = at + engine.prompt_rows; + return false; + } + + fn cancelPrefillFn(ptr: *anyopaque, s: *lanes.Stream) !void { + const l = of(ptr).lanes.getPtr(s) orelse return; + l.fill = null; + } + + fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + if (position != s.prompt_len) return error.PositionMismatch; + const l = of(ptr).lanes.getPtr(s) orelse return error.UnknownStream; + return l.first orelse error.NoFirstToken; + } + + fn queueFn(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + _ = ptr; + _ = s; + _ = feed; + _ = position; + return error.NotPipelined; + } + + fn readFn(ptr: *anyopaque, handle: u64) anyerror!u32 { + const self = of(ptr); + if (handle >= self.next or self.next - handle > ring) return error.NoSuchToken; + return self.drawn[handle % ring]; + } + + /// A round's one-row windows in one forward (Engine.verifyShared), one stream or several. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const self = of(ptr); + if (windows.len > engine.max_shared) return error.WindowTooWide; + var parts: [engine.max_shared]engine.Part = undefined; + var ids: [engine.max_shared][max_rows]u32 = undefined; + var sampled: [engine.max_shared][max_rows]u32 = undefined; + for (windows, 0..) |w, k| { + if (w.parents != null) return error.TreesNotBuilt; + if (w.masks.len > 0) return error.Inkling2NoGrammar; + const l = try self.bind(w.stream); + if (w.held > 0) return error.NoHeldDrafts; + const rows = w.rows(); + if (rows > max_rows) return error.WindowTooWide; + const pos = self.x.e.pos(); + for (w.positions, 0..) |p, r| if (p != pos + 1 + r) return error.PositionMismatch; + ids[k][0] = w.pending; + parts[k] = .{ .slot = l.slot, .ids = ids[k][0..rows], .out = sampled[k][0..rows] }; + } + try self.x.verifyShared(parts[0..windows.len]); + if (windows.len > 1) self.shared += 1; + for (out[0..windows.len], parts[0..windows.len]) |*o, p| @memcpy(o.sampled[0..p.ids.len], p.out); + } + + /// A one-row window is committed by its verify: the only path keeps its row. + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + _ = ptr; + for (windows, paths) |w, path| if (path.len != 1 or path[0] != 0 or w.rows() != 1) return error.TreesNotBuilt; + } + + /// No drafter runs here: rounds hold no drafts. + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + _ = ptr; + if (requests.len > 0) return error.NoDraftHead; + } + + /// The stream left the rounds: its slot is free (its rows stay for the states kept there). + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { + const self = of(ptr); + const kv = self.lanes.fetchRemove(s) orelse return; + self.x.release(kv.value.slot) catch |err| std.log.err("releasing slot {d}: {s}", .{ kv.value.slot, @errorName(err) }); + if (self.lanes.count() == 0) self.x.idle() catch |err| std.log.err("the other ranks' idle step: {s}", .{@errorName(err)}); + } +}; diff --git a/zig/src/families/inkling2/native.zig b/zig/src/families/inkling2/native.zig new file mode 100644 index 00000000000..7de8ea56d96 --- /dev/null +++ b/zig/src/families/inkling2/native.zig @@ -0,0 +1,269 @@ +//! Inkling 2 native CUDA at TP=2 (TF_INKLING2_RANK, TF_INKLING2_WORLD, NCCL_COMM_ID): rank 0 serves, rank 1 follows. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const core = @import("core"); +const cfg = @import("shape.zig"); +const admission = @import("admit.zig"); +const shard = @import("shard.zig"); +const engine = @import("engine.zig"); +const follow = @import("follow.zig"); +const ink_lanes = @import("lanes.zig"); +const pictures = @import("pictures.zig"); +const tower = @import("vision.zig"); + +pub const model_type = "inkling2"; +pub const formats: []const []const u8 = &.{"exl3"}; +/// The model's native window: no rope, so 1M is served as trained. +pub const default_context: i64 = 1048576; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = engine.prompt_rows; +/// Kept prompt states are taken where a prompt chunk starts. +pub const snap_grid: u32 = prompt_rows; +pub const window_rows: u32 = engine.window_rows; +pub const explains_open = true; + +/// The server's reading of this rank's room after its load (the budget streams are admitted by); null if unreadable. +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, + room: ?Room = null, + vision: ?pictures.Limits = null, // --vision on every rank: rank 0's tower, every rank's image rows +}; +/// A request's visual tokens in all unless --vision-image-tokens says otherwise. +pub const default_image_tokens: u32 = pictures.default_image_tokens; +/// The smallest room among the other ranks and whose it is. +pub const Peer = struct { bytes: u64, rank: usize }; + +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32 = 0, // every slot's caches are made by `reserve`, after admission + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + reserve: *const fn (*anyopaque, u32) anyerror!void, + peer_room: ?Peer = null, + target: *anyopaque, // the prompt cache keeps this rank group's states (snap_*) + vision: ?*pictures.Offer = null, // the server's image offer (rank 0's processor and limits) +}; + +/// The tower's bytes on this rank: rank 0 holds it, its tensors plus scratch for a picture at the cap. +pub fn visionBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, _: u32, _: u32) !u64 { + const p = admission.place() catch return 0; + if (p.rank != 0) return 0; + const c = try cfg.Config.read(a, io, dir); + return tower.Tower.bytesFor(a, io, dir, c.vision, pictures.picture_tokens); +} + +/// The text shards' bytes (vision.safetensors is counted beside them; a drafter's mtp.safetensors is not loaded). +pub fn tensorWeightBytes(a: std.mem.Allocator, io: std.Io, dir: []const u8, vision: bool) !u64 { + _ = vision; + const files = try core.checkpoint.shardFiles(a, io, dir); + defer core.checkpoint.freeShardFiles(a, files); + var total: u64 = 0; + for (files) |f| { + const name = std.fs.path.basename(f); + if (std.mem.indexOf(u8, name, "vision") != null or std.mem.indexOf(u8, name, "mtp") != null) continue; + total += (try std.Io.Dir.cwd().statFile(io, f, .{})).size; + } + return total; +} + +/// Bytes this rank's weights take: half the split tensors, the embedding and the routers whole. +pub fn weightShare(a: std.mem.Allocator, io: std.Io, dir: []const u8, total: u64, drafts: bool, _: u32, _: u32) u64 { + _ = drafts; + const p = admission.place() catch return total; + if (p.world == 1) return total; + const c = cfg.Config.read(a, io, dir) catch return total; + const whole = @as(u64, c.vocab) * c.hidden * 2 + @as(u64, c.layers) * (@as(u64, c.experts) * c.hidden * 2 + c.experts * 4); + if (total < whole) return total; + return (total - whole) / p.world + whole; +} + +/// Positions a stream holds: `context` plus a window, in whole 64-key tiles. +pub fn capacity(context: usize) usize { + return std.mem.alignForward(usize, context + engine.window_rows, 64); +} + +const Owned = struct { + gpa: std.mem.Allocator, + lib: ?cuda.nccl.Library = null, + comm: cuda.nccl.Comm = null, + group: ?cuda.tp_group.Group = null, // lib and comm (owned above) with RoCE writes for two ranks' small gathers + e: *engine.Engine, + link: ?follow.Link = null, + lanes: ink_lanes.Lanes, + offer: ?*pictures.Offer = null, +}; + +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + _ = kernels; + try @import("sys").environment.checkScope(.inkling2, @import("sys").environment.Process{}); + const p = try admission.place(); + try admission.check(ctx, p.world); + if (std.c.getenv("NCCL_COMM_ID") == null) return error.NoCommId; + try cuda.tp_watch.start(io, p.rank, p.world); + return openRank(gpa, io, ctx, dir, o, p) catch |err| { + cuda.tp_watch.fail(@errorName(err)); + return err; + }; +} + +fn openRank(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, o: Options, p: admission.Place) !Loaded { + var load_cache = core.checkpoint.cache.Load.begin(io, true); + defer load_cache.deinit(); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + own.* = .{ .gpa = gpa, .e = undefined, .lanes = undefined }; + var lib = try cuda.nccl.Library.open(); + errdefer lib.close(); + var id: cuda.nccl.UniqueId = undefined; + if (p.rank == 0) { + try lib.check(lib.api.ncclGetUniqueId(&id), "ncclGetUniqueId"); + cuda.tp_watch.sendId(&id.internal); + } else id.internal = try cuda.tp_watch.takeId(io); + var comm: cuda.nccl.Comm = null; + try lib.check(lib.api.ncclCommInitRank(&comm, @intCast(p.world), id, @intCast(p.rank)), "ncclCommInitRank"); + own.lib = lib; + own.comm = comm; + errdefer _ = own.lib.?.api.ncclCommDestroy(own.comm); + const cap = capacity(o.context); + const lim: ?pictures.Limits = if (o.vision) |v| .{ .image_tokens = v.image_tokens, .max_images = @min(v.max_images, 64) } else null; + own.e = try engine.Engine.init(gpa, io, ctx.d, dir, p.rank, p.world, .{ .capacity = cap, .vision = lim }); + errdefer own.e.deinit(); + own.link = try follow.Link.init(gpa, ctx.d, &own.lib.?, own.comm, own.e.stream, @max(cap, engine.prompt_rows)); + errdefer own.link.?.deinit(); + // gathers up to a prompt call's partial by RoCE writes, both ranks or neither (TF_ROCE=0: NCCL); plan word on NCCL + own.group = .{ .lib = own.lib.?, .comm = own.comm, .rank = p.rank, .world = p.world }; + try own.group.?.openRoce(gpa, io, ctx.d, own.e.stream, own.e.roceBytes()); + errdefer if (own.group.?.fast) |f| f.deinit(); + own.e.exchange = .{ .nccl = .{ .lib = &own.lib.?, .comm = own.comm, .group = &own.group.? } }; + try load_cache.finishAfter(.{ io, own.e.checkpoint_digest }, cuda.tp_watch.ready); + // rank 0 admits by the smallest room of the ranks + var peer: ?Peer = null; + { + const mine: u64 = if (o.room) |r| r.read(r.ctx) orelse 0 else std.math.maxInt(u64); + var rooms = try cuda.DeviceBuffer.alloc(ctx.d, 8 * p.world); + defer rooms.free(); + try rooms.upload(p.rank * 8, std.mem.asBytes(&mine)); + try own.lib.?.check(own.lib.?.api.ncclAllGather(rooms.ptr + p.rank * 8, rooms.ptr, 8, .u8, own.comm, own.e.stream.handle), "ncclAllGather"); + try own.e.stream.synchronize(); + var all: [2]u64 = undefined; + try rooms.download(0, std.mem.sliceAsBytes(all[0..p.world])); + for (all[1..p.world], 1..) |r, q| if (peer == null or r < peer.?.bytes) { + peer = .{ .bytes = r, .rank = q }; + }; + } + if (p.rank != 0) { + follow.follow(own.e, &own.link.?) catch |err| { + std.log.err("rank {d}: following rank 0 stopped ({s})", .{ p.rank, @errorName(err) }); + cuda.tp_watch.fail(@errorName(err)); + std.c._exit(1); + }; + cuda.tp_watch.ended(); + std.log.info("rank {d}: rank 0 ended; leaving", .{p.rank}); + release(own); + std.process.exit(0); + } + own.link.?.asleep = cuda.tp_watch.open(); + own.lanes = .{ .x = .{ .e = own.e, .link = &own.link.? } }; + if (lim) |l| own.offer = try pictures.Offer.init(gpa, io, l); + return .{ + .backend = own.lanes.backend(), + .facts = own.lanes.facts(), + .rows = ink_lanes.max_rows, + .stream_bytes = own.e.seqBytes(), + .ctx = own, + .deinit = close, + .reserve = reserveFn, + .peer_room = peer, + .target = own, + .vision = own.offer, + }; +} + +/// The host's admitted stream count: every rank's slots made at once. +fn reserveFn(ptr: *anyopaque, streams: u32) anyerror!void { + const own: *Owned = @ptrCast(@alignCast(ptr)); + try own.lanes.x.reserve(streams); +} + +/// A state kept at `at`: its bytes on this rank (rings and conv states; the global rows stay in their slot). +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + _ = at; + const own: *Owned = @ptrCast(@alignCast(ptr)); + return own.e.stateBytes(); +} + +/// The prompt pass stands at `at` (a mark at a chunk start): every rank copies the state there under one new id. +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + _ = owner; + const own: *Owned = @ptrCast(@alignCast(ptr)); + if (own.e.pos() != at) return error.NotAtMark; + const k = try own.gpa.create(follow.Kept); + errdefer own.gpa.destroy(k); + k.* = try own.lanes.x.save(at); + return k; +} + +/// A restore outside a prompt pass would leave the other rank behind: states resume inside it (Lanes.resumeFrom). +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + _ = ptr; + _ = owner; + _ = saved; + return error.RestoredInPromptPass; +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(ptr)); + const k: *follow.Kept = @ptrCast(@alignCast(saved)); + own.lanes.x.drop(k.id); + own.gpa.destroy(k); +} + +fn close(ptr: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(ptr)); + cuda.tp_watch.ended(); + own.lanes.x.end() catch {}; + own.lanes.deinit(); + release(own); +} + +fn release(own: *Owned) void { + if (own.offer) |v| v.deinit(); + if (own.link) |*l| l.deinit(); + own.e.deinit(); + if (own.group) |*g| if (g.fast) |f| f.deinit(); + if (own.lib) |*lib| { + _ = lib.api.ncclCommDestroy(own.comm); + lib.close(); + } + own.gpa.destroy(own); +} + +/// The server's words for this family's refusals. +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return admission.explain(err) orelse switch (err) { + error.NoCommId => "Inkling 2's ranks meet over NCCL: set NCCL_COMM_ID to rank 0's address:port on both hosts", + error.UnexpectedInkling2Tensor => "a tensor is not stored as the Inkling 2 EXL3 pack stores it (the log names it)", + error.NotExl3 => "Inkling 2 on CUDA reads EXL3 packs: config.json needs a quantization_config with quant_method exl3", + error.UnsupportedExl3 => "this EXL3 pack is not from exllamav3 1.x on the mul1 codebook, the only form validated here", + error.NoVision => "images need --vision on both ranks (rank 0 runs the tower from the pack's vision.safetensors)", + error.ImagePlaceholders => "the prompt's image placeholders do not match its pictures", + error.ImageTooLarge => pictures.Offer.explain(error.ImageTooLarge).?, + else => null, + }; +} + +test "native: refusals explain themselves; a stream's capacity holds the context and a window in whole tiles" { + try std.testing.expect(explain(null, error.Inkling2RequiresSm121) != null); + try std.testing.expect(explain(null, error.Inkling2RequiresTwoRanks) != null); + try std.testing.expect(explain(null, error.NoCommId) != null); + try std.testing.expectEqual(@as(usize, 1048576 + 64), capacity(1048576)); + try std.testing.expectEqual(@as(usize, 131072 + 64), capacity(131072)); +} diff --git a/zig/src/families/inkling2/pictures.zig b/zig/src/families/inkling2/pictures.zig new file mode 100644 index 00000000000..863461371d1 --- /dev/null +++ b/zig/src/families/inkling2/pictures.zig @@ -0,0 +1,173 @@ +//! Served pictures: the server's image offer, each slot's image rows and spans, the rows' trip to every rank. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const image = @import("image.zig"); +const vision = @import("vision.zig"); + +/// Visual tokens one picture may take: 2560 x 2560 pixels (the processor never resizes, so larger ones are refused). +pub const picture_tokens: u32 = 4096; +/// A request's visual tokens in all unless --vision-image-tokens says otherwise (one picture at the cap). +pub const default_image_tokens: u32 = 4096; +/// The chat template's tokens around an image: `<|content_image|>`, the placeholder, `<|end_message|>`. +pub const content_image: u32 = 200005; +pub const end_message: u32 = 200010; + +/// A request's image limits (--vision): visual tokens in all and pictures. +pub const Limits = struct { image_tokens: u32, max_images: u32 }; + +/// What rank 0 offers the server: the processor, the template's tokens, the limits. +pub const Offer = struct { + gpa: std.mem.Allocator, + io: std.Io, + limits: Limits, + marks: struct { image: u32, open: u32, close: u32 } = .{ .image = image.image_token, .open = content_image, .close = end_message }, + mark_ids: [3]u32 = .{ content_image, image.image_token, end_message }, + + /// The template writes `<|content_image|>` and `<|end_message|>` itself: the server expands the placeholder alone. + pub const template_wraps = true; + + pub fn init(gpa: std.mem.Allocator, io: std.Io, limits: Limits) !*Offer { + const v = try gpa.create(Offer); + v.* = .{ .gpa = gpa, .io = io, .limits = limits }; + return v; + } + + pub fn deinit(v: *Offer) void { + v.gpa.destroy(v); + } + + /// The server's processor (on the HTTP thread): one token per 40 x 40 cell, refused past the cap or the budget. + pub fn prepare(v: *const Offer, a: std.mem.Allocator, bytes: []const u8, max: u32) !Prepared { + const cap = @min(max, picture_tokens); + if (cap == 0) return error.ImageTooSmall; + const p = try image.prepare(v.io, a, bytes, cap); + const g = [2]u32{ p.rows, p.cols }; + return .{ .pixels = p.pixels, .gh = p.rows, .gw = p.cols, .tokens = p.tokens(), .hash = core.picture.identity.withGrid(core.picture.identity.ofBytes(0x1a2b, bytes), g) }; + } + + pub fn explain(err: anyerror) ?[]const u8 { + return switch (err) { + error.ImageTooLarge => "too large: Inkling 2 reads one visual token per 40 x 40 pixels with no resize, at most 4096 a " ++ + "picture (2560 x 2560) and the request's --vision-image-tokens shared by its pictures; send it smaller", + else => image.explain(err), + }; + } +}; + +/// prepare's answer, in the fields the server's offer reads. +pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +/// One slot's pictures for its prompt pass: their rows (bf16 [tokens][hidden]) and where they go. +pub const Rows = struct { + buf: cuda.DeviceBuffer, + spans: std.ArrayList(vision.Span) = .empty, +}; + +/// Bytes a slot's image rows take at a request's limit. +pub fn slotBytes(l: Limits, hidden: usize) u64 { + return @as(u64, l.image_tokens) * hidden * 2; +} + +/// Every slot's rows buffer, made with the slots. +pub fn makeRows(gpa: std.mem.Allocator, d: *const cuda.Driver, l: Limits, slots: usize, hidden: usize) ![]Rows { + const rows = try gpa.alloc(Rows, slots); + var made: usize = 0; + errdefer { + for (rows[0..made]) |*r| r.buf.free(); + gpa.free(rows); + } + for (rows) |*r| { + r.* = .{ .buf = try cuda.DeviceBuffer.alloc(d, slotBytes(l, hidden)) }; + made += 1; + } + return rows; +} + +pub fn freeRows(gpa: std.mem.Allocator, rows: []Rows) void { + for (rows) |*r| { + r.buf.free(); + r.spans.deinit(gpa); + } + gpa.free(rows); +} + +/// The request's pictures as the tower reads them, and their spans: each at its first placeholder, rows in order. +pub fn fromRequest(a: std.mem.Allocator, ids: []const u32, imgs: anytype, pics: []image.Prepared) ![]vision.Span { + if (imgs.len > pics.len) return error.ImageCount; + const list = try vision.spans(a, ids); + errdefer a.free(list); + if (list.len != imgs.len) return error.ImagePlaceholders; + for (imgs, pics[0..imgs.len], list) |im, *p, sp| { + if (im.at != sp.at or im.tokens != sp.n or im.tokens != im.gh * im.gw) return error.ImagePlaceholders; + p.* = .{ .pixels = @constCast(im.pixels), .rows = im.gh, .cols = im.gw }; + } + try vision.check(list, pics[0..imgs.len]); + return list; +} + +/// Spans checked against a slot's rows (a follower's step, or rank 0's before it goes out): rows in order, in room. +pub fn checkSpans(list: []const vision.Span, l: Limits) !u32 { + var row: u32 = 0; + var end: u32 = 0; + for (list) |sp| { + if (sp.n == 0 or sp.row != row or sp.at < end) return error.ImagePlaceholders; + row += sp.n; + end = sp.at + sp.n; + } + if (row > l.image_tokens or list.len > l.max_images) return error.ImageTooLarge; + return row; +} + +/// Spans as a step's words (at, n, row each) and back. +pub fn toWords(list: []const vision.Span, out: []u32) ![]u32 { + if (out.len < 3 * list.len) return error.TooManyImages; + for (list, 0..) |sp, i| out[3 * i ..][0..3].* = .{ sp.at, sp.n, sp.row }; + return out[0 .. 3 * list.len]; +} + +pub fn fromWords(words: []const u32, out: []vision.Span) ![]vision.Span { + if (words.len % 3 != 0 or words.len / 3 > out.len) return error.BadStep; + for (out[0 .. words.len / 3], 0..) |*sp, i| sp.* = .{ .at = words[3 * i], .n = words[3 * i + 1], .row = words[3 * i + 2] }; + return out[0 .. words.len / 3]; +} + +test "spans cross as words and back; a slot's spans are checked against its limits" { + const list = [_]vision.Span{ .{ .at = 3, .n = 15, .row = 0 }, .{ .at = 40, .n = 4, .row = 15 } }; + var w: [6]u32 = undefined; + var back: [4]vision.Span = undefined; + const got = try fromWords(try toWords(&list, &w), &back); + try std.testing.expectEqualSlices(vision.Span, &list, got); + try std.testing.expectEqual(@as(u32, 19), try checkSpans(&list, .{ .image_tokens = 19, .max_images = 2 })); + try std.testing.expectError(error.ImageTooLarge, checkSpans(&list, .{ .image_tokens = 18, .max_images = 2 })); + try std.testing.expectError(error.ImageTooLarge, checkSpans(&list, .{ .image_tokens = 64, .max_images = 1 })); + const gap = [_]vision.Span{.{ .at = 3, .n = 15, .row = 1 }}; + try std.testing.expectError(error.ImagePlaceholders, checkSpans(&gap, .{ .image_tokens = 64, .max_images = 2 })); + try std.testing.expectError(error.BadStep, fromWords(w[0..5], &back)); +} + +test "a request's pictures map to their placeholder runs; a count or place that differs is refused" { + const a = std.testing.allocator; + const t = image.image_token; + const Img = struct { pixels: []const f32, gh: u32, gw: u32, at: u32, tokens: u32 }; + var px: [6 * image.side * image.side * 3]f32 = undefined; + const ids = [_]u32{ 9, content_image, t, t, t, t, end_message, 5, content_image, t, t, end_message }; + var pics: [4]image.Prepared = undefined; + const two = [_]Img{ .{ .pixels = px[0..], .gh = 2, .gw = 2, .at = 2, .tokens = 4 }, .{ .pixels = px[0..], .gh = 1, .gw = 2, .at = 9, .tokens = 2 } }; + const got = try fromRequest(a, &ids, &two, &pics); + defer a.free(got); + try std.testing.expectEqual(vision.Span{ .at = 9, .n = 2, .row = 4 }, got[1]); + try std.testing.expectEqual(@as(u32, 2), pics[1].cols); + const moved = [_]Img{ two[0], .{ .pixels = px[0..], .gh = 1, .gw = 2, .at = 8, .tokens = 2 } }; + try std.testing.expectError(error.ImagePlaceholders, fromRequest(a, &ids, &moved, &pics)); + try std.testing.expectError(error.ImagePlaceholders, fromRequest(a, &ids, two[0..1], &pics)); +} + +test "the cap: a picture past 4096 tokens is refused with words naming the limit; the slot rows fit the default" { + try std.testing.expect(image.tokensFor(2560, 2560) == picture_tokens); + try std.testing.expect(image.tokensFor(2561, 2560) > picture_tokens); + try std.testing.expect(std.mem.indexOf(u8, Offer.explain(error.ImageTooLarge).?, "4096") != null); + try std.testing.expectEqual(@as(u64, 4096 * 4608 * 2), slotBytes(.{ .image_tokens = default_image_tokens, .max_images = 4 }, 4608)); + const c = try @import("shape.zig").parse(std.testing.allocator, @embedFile("fixtures/config.json")); + try std.testing.expect(vision.scratchBytes(c.vision, picture_tokens) < 1 << 30); +} diff --git a/zig/src/families/inkling2/prompt_dense.zig b/zig/src/families/inkling2/prompt_dense.zig new file mode 100644 index 00000000000..07343714026 --- /dev/null +++ b/zig/src/families/inkling2/prompt_dense.zig @@ -0,0 +1,110 @@ +//! Prompt rows' dense EXL3 projections (exl3.md, Prompts): W decoded once into fp16, a cuBLASLt GEMM, the rotation. +const std = @import("std"); +const cuda = @import("cuda"); + +const lt_ = cuda.cublaslt; +const Buf = cuda.DeviceBuffer; + +/// Calls of fewer rows keep exl3.Dense (decode rows, short prompts: the same bits as decode). +pub const min_rows = 256; +const workspace_bytes = 32 << 20; + +const Plan = struct { rows: usize, k: usize, n: usize, g: lt_.Gemm }; + +pub const Prompt = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + lt: lt_.Library, + handle: lt_.Handle, + mod: cuda.Module, + rotate: cuda.Function, + unpack: cuda.Function, + tail: cuda.Function, + xh: Buf, // fp16 [rows][k]: (x * suh) H 2^-4 + w: Buf, // fp16 [k][n]: W_q in the rotated domain + z: Buf, // fp32 [rows][n]: the GEMM's sums + ws: Buf, + plans: std.ArrayList(Plan) = .empty, + rows_max: usize, + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, tail: cuda.Function, rows_max: usize, k_max: usize, n_max: usize) !Prompt { + var lt = try lt_.Library.open(); + errdefer lt.close(); + const handle = try lt_.createHandle(<); + errdefer _ = lt.api.cublasLtDestroy(handle); + var mod = try cuda.Module.load(d, cuda.kernels.exl3_candidate); + errdefer mod.unload(); + var xh = try Buf.alloc(d, rows_max * k_max * 2); + errdefer xh.free(); + var w = try Buf.alloc(d, k_max * n_max * 2); + errdefer w.free(); + var z = try Buf.alloc(d, rows_max * n_max * 4); + errdefer z.free(); + const ws = try Buf.alloc(d, workspace_bytes); + return .{ .gpa = gpa, .d = d, .lt = lt, .handle = handle, .mod = mod, .rotate = try mod.function("tf_exl3_rotate_h"), .unpack = try mod.function("tf_exl3_unpack"), .tail = tail, .xh = xh, .w = w, .z = z, .ws = ws, .rows_max = rows_max }; + } + + /// Scratch for the widest attention projection of `layers` at `rows` rows. + pub fn of(gpa: std.mem.Allocator, d: *const cuda.Driver, tail: cuda.Function, rows: usize, layers: anytype) !Prompt { + var k: usize = 0; + var n: usize = 0; + for (layers) |l| for ([_]cuda.exl3.Weight{ l.attn.q, l.attn.k, l.attn.v, l.attn.r, l.attn.gate, l.attn.o }) |x| { + k = @max(k, x.k); + n = @max(n, x.n); + }; + return init(gpa, d, tail, rows, k, n); + } + + pub fn deinit(p: *Prompt) void { + for (p.plans.items) |*x| x.g.deinit(); + p.plans.deinit(p.gpa); + for ([_]*Buf{ &p.xh, &p.w, &p.z, &p.ws }) |b| b.free(); + p.mod.unload(); + _ = p.lt.api.cublasLtDestroy(p.handle); + p.lt.close(); + } + + /// Whether `w` takes this path: whole bits (the unpack's widths), no bias, the stored layout, within the scratch. + pub fn takes(p: *const Prompt, w: cuda.exl3.Weight, rows: usize) bool { + const st = cuda.exl3.strides(w.k, w.n, w.halves, false); + return rows >= min_rows and rows <= p.rows_max and w.halves % 2 == 0 and w.halves <= 16 and w.bias == 0 and + w.stride_k == st.k and w.stride_nb == st.nb and @as(usize, w.k) * 2 * rows <= p.xh.len and + @as(usize, w.k) * w.n * 2 <= p.w.len and rows * w.n * 4 <= p.z.len; + } + + fn plan(p: *Prompt, rows: usize, k: usize, n: usize) !*const lt_.Gemm { + for (p.plans.items) |*x| if (x.rows == rows and x.k == k and x.n == n) return &x.g; + // column-major: Z^T [n, rows] = W^T [n, k] . Xh^T [k, rows] + const g = try lt_.Gemm.init(&p.lt, p.handle, .{ .m = n, .n = rows, .k = k, .a = .f16, .b = .f16, .c = .f32, .lda = n, .ldb = k, .ldc = n }, workspace_bytes); + try p.plans.append(p.gpa, .{ .rows = rows, .k = k, .n = n, .g = g }); + return &p.plans.items[p.plans.items.len - 1].g; + } + + /// y [rows][n] (bf16 or fp32) = x [rows][k] (bf16) through `w`, on `s`. + pub fn run(p: *Prompt, s: cuda.Stream, w: cuda.exl3.Weight, x: u64, rows: usize, y: u64, y_f32: bool) !void { + const g = try p.plan(rows, w.k, w.n); + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(u32, w.k)); + a.add(w.suh); + a.add(p.xh.ptr); + a.add(@as(u32, w.k)); + try cuda.launch.launch(p.rotate, .{ .grid = .{ .x = w.k / 128, .y = @intCast(rows) }, .block = .{ .x = 32 } }, s, &a); + var b: cuda.Args = .{}; + b.add(w.trellis); + b.add(MatrixArgs{ .k = w.k, .n = w.n, .bits = w.halves / 2, .tiles_n = w.n / 16, .split = 1 }); + b.add(@as(u32, @backingInt(w.codebook))); + b.add(p.w.ptr); + try cuda.launch.launch(p.unpack, .{ .grid = .{ .x = w.n / 16, .y = w.k / 16 }, .block = .{ .x = 32 } }, s, &b); + try g.run(1.0, p.w.ptr, p.xh.ptr, 0.0, p.z.ptr, p.ws.ptr, p.ws.len, s.handle); + var c: cuda.Args = .{}; + for ([_]u64{ p.z.ptr, w.svh }) |v| c.add(v); + c.add(@as(u32, w.n)); + c.add(y); + c.add(@as(u32, @intFromBool(y_f32))); + try cuda.launch.launch(p.tail, .{ .grid = .{ .x = w.n / 128, .y = @intCast(rows) }, .block = .{ .x = 32 } }, s, &c); + } +}; + +/// exl3_candidate.cu's TfExl3Matrix, by value. +const MatrixArgs = extern struct { k: u32, n: u32, bits: u32, tiles_n: u32, split: u32 }; diff --git a/zig/src/families/inkling2/sampler.zig b/zig/src/families/inkling2/sampler.zig new file mode 100644 index 00000000000..7260d85dfce --- /dev/null +++ b/zig/src/families/inkling2/sampler.zig @@ -0,0 +1,107 @@ +//! Sampled draws on main's sample.cu: each rank's bf16 columns broadcast into whole rows, every rank draws the same. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const Span = @import("shard.zig").Span; +const Exchange = @import("forward.zig").Exchange; + +pub const Sampling = lanes.Sampling; + +/// The request's rule as the engine runs it: null (or temperature 0) decodes greedily. +pub fn check(s: ?Sampling) ?Sampling { + const x = s orelse return null; + return if (x.temperature > 0) x else null; +} + +pub const Rule = cuda.sample.Rule; + +pub fn rule(s: Sampling) Rule { + return cuda.sample.rule(s); +} + +pub const Sampler = struct { + d: *const cuda.Driver, + module: cuda.Module, + tf_draw: cuda.Function, + vocab: usize, // a whole row's columns: every rank's padded span + rows: usize, + full: cuda.DeviceBuffer, // bf16 [rows][vocab]: every rank's columns in place + rule: cuda.DeviceBuffer, + meta: cuda.DeviceBuffer, + tok: cuda.DeviceBuffer, + prob: cuda.DeviceBuffer, + + pub fn init(d: *const cuda.Driver, vocab: usize, rows: usize) !Sampler { + var m = try cuda.Module.load(d, cuda.kernels.sample); + errdefer m.unload(); + const f = try m.function("tf_draw"); + var full = try cuda.DeviceBuffer.alloc(d, rows * vocab * 2); + errdefer full.free(); + var r = try cuda.DeviceBuffer.alloc(d, @sizeOf(Rule)); + errdefer r.free(); + var meta = try cuda.DeviceBuffer.alloc(d, 16); + errdefer meta.free(); + var tok = try cuda.DeviceBuffer.alloc(d, rows * 4); + errdefer tok.free(); + const prob = try cuda.DeviceBuffer.alloc(d, rows * 4); + return .{ .d = d, .module = m, .tf_draw = f, .vocab = vocab, .rows = rows, .full = full, .rule = r, .meta = meta, .tok = tok, .prob = prob }; + } + + pub fn deinit(s: *Sampler) void { + s.prob.free(); + s.tok.free(); + s.meta.free(); + s.rule.free(); + s.full.free(); + s.module.unload(); + } + + /// `rows` rows of `full` (this rank's columns written) made whole, then drawn: tokens at first, first + 1, ... + pub fn draw(s: *Sampler, stream: cuda.Stream, exchange: Exchange, spans: []const Span, rows: usize, first: u64, r: Rule, out: []u32) !void { + std.debug.assert(rows <= s.rows and out.len >= rows and first >= 1); + switch (exchange) { + .local => {}, + .nccl => |x| try x.lib.group(Spread{ .lib = x.lib, .comm = x.comm, .stream = stream, .full = s.full.ptr, .vocab = s.vocab, .spans = spans, .rows = rows }, Spread.post), + } + try s.rule.uploadAsync(0, std.mem.asBytes(&r), stream.handle); + const meta = [4]i32{ @intCast(first - 1), 0, 0, 0 }; // row r keys meta[0] + r + 1 + try s.meta.uploadAsync(0, std.mem.asBytes(&meta), stream.handle); + var args: cuda.Args = .{}; + args.add(s.full.ptr); + args.add(@as(u32, @intCast(s.vocab))); + args.add(s.rule.ptr); + args.add(s.meta.ptr); + args.add(@as(i32, 0)); + args.add(s.tok.ptr); + args.add(s.prob.ptr); + try cuda.launch.launch(s.tf_draw, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 1024 } }, stream, &args); + try stream.synchronize(); + try s.tok.download(0, std.mem.sliceAsBytes(out[0..rows])); + } +}; + +/// Each rank's columns of each row from that rank, in one NCCL group. +const Spread = struct { + lib: *const cuda.nccl.Library, + comm: cuda.nccl.Comm, + stream: cuda.Stream, + full: u64, + vocab: usize, + spans: []const Span, + rows: usize, + + fn post(t: Spread) anyerror!void { + for (0..t.rows) |row| for (t.spans, 0..) |span, q| { + const at = t.full + (row * t.vocab + span.lo) * 2; + try t.lib.check(t.lib.api.ncclBroadcast(at, at, span.len(), .bf16, @intCast(q), t.comm, t.stream.handle), "ncclBroadcast"); + }; + } +}; + +test "sampler: temperature 0 is greedy, a sampled rule keeps its settings" { + const s: Sampling = .{ .seed = 1234, .temperature = 0.5, .top_k = 20, .top_p = 0.95 }; + const r = rule(check(s).?); + try std.testing.expectEqual(@as(f32, 2.0), r.inv_t); + try std.testing.expectEqual(@as(u32, 20), r.top_k); + try std.testing.expectEqual(@as(?Sampling, null), check(.{ .seed = 0, .temperature = 0 })); +} diff --git a/zig/src/families/inkling2/shape.zig b/zig/src/families/inkling2/shape.zig index ec90708b87f..1f455da2208 100644 --- a/zig/src/families/inkling2/shape.zig +++ b/zig/src/families/inkling2/shape.zig @@ -38,6 +38,7 @@ pub const Config = struct { eos: [4]u32 = .{ 200006, 0, 0, 0 }, eos_count: u32 = 1, layer: [max_layers]Kind = undefined, + vision: shared.Vision = undefined, // the tower's shape, for the image path pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); @@ -114,6 +115,7 @@ pub fn from(s: *const shared.Config) Error!Config { .context = t.max_context, .eos = .{ s.eos, 0, 0, 0 }, .eos_count = 1, + .vision = s.vision, }; for (c.layer[0..c.layers], 0..) |*k, i| k.* = if (shared.isGlobal(@intCast(i))) .global else .sliding; try validate(&c); diff --git a/zig/src/families/inkling2/tokenizer_fixture.json b/zig/src/families/inkling2/tokenizer_fixture.json new file mode 100644 index 00000000000..d7b88308fb0 --- /dev/null +++ b/zig/src/families/inkling2/tokenizer_fixture.json @@ -0,0 +1,66 @@ +{ + "tokenizer_class": "PreTrainedTokenizerFast", + "model_max_length": 1048576, + "added_tokens_decoder": { + "199999": { + "content": "<|endoftext|>", + "special": true + }, + "200000": { + "content": "<|message_user|>", + "special": true + }, + "200001": { + "content": "<|message_model|>", + "special": true + }, + "200002": { + "content": "<|message_system|>", + "special": true + }, + "200003": { + "content": "<|message_tool|>", + "special": true + }, + "200004": { + "content": "<|content_text|>", + "special": true + }, + "200005": { + "content": "<|content_image|>", + "special": true + }, + "200006": { + "content": "<|content_model_end_sampling|>", + "special": true + }, + "200008": { + "content": "<|content_thinking|>", + "special": true + }, + "200010": { + "content": "<|end_message|>", + "special": true + }, + "200022": { + "content": "<|content_tool_error|>", + "special": true + }, + "200024": { + "content": "<|content_xml|>", + "special": true + }, + "200049": { + "content": "<|content_invoke_tool_json|>", + "special": true + }, + "200054": { + "content": "<|unused_200054|>", + "special": true + }, + "200057": { + "content": "<|content_invoke_tool_text|>", + "special": true + } + } +} \ No newline at end of file diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index f63fa894ce6..02dae66f59c 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -15,7 +15,7 @@ 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, nemotron.transcribe, 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("ricursive_cuda").native, @import("lfm3_cuda").native, @import("lfm2_moe_cuda").native, inkling2.native }; +pub const registry = .{ nemotron.native, nemotron.omni, nemotron.transcribe, 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("ricursive_cuda").native, @import("lfm3_cuda").native, @import("lfm2_moe_cuda").native, inkling2.native, inkling2.native_exl3 }; pub const families: []const api.Family = blk: { var out: [registry.len + 6]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 &.{} }; @@ -32,8 +32,9 @@ 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 + 6), families.len); try std.testing.expectEqualStrings("nemotron_h", families[0].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("lfm2_moe", families[registry.len - 3].model_type); + try std.testing.expectEqualStrings("inkling2_loop", families[registry.len - 2].model_type); + try std.testing.expectEqualStrings("inkling2", 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); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index d9d10fb194f..11f233549e7 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -3,7 +3,7 @@ const std = @import("std"); const sys = @import("sys.zig"); pub const Error = error{InvalidEnvironment}; -pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext, nemotron, minimax_m3, chat, hub }; +pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext, nemotron, minimax_m3, chat, hub, inkling2 }; pub const Kind = enum { u32, u64, size, percent, positive, device, segments, mib, bit_width, word, prompt, flag, toggle, real, positive_real, signed_real, range, path, parallel, names }; /// The release from which the server refuses the rank aliases: the one after the release that first ships the flags. pub const alias_retire = "1.4.0"; @@ -180,6 +180,8 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_RANK", .scope = .glm, .kind = .u32, .forms = "a whole rank from 0", .flag = "--rank", .retire = alias_retire }, .{ .name = "TF_GLM_WORLD", .scope = .glm, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, .{ .name = "TF_MINIMAX_RANK", .scope = .minimax_m3, .kind = .u32, .forms = "a whole rank from 0", .flag = "--rank", .retire = alias_retire }, + .{ .name = "TF_INKLING2_RANK", .scope = .inkling2, .kind = .u32, .forms = "a whole rank index, 0 or 1 at two ranks (unset with TF_INKLING2_WORLD gives one rank)" }, + .{ .name = "TF_INKLING2_WORLD", .scope = .inkling2, .kind = .u32, .min = 1, .forms = "a whole rank count, 2 on CUDA (unset with TF_INKLING2_RANK gives one rank)" }, .{ .name = "TF_MINIMAX_WORLD", .scope = .minimax_m3, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, .{ .name = "TF_MINIMAX_GRAPHS", .scope = .minimax_m3, .kind = .flag, .forms = "0 or 1 (1 records one-stream decode verify windows as CUDA graphs; default 0)" }, .{ .name = "TF_NEMOTRON_RANK", .scope = .nemotron, .kind = .u32, .forms = "a whole rank from 0", .flag = "--rank", .retire = alias_retire }, diff --git a/zig/src/platform/environment_flags.zig b/zig/src/platform/environment_flags.zig index f7d87a74590..1e14dea8286 100644 --- a/zig/src/platform/environment_flags.zig +++ b/zig/src/platform/environment_flags.zig @@ -22,6 +22,7 @@ pub const Flags = struct { carveout: bool = false, /// --parallel named: TENSORFOLD_PARALLEL then stays out of the way, as a flag-named device does. parallel_named: bool = false, + inkling2: bool = false, pub fn includes(f: Flags, scope: Scope) bool { return switch (scope) { @@ -40,6 +41,7 @@ pub const Flags = struct { .minimax_m3 => f.minimax_m3, .chat => f.chat, .hub => f.hub, + .inkling2 => f.inkling2, }; } diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 2769daf72f9..f26dba122db 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -3,7 +3,7 @@ const std = @import("std"); const e = @import("environment.zig"); const t = std.testing; const a = t.allocator; -const all: e.Flags = .{ .cuda = true, .metal = true, .xpu = true, .slide = true, .hooks = true, .dsv41 = true, .gemma4 = true, .drama3 = true, .glm = true, .flashnext = true, .nemotron = true, .minimax_m3 = true, .chat = true, .hub = true }; +const all: e.Flags = .{ .cuda = true, .metal = true, .xpu = true, .slide = true, .hooks = true, .dsv41 = true, .gemma4 = true, .drama3 = true, .glm = true, .flashnext = true, .nemotron = true, .minimax_m3 = true, .chat = true, .hub = true, .inkling2 = true }; const Env = struct { name: []const u8, raw: ?[]const u8, @@ -136,6 +136,8 @@ const valid = [_]Case{ .{ .name = "TENSORFOLD_LFM3_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "TF_ROCE_GID_INDEX", .raw = "2147483647", .n = 2147483647 }, .{ .name = "TF_MINIMAX_RANK", .raw = "1", .n = 1 }, + .{ .name = "TF_INKLING2_RANK", .raw = "1", .n = 1 }, + .{ .name = "TF_INKLING2_WORLD", .raw = "2", .n = 2 }, .{ .name = "TF_MINIMAX_WORLD", .raw = "2", .n = 2 }, .{ .name = "TF_MINIMAX_GRAPHS", .raw = "0", .n = 0 }, .{ .name = "TF_MINIMAX_GRAPHS", .raw = "1", .n = 1 }, From c6b04d08e9b9e67d295d78987f465902d44177f9 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 07:47:41 +1100 Subject: [PATCH 22/27] docs: add the Inkling 2 Small CUDA recipe page --- docs/recipes/README.md | 1 + docs/recipes/inkling-2-small-cuda.md | 52 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 docs/recipes/inkling-2-small-cuda.md diff --git a/docs/recipes/README.md b/docs/recipes/README.md index 69e6082ca85..cb95f8757ec 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -36,6 +36,7 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Recursive Flint | [Native Metal, the publisher's affine 4-bit export, reasoning and tool calls](flint.md) | | Unlimited-OCR-2 | [Native Metal, the bf16 release: page images to structured text, 131k context](unlimited-ocr-metal.md) | | Muse Spark Open | [EXL3 on CUDA, two-rank DGX Spark, plain decode](muse-spark.md) | +| Inkling 2 Small | [EXL3 on CUDA, two-rank DGX Spark, images, plain decode](inkling-2-small-cuda.md) | | Ripple-65B-Preview | [Native CUDA, the publisher's NVFP4 release](ripple-65b-cuda.md), [native Metal, the publisher's NVFP4 and bf16 releases](ripple-65b-metal.md) | | Ling-3.0-tiny | [Native CPU on aarch64 Linux, the Q4_K_M GGUF, exact greedy decode from token IDs](ling-3.0-tiny-cpu.md) | | SenseNova-Loop-9B | [Native Metal, BF16 and AWQ g128, 512k context, MTP drafts, images](sensenova-loop-9b.md) | diff --git a/docs/recipes/inkling-2-small-cuda.md b/docs/recipes/inkling-2-small-cuda.md new file mode 100644 index 00000000000..f2e22f13c35 --- /dev/null +++ b/docs/recipes/inkling-2-small-cuda.md @@ -0,0 +1,52 @@ +# Inkling 2 Small on CUDA + +The `inkling2` family serves a standard exllamav3 EXL3 pack of Thinking Machines' Inkling 2 Small on the native CUDA +server, on two DGX Sparks (GB10, sm_121) as tensor-parallel ranks. Package: `zig/src/families/inkling2/`, kernels in +`zig/kernels/cuda/inkling2/`. It reads the pack exllamav3 writes (`config.json` with `quantization_config`, an index +and shards), so any exllamav3 1.x pack of the model on the `mul1` codebook loads. + +## The model + +- 48 layers of hidden size 4,608: 40 sliding-window layers (1,024 keys) and 8 global layers, no RoPE. The global + layers keep every key, so the served window is the model's own 1,048,576 tokens. +- Attention: 48 query heads and 8 key heads of 128, a learned relative-position bias, sinks and a sigmoid output gate. + Short convolutions sit on the keys, the values and both residual branches. +- MoE: 384 routed experts, 8 a token, softcapped SwiGLU. +- A vision tower (`vision.safetensors` beside the pack) turns pictures into rows that replace the image placeholders. + +## Checkpoint + +| | Repository | Revision | +|---|---|---| +| Pack (EXL3 mul1, 2.2 bpw, head 8 bits) | `ajensenwaud/inkspark-2dgx` | `aa29f3a011b011896826416f03b8ac55d7ec7c6f` | +| Source | `thinkingmachines/Inkling-2-Small` | `aac974122acd33ddb0d3e1f54433a9c5dd2249ce` | + +## Files + +| File | What it does | +|---|---| +| `exl3.zig`, `pack_weights.zig`, `shard.zig`, `shape.zig` | The pack's reader: EXL3 projections, grouped experts, the head, each cut to its rank | +| `forward.zig`, `prompt_dense.zig` | A call's rows through every layer: decode rows of several streams, or a prompt chunk | +| `engine.zig`, `kept.zig`, `sampler.zig` | One rank's engine: slots, graphed decode rows, prompt chunks, kept prompt states, draws | +| `follow.zig`, `lanes.zig`, `native.zig`, `admit.zig` | Rank 0 serves and sends each step to rank 1; the lanes backend behind `serve` | +| `pictures.zig` | The server's image offer and each slot's image rows on every rank | +| `engine_main.zig` | `tf-inkling2-engine`: graph replay against eager rows, and greedy decode, on two ranks | + +A row's bits do not depend on the other streams in its forward, the graph or how its prompt is cut into chunks, so +graphed decode equals eager decode and a resumed prompt equals a fresh one. + +## Serving + +Both hosts run the server with the same flags; rank 0 answers the API. + +```bash +# on each host, RANK 0 on the head and 1 on the worker +TF_INKLING2_RANK=$RANK TF_INKLING2_WORLD=2 NCCL_COMM_ID=: TF_ROCE=1 \ + tensorfold-native serve /model --name Inkling-2-Small --context 1048576 --parallel 1 --vision --no-drafts +``` + +`--context 131072 --parallel 4` gives four streams of 128K. The KV cache is bf16. The bundled DSpark drafter +(`mtp.safetensors`) is not read yet, so every stream decodes one token a step. + +The family refuses any other setup by name: one rank, a GPU other than GB10, another codebook or exllamav3 version, +and a pack whose tensors differ from what the reader expects. From 65ded7954646e3284eb0e82ac0e23cfceca7c327 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 23:31:03 +1100 Subject: [PATCH 23/27] inkling2: choose a stream's slot before publishing its lane The new map entry went in before pick scanned the lanes, so the scan read the entry's unset slot, and a failed pick left the entry behind. The slot is now chosen first and the entry added only once it has one. --- zig/src/families/inkling2/lanes.zig | 44 ++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/zig/src/families/inkling2/lanes.zig b/zig/src/families/inkling2/lanes.zig index 435da0a3aae..389fa95aba1 100644 --- a/zig/src/families/inkling2/lanes.zig +++ b/zig/src/families/inkling2/lanes.zig @@ -20,9 +20,20 @@ const Lane = struct { pictures: bool = false, // an image prompt: never resumed from or kept in the prompt cache }; +const Map = std.AutoHashMapUnmanaged(*const lanes.Stream, Lane); + +/// The stream's lane, a new one published only once `chooser.pick` gave its slot: a failed choice leaves no entry. +fn claim(map: *Map, gpa: std.mem.Allocator, s: *const lanes.Stream, chooser: anytype) !*Lane { + if (map.getPtr(s)) |l| return l; + const slot = try chooser.pick(s); + const gop = try map.getOrPut(gpa, s); + gop.value_ptr.* = .{ .slot = slot }; + return gop.value_ptr; +} + pub const Lanes = struct { x: follow.Leader, - lanes: std.AutoHashMapUnmanaged(*const lanes.Stream, Lane) = .empty, + lanes: Map = .empty, drawn: [ring]u32 = undefined, next: u64 = 0, shared: u64 = 0, // forwards that held several streams' windows @@ -118,9 +129,7 @@ pub const Lanes = struct { const ids = s.prompt(); if (ids.len + s.max_new + max_rows >= self.x.e.capacity) return error.PromptTooLong; if (s.images.len > 0 and self.x.e.vision == null) return error.NoVision; - const gop = try self.lanes.getOrPut(self.x.e.gpa, s); - if (!gop.found_existing) gop.value_ptr.* = .{ .slot = try self.pick(s) }; - const l = gop.value_ptr; + const l = try claim(&self.lanes, self.x.e.gpa, s, self); l.fill = null; l.first = null; l.pictures = s.images.len > 0; @@ -265,3 +274,30 @@ pub const Lanes = struct { if (self.lanes.count() == 0) self.x.idle() catch |err| std.log.err("the other ranks' idle step: {s}", .{@errorName(err)}); } }; + +test "lanes: a new stream's slot is chosen before its entry exists, and a failed choice leaves no entry" { + const gpa = std.testing.allocator; + var map: Map = .empty; + defer map.deinit(gpa); + var streams: [3]lanes.Stream = undefined; + const Chooser = struct { + map: *const Map, + next: u32 = 0, + full: bool = false, + fn pick(c: *@This(), _: *const lanes.Stream) !u32 { + if (c.full) return error.NoFreeSlot; + var it = c.map.valueIterator(); // every entry the scan meets holds a slot already chosen + while (it.next()) |l| try std.testing.expect(l.slot < c.next); + c.next += 1; + return c.next - 1; + } + }; + var ch: Chooser = .{ .map = &map }; + try std.testing.expectEqual(@as(u32, 0), (try claim(&map, gpa, &streams[0], &ch)).slot); + try std.testing.expectEqual(@as(u32, 1), (try claim(&map, gpa, &streams[1], &ch)).slot); + try std.testing.expectEqual(@as(u32, 0), (try claim(&map, gpa, &streams[0], &ch)).slot); + ch.full = true; + try std.testing.expectError(error.NoFreeSlot, claim(&map, gpa, &streams[2], &ch)); + try std.testing.expectEqual(@as(u32, 2), map.count()); + try std.testing.expect(map.get(&streams[2]) == null); +} From 45259749b63e661bc306406e813a13a28eb3ac3f Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 23:31:03 +1100 Subject: [PATCH 24/27] inkling2: compare every shard byte across the ranks at ready checkpoint_digest stayed zero, so the ready check passed two ranks holding different packs. Each rank now hashes every shard byte beside the load and hands that digest to the check. --- zig/src/families/inkling2/engine.zig | 2 +- zig/src/families/inkling2/native.zig | 41 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/engine.zig b/zig/src/families/inkling2/engine.zig index 2f253cf6da8..ea211079f25 100644 --- a/zig/src/families/inkling2/engine.zig +++ b/zig/src/families/inkling2/engine.zig @@ -60,7 +60,7 @@ pub const Engine = struct { graphs: cuda.graph_cache.Cache(Key), gengine: cuda.graph_cache.CudaEngine, states: kept.Store, - checkpoint_digest: [32]u8 = @splat(0), + checkpoint_digest: [32]u8 = @splat(0), // every shard byte this rank loaded (native.zig); the ranks compare it vision: ?pictures.Limits = null, // images on (--vision): every rank's rows a slot, rank 0's tower tower: ?*vision.Tower = null, rows: []pictures.Rows = &.{}, diff --git a/zig/src/families/inkling2/native.zig b/zig/src/families/inkling2/native.zig index 7de8ea56d96..11e63017d5b 100644 --- a/zig/src/families/inkling2/native.zig +++ b/zig/src/families/inkling2/native.zig @@ -134,6 +134,9 @@ fn openRank(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer _ = own.lib.?.api.ncclCommDestroy(own.comm); const cap = capacity(o.context); const lim: ?pictures.Limits = if (o.vision) |v| .{ .image_tokens = v.image_tokens, .max_images = @min(v.max_images, 64) } else null; + // every shard byte, hashed beside the weights' load; the ranks compare the digests at ready + var content: ?*core.checkpoint_identity.Content = try startIdentity(gpa, io, dir); + errdefer if (content) |x| x.abandon(); own.e = try engine.Engine.init(gpa, io, ctx.d, dir, p.rank, p.world, .{ .capacity = cap, .vision = lim }); errdefer own.e.deinit(); own.link = try follow.Link.init(gpa, ctx.d, &own.lib.?, own.comm, own.e.stream, @max(cap, engine.prompt_rows)); @@ -143,6 +146,9 @@ fn openRank(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ try own.group.?.openRoce(gpa, io, ctx.d, own.e.stream, own.e.roceBytes()); errdefer if (own.group.?.fast) |f| f.deinit(); own.e.exchange = .{ .nccl = .{ .lib = &own.lib.?, .comm = own.comm, .group = &own.group.? } }; + const hashing = content.?; + content = null; + own.e.checkpoint_digest = try hashing.finish(); try load_cache.finishAfter(.{ io, own.e.checkpoint_digest }, cuda.tp_watch.ready); // rank 0 admits by the smallest room of the ranks var peer: ?Peer = null; @@ -246,6 +252,11 @@ fn release(own: *Owned) void { own.gpa.destroy(own); } +/// Every shard byte of the pack, hashed on threads: both ranks read whole files, so their digests must match. +pub fn startIdentity(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*core.checkpoint_identity.Content { + return core.checkpoint_identity.Content.start(gpa, io, dir, false); +} + /// The server's words for this family's refusals. pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return admission.explain(err) orelse switch (err) { @@ -253,6 +264,7 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.UnexpectedInkling2Tensor => "a tensor is not stored as the Inkling 2 EXL3 pack stores it (the log names it)", error.NotExl3 => "Inkling 2 on CUDA reads EXL3 packs: config.json needs a quantization_config with quant_method exl3", error.UnsupportedExl3 => "this EXL3 pack is not from exllamav3 1.x on the mul1 codebook, the only form validated here", + error.CheckpointBytesDiffer => "the two ranks' packs hold different bytes: copy the same pack to both hosts", error.NoVision => "images need --vision on both ranks (rank 0 runs the tower from the pack's vision.safetensors)", error.ImagePlaceholders => "the prompt's image placeholders do not match its pictures", error.ImageTooLarge => pictures.Offer.explain(error.ImageTooLarge).?, @@ -267,3 +279,32 @@ test "native: refusals explain themselves; a stream's capacity holds the context try std.testing.expectEqual(@as(usize, 1048576 + 64), capacity(1048576)); try std.testing.expectEqual(@as(usize, 131072 + 64), capacity(131072)); } + +test "native: the ranks compare every shard byte, so one changed byte in a pack changes the digest" { + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const head = "{\"t\":{\"dtype\":\"U8\",\"shape\":[64],\"data_offsets\":[0,64]}}"; + var bytes: [8 + head.len + 64]u8 = undefined; + std.mem.writeInt(u64, bytes[0..8], head.len, .little); + @memcpy(bytes[8..][0..head.len], head); + for (bytes[8 + head.len ..], 0..) |*b, i| b.* = @truncate(i); + const subs = [_][]const u8{ "a", "b", "c" }; + var got: [3][32]u8 = undefined; + for (subs, &got, 0..) |sub, *g, k| { + if (k == 2) bytes[bytes.len - 1] ^= 1; // the last tensor byte of the third copy + try tmp.dir.createDirPath(io, sub); + var d = try tmp.dir.openDir(io, sub, .{}); + defer d.close(io); + try d.writeFile(io, .{ .sub_path = "config.json", .data = "{}" }); + try d.writeFile(io, .{ .sub_path = "model.safetensors", .data = &bytes }); + const path = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/{s}", .{ tmp.sub_path, sub }); + defer gpa.free(path); + g.* = try (try startIdentity(gpa, io, path)).finish(); + } + try std.testing.expectEqual(got[0], got[1]); + try std.testing.expect(!std.mem.eql(u8, &got[0], &got[2])); + try std.testing.expect(!std.mem.eql(u8, &got[0], &@as([32]u8, @splat(0)))); + try std.testing.expect(explain(null, error.CheckpointBytesDiffer) != null); +} From b4d0a1361373f22606c665883374371173859617 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 24 Nov 2026 23:31:03 +1100 Subject: [PATCH 25/27] inkling2: make a call's scratch safe to free at every failed allocation Buffers.deinit read ids and logits before init had made them. Both now start empty, and a fake-driver test fails each allocation in turn. --- zig/src/families/inkling2/forward.zig | 12 +++-- zig/src/families/inkling2/forward_test.zig | 60 ++++++++++++++++++++++ 2 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 zig/src/families/inkling2/forward_test.zig diff --git a/zig/src/families/inkling2/forward.zig b/zig/src/families/inkling2/forward.zig index eca983c9556..cc418ffc77f 100644 --- a/zig/src/families/inkling2/forward.zig +++ b/zig/src/families/inkling2/forward.zig @@ -188,7 +188,7 @@ pub const Partials = struct { o: u64, ml: u64, slots: usize }; pub const Buffers = struct { gpa: std.mem.Allocator, bufs: std.ArrayList(Buf) = .empty, - ids: Buf = undefined, // int32 rows, then pos, seg_of, the segments and the tiles + ids: Buf, // int32 rows, then pos, seg_of, the segments and the tiles x: u64 = 0, // bf16 [rows][hidden]: the residual stream between layers resid: u64 = 0, // fp32 [rows][hidden]: the residual inside a layer blocks: u64 = 0, // bf16 [8][rows][hidden]: the completed blocks' inputs of these rows @@ -215,13 +215,13 @@ pub const Buffers = struct { moe: u64 = 0, gathered: u64 = 0, // fp32 [world][rows][hidden]: every rank's partial of a site (world > 1) exs: cuda.exl3_experts.Scratch = undefined, - logits: Buf = undefined, // fp32 [rows][padded vocab of the rank] + logits: Buf, // fp32 [rows][padded vocab of the rank] /// Scratch for `s.rows` rows; `shared` partials, else its own for every row at the shape's context. pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const weights.Weights, s: Shape, shared: ?Partials) !Buffers { const c = &w.config; - var b: Buffers = .{ .gpa = gpa }; - errdefer b.deinit(); + var b: Buffers = .{ .gpa = gpa, .ids = .{ .d = d, .ptr = 0, .len = 0 }, .logits = .{ .d = d, .ptr = 0, .len = 0 } }; + errdefer b.deinit(); // ids and logits start empty, so a failure before either is made frees neither const n = s.rows; const h: usize = c.hidden; const hd: usize = c.head_dim; @@ -513,3 +513,7 @@ test "forward: a staged call's words sit where launch reads them" { try std.testing.expectEqual(@as(u32, 5), stride(&c, 100)); try std.testing.expectEqual(@as(u32, 64), stride(&c, 1048575)); } + +test { + _ = @import("forward_test.zig"); +} diff --git a/zig/src/families/inkling2/forward_test.zig b/zig/src/families/inkling2/forward_test.zig new file mode 100644 index 00000000000..d7afa492a5b --- /dev/null +++ b/zig/src/families/inkling2/forward_test.zig @@ -0,0 +1,60 @@ +//! A call's scratch (forward.Buffers) on a fake driver: every allocation that can fail leaves nothing behind. +const std = @import("std"); +const cuda = @import("cuda"); +const fw = @import("forward.zig"); +const cfg = @import("shape.zig"); +const weights = @import("pack_weights.zig"); +const shard = @import("shard.zig"); + +const Fake = struct { + var made: usize = 0; + var freed: usize = 0; + var fail_at: usize = 0; // the allocation (1 for the first) that fails, 0 for none + var next: u64 = 1 << 20; + + fn alloc(p: *cuda.abi.DevicePtr, _: usize) callconv(.c) cuda.abi.Result { + if (made + 1 == fail_at) return cuda.abi.error_not_ready; + made += 1; + p.* = next; + next += 1 << 20; + return 0; + } + fn free(_: cuda.abi.DevicePtr) callconv(.c) cuda.abi.Result { + freed += 1; + return 0; + } + fn fill(_: cuda.abi.DevicePtr, _: u8, _: usize) callconv(.c) cuda.abi.Result { + return 0; + } + fn reset(at: usize) void { + made = 0; + freed = 0; + fail_at = at; + } +}; + +test "forward: a call's scratch frees exactly what it made when any one of its allocations fails" { + const gpa = std.testing.allocator; + var d: cuda.Driver = undefined; + d.api.cuMemAlloc_v2 = Fake.alloc; + d.api.cuMemFree_v2 = Fake.free; + d.api.cuMemsetD8_v2 = Fake.fill; + var w: weights.Weights = .{ .gpa = gpa, .d = &d, .config = try cfg.parse(gpa, @embedFile("fixtures/config.json")), .share = undefined }; + w.share = try shard.Share.of(&w.config, 201088, 0, 2); + var layer: weights.Layer = undefined; + layer.experts = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .experts = w.config.experts, .dims = w.config.hidden, .width = 1152, .codebook = .mul1 }; + w.layers = (&layer)[0..1]; + const shape: fw.Shape = .{ .rows = 8, .context = 4096, .heads = 6, .kv = 1 }; + Fake.reset(0); + var whole = try fw.Buffers.init(gpa, &d, &w, shape, null); + whole.deinit(); + const total = Fake.made; + try std.testing.expect(total > 20); + try std.testing.expectEqual(total, Fake.freed); + for (1..total + 1) |at| { + Fake.reset(at); + try std.testing.expectError(error.NotReady, fw.Buffers.init(gpa, &d, &w, shape, null)); + try std.testing.expectEqual(at - 1, Fake.made); + try std.testing.expectEqual(Fake.made, Fake.freed); + } +} From f7e9fca025f66214d2044a476ed229602b97e341 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Wed, 25 Nov 2026 21:04:26 +1100 Subject: [PATCH 26/27] inkling2: bind the config each rank runs into the ready check Two ranks with identical shards but different configs, such as another rms_norm_eps, passed the ready check. The digest now also covers the parsed config and the stream shape each rank was started with. --- zig/src/families/inkling2/native.zig | 33 ++++++++++++++++++++++++++-- zig/src/families/inkling2/shape.zig | 10 +++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/zig/src/families/inkling2/native.zig b/zig/src/families/inkling2/native.zig index 11e63017d5b..e3d55bc64fe 100644 --- a/zig/src/families/inkling2/native.zig +++ b/zig/src/families/inkling2/native.zig @@ -148,7 +148,7 @@ fn openRank(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ own.e.exchange = .{ .nccl = .{ .lib = &own.lib.?, .comm = own.comm, .group = &own.group.? } }; const hashing = content.?; content = null; - own.e.checkpoint_digest = try hashing.finish(); + own.e.checkpoint_digest = readyDigest(try hashing.finish(), &own.e.c, cap, lim); try load_cache.finishAfter(.{ io, own.e.checkpoint_digest }, cuda.tp_watch.ready); // rank 0 admits by the smallest room of the ranks var peer: ?Peer = null; @@ -257,6 +257,16 @@ pub fn startIdentity(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*core return core.checkpoint_identity.Content.start(gpa, io, dir, false); } +/// What the ranks compare at ready: every shard byte, the config the engine runs and the stream shape. +pub fn readyDigest(shards: [32]u8, c: *const cfg.Config, cap: usize, lim: ?pictures.Limits) [32]u8 { + var h = std.crypto.hash.sha2.Sha256.init(.{}); + h.update(&shards); + c.hash(&h); + const shape = [3]u64{ cap, if (lim) |l| l.image_tokens else 0, if (lim) |l| l.max_images else 0 }; + h.update(std.mem.sliceAsBytes(&shape)); + return h.finalResult(); +} + /// The server's words for this family's refusals. pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return admission.explain(err) orelse switch (err) { @@ -264,7 +274,7 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.UnexpectedInkling2Tensor => "a tensor is not stored as the Inkling 2 EXL3 pack stores it (the log names it)", error.NotExl3 => "Inkling 2 on CUDA reads EXL3 packs: config.json needs a quantization_config with quant_method exl3", error.UnsupportedExl3 => "this EXL3 pack is not from exllamav3 1.x on the mul1 codebook, the only form validated here", - error.CheckpointBytesDiffer => "the two ranks' packs hold different bytes: copy the same pack to both hosts", + error.CheckpointBytesDiffer => "the two ranks' packs or settings differ: copy the same pack to both hosts and start both alike", error.NoVision => "images need --vision on both ranks (rank 0 runs the tower from the pack's vision.safetensors)", error.ImagePlaceholders => "the prompt's image placeholders do not match its pictures", error.ImageTooLarge => pictures.Offer.explain(error.ImageTooLarge).?, @@ -308,3 +318,22 @@ test "native: the ranks compare every shard byte, so one changed byte in a pack try std.testing.expect(!std.mem.eql(u8, &got[0], &@as([32]u8, @splat(0)))); try std.testing.expect(explain(null, error.CheckpointBytesDiffer) != null); } + +test "native: the ready digest binds the config the engine runs, so a config-only change differs" { + const gpa = std.testing.allocator; + const text = @embedFile("fixtures/config.json"); + const eps = "\"rms_norm_eps\": 1e-06"; + const at = std.mem.indexOf(u8, text, eps).?; // the text model's, the first in the file + const other = try std.mem.concat(gpa, u8, &.{ text[0..at], "\"rms_norm_eps\": 1e-05", text[at + eps.len ..] }); + defer gpa.free(other); + const a = try cfg.parse(gpa, text); + const b = try cfg.parse(gpa, other); + try std.testing.expect(a.eps != b.eps); + const shards: [32]u8 = @splat(7); + const base = readyDigest(shards, &a, capacity(131072), null); + try std.testing.expectEqual(base, readyDigest(shards, &try cfg.parse(gpa, text), capacity(131072), null)); + try std.testing.expect(!std.mem.eql(u8, &base, &readyDigest(shards, &b, capacity(131072), null))); + try std.testing.expect(!std.mem.eql(u8, &base, &readyDigest(shards, &a, capacity(1048576), null))); + try std.testing.expect(!std.mem.eql(u8, &base, &readyDigest(shards, &a, capacity(131072), .{ .image_tokens = 1024, .max_images = 8 }))); + try std.testing.expect(!std.mem.eql(u8, &base, &readyDigest(@splat(8), &a, capacity(131072), null))); +} diff --git a/zig/src/families/inkling2/shape.zig b/zig/src/families/inkling2/shape.zig index 1f455da2208..9ea7f8baecc 100644 --- a/zig/src/families/inkling2/shape.zig +++ b/zig/src/families/inkling2/shape.zig @@ -68,6 +68,16 @@ pub const Config = struct { pub fn stops(c: *const Config) []const u32 { return c.eos[0..c.eos_count]; } + + /// Every value the engine runs with, for the ranks' ready check (layer kinds up to `layers`). + pub fn hash(c: *const Config, h: *std.crypto.hash.sha2.Sha256) void { + inline for (@typeInfo(Config).@"struct".field_names) |name| { + h.update(name); + if (comptime std.mem.eql(u8, name, "layer")) { + for (c.layer[0..c.layers]) |k| h.update(&[_]u8{@backingInt(k)}); + } else h.update(std.mem.asBytes(&@field(c, name))); + } + } }; pub const Error = error{ BadInkling2Config, UnsupportedInkling2Attention, UnsupportedInkling2Experts }; From 3c262e577e00da7d92e7bcec1bb91679c9bcad61 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Wed, 25 Nov 2026 21:04:26 +1100 Subject: [PATCH 27/27] inkling2: free the prompt projections when engine setup fails Engine.init cleaned up a stale copy of its modules, which never held the prompt projections. A failed kernel lookup leaked the GEMM workspace and a failed plan insertion leaked its descriptor and layouts. --- zig/src/families/inkling2/engine.zig | 14 ++- zig/src/families/inkling2/prompt_dense.zig | 137 ++++++++++++++++++++- 2 files changed, 143 insertions(+), 8 deletions(-) diff --git a/zig/src/families/inkling2/engine.zig b/zig/src/families/inkling2/engine.zig index ea211079f25..0075864821b 100644 --- a/zig/src/families/inkling2/engine.zig +++ b/zig/src/families/inkling2/engine.zig @@ -60,7 +60,7 @@ pub const Engine = struct { graphs: cuda.graph_cache.Cache(Key), gengine: cuda.graph_cache.CudaEngine, states: kept.Store, - checkpoint_digest: [32]u8 = @splat(0), // every shard byte this rank loaded (native.zig); the ranks compare it + checkpoint_digest: [32]u8 = @splat(0), // shard bytes, config and stream shape (native.readyDigest); ranks compare it vision: ?pictures.Limits = null, // images on (--vision): every rank's rows a slot, rank 0's tower tower: ?*vision.Tower = null, rows: []pictures.Rows = &.{}, @@ -71,16 +71,18 @@ pub const Engine = struct { const c = try cfg.Config.read(gpa, io, dir); var stream = try cuda.Stream.init(d, false); errdefer stream.deinit(); - var m = try fw.Modules.load(d); - errdefer m.deinit(); - e.* = .{ .gpa = gpa, .io = io, .d = d, .c = c, .m = m, .stream = stream, .w = undefined, .shape_p = undefined, .shape_d = undefined, .bp = undefined, .bd = undefined, .capacity = o.capacity, .picks = undefined, .picks_host = &.{}, .smp = undefined, .spans = &.{}, .graphs = undefined, .gengine = .{ .d = d }, .states = .{ .gpa = gpa } }; + e.* = .{ .gpa = gpa, .io = io, .d = d, .c = c, .m = try fw.Modules.load(d), .stream = stream, .w = undefined, .shape_p = undefined, .shape_d = undefined, .bp = undefined, .bd = undefined, .capacity = o.capacity, .picks = undefined, .picks_host = &.{}, .smp = undefined, .spans = &.{}, .graphs = undefined, .gengine = .{ .d = d }, .states = .{ .gpa = gpa } }; + errdefer e.m.deinit(); // e's copy: it holds the prompt projections and the scratch reserve grows e.w = try weights.load(gpa, io, d, &e.m.dense, stream, dir, c, rank, world); errdefer e.w.deinit(); const heads = e.w.share.heads.len(); const kv = e.w.share.kv.len(); e.shape_p = .{ .rows = prompt_rows, .context = o.capacity, .heads = heads, .kv = kv }; e.shape_d = .{ .rows = shared_rows, .context = o.capacity, .heads = heads, .kv = kv, .ring_rows = prompt_rows }; - errdefer for (e.parts.items) |*b| b.free(); + errdefer { + for (e.parts.items) |*b| b.free(); + e.parts.deinit(gpa); + } const slots = @max(prompt_rows * heads * prompt_parts, shared_rows * heads * fw.stride(&e.c, o.capacity - 1)); const shared = try fw.partialsFor(d, &e.parts, gpa, slots); e.bp = try fw.Buffers.init(gpa, d, &e.w, e.shape_p, shared); @@ -104,8 +106,10 @@ pub const Engine = struct { e.smp = try sampler.Sampler.init(d, e.w.padded_vocab, shared_rows); errdefer e.smp.deinit(); e.spans = try gpa.alloc(shard.Span, world); + errdefer gpa.free(e.spans); for (e.spans, 0..) |*sp, q| sp.* = (try shard.Share.of(&e.c, e.w.padded_vocab, q, world)).vocab; e.graphs = .init(gpa, e.gengine.engine(), .{}); + errdefer e.graphs.deinit(); e.graphs.name = "inkling2 decode"; try e.stream.synchronize(); return e; diff --git a/zig/src/families/inkling2/prompt_dense.zig b/zig/src/families/inkling2/prompt_dense.zig index 07343714026..a641238507d 100644 --- a/zig/src/families/inkling2/prompt_dense.zig +++ b/zig/src/families/inkling2/prompt_dense.zig @@ -30,10 +30,17 @@ pub const Prompt = struct { pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, tail: cuda.Function, rows_max: usize, k_max: usize, n_max: usize) !Prompt { var lt = try lt_.Library.open(); errdefer lt.close(); + return make(gpa, d, lt, cuda.kernels.exl3_candidate, tail, rows_max, k_max, n_max); + } + + /// Everything but the library, which the caller closes on failure; a failed step leaves nothing else behind. + fn make(gpa: std.mem.Allocator, d: *const cuda.Driver, lt: lt_.Library, image: []const u8, tail: cuda.Function, rows_max: usize, k_max: usize, n_max: usize) !Prompt { const handle = try lt_.createHandle(<); errdefer _ = lt.api.cublasLtDestroy(handle); - var mod = try cuda.Module.load(d, cuda.kernels.exl3_candidate); + var mod = try cuda.Module.load(d, image); errdefer mod.unload(); + const rotate = try mod.function("tf_exl3_rotate_h"); + const unpack = try mod.function("tf_exl3_unpack"); var xh = try Buf.alloc(d, rows_max * k_max * 2); errdefer xh.free(); var w = try Buf.alloc(d, k_max * n_max * 2); @@ -41,7 +48,7 @@ pub const Prompt = struct { var z = try Buf.alloc(d, rows_max * n_max * 4); errdefer z.free(); const ws = try Buf.alloc(d, workspace_bytes); - return .{ .gpa = gpa, .d = d, .lt = lt, .handle = handle, .mod = mod, .rotate = try mod.function("tf_exl3_rotate_h"), .unpack = try mod.function("tf_exl3_unpack"), .tail = tail, .xh = xh, .w = w, .z = z, .ws = ws, .rows_max = rows_max }; + return .{ .gpa = gpa, .d = d, .lt = lt, .handle = handle, .mod = mod, .rotate = rotate, .unpack = unpack, .tail = tail, .xh = xh, .w = w, .z = z, .ws = ws, .rows_max = rows_max }; } /// Scratch for the widest attention projection of `layers` at `rows` rows. @@ -75,7 +82,8 @@ pub const Prompt = struct { fn plan(p: *Prompt, rows: usize, k: usize, n: usize) !*const lt_.Gemm { for (p.plans.items) |*x| if (x.rows == rows and x.k == k and x.n == n) return &x.g; // column-major: Z^T [n, rows] = W^T [n, k] . Xh^T [k, rows] - const g = try lt_.Gemm.init(&p.lt, p.handle, .{ .m = n, .n = rows, .k = k, .a = .f16, .b = .f16, .c = .f32, .lda = n, .ldb = k, .ldc = n }, workspace_bytes); + var g = try lt_.Gemm.init(&p.lt, p.handle, .{ .m = n, .n = rows, .k = k, .a = .f16, .b = .f16, .c = .f32, .lda = n, .ldb = k, .ldc = n }, workspace_bytes); + errdefer g.deinit(); try p.plans.append(p.gpa, .{ .rows = rows, .k = k, .n = n, .g = g }); return &p.plans.items[p.plans.items.len - 1].g; } @@ -108,3 +116,126 @@ pub const Prompt = struct { /// exl3_candidate.cu's TfExl3Matrix, by value. const MatrixArgs = extern struct { k: u32, n: u32, bits: u32, tiles_n: u32, split: u32 }; + +/// A driver and cuBLASLt that make handles and count them, failing the `fail_at`th device allocation (0: none). +const Fake = struct { + var made: usize = 0; + var gone: usize = 0; + var allocs: usize = 0; + var fail_at: usize = 0; + var fail_load = false; + var token: u8 = 0; + + fn reset(at: usize, refuse_load: bool) void { + made = 0; + gone = 0; + allocs = 0; + fail_at = at; + fail_load = refuse_load; + } + fn make(p: anytype) cuda.abi.Result { + made += 1; + p.* = @ptrCast(&token); + return 0; + } + fn unload(_: cuda.abi.Module) callconv(.c) cuda.abi.Result { + gone += 1; + return 0; + } + fn destroy(_: ?*anyopaque) callconv(.c) c_int { + gone += 1; + return 0; + } + fn load(m: *cuda.abi.Module, _: ?*const anyopaque) callconv(.c) cuda.abi.Result { + return if (fail_load) cuda.abi.error_not_ready else make(m); + } + fn function(f: *cuda.abi.Function, _: cuda.abi.Module, _: [*:0]const u8) callconv(.c) cuda.abi.Result { + f.* = @ptrCast(&token); + return 0; + } + fn alloc(p: *cuda.abi.DevicePtr, _: usize) callconv(.c) cuda.abi.Result { + allocs += 1; + if (allocs == fail_at) return cuda.abi.error_not_ready; + made += 1; + p.* = allocs << 20; + return 0; + } + fn free(_: cuda.abi.DevicePtr) callconv(.c) cuda.abi.Result { + gone += 1; + return 0; + } + fn create(h: *lt_.Handle) callconv(.c) c_int { + return make(h); + } + fn desc(x: *lt_.MatmulDesc, _: c_int, _: lt_.DataType) callconv(.c) c_int { + return make(x); + } + fn layout(x: *lt_.Layout, _: lt_.DataType, _: u64, _: u64, _: i64) callconv(.c) c_int { + return make(x); + } + fn pref(x: *lt_.Preference) callconv(.c) c_int { + return make(x); + } + fn set(_: ?*anyopaque, _: c_int, _: ?*const anyopaque, _: usize) callconv(.c) c_int { + return 0; + } + fn heuristic(_: lt_.Handle, _: lt_.MatmulDesc, _: lt_.Layout, _: lt_.Layout, _: lt_.Layout, _: lt_.Layout, _: lt_.Preference, _: c_int, out: [*]lt_.Heuristic, n: *c_int) callconv(.c) c_int { + out[0] = std.mem.zeroes(lt_.Heuristic); + n.* = 1; + return 0; + } + + fn driver() cuda.Driver { + var d: cuda.Driver = undefined; + d.api.cuModuleLoadData = load; + d.api.cuModuleUnload = unload; + d.api.cuModuleGetFunction = function; + d.api.cuMemAlloc_v2 = alloc; + d.api.cuMemFree_v2 = free; + return d; + } + fn library() lt_.Library { + var lt: lt_.Library = undefined; + lt.api.cublasLtCreate = create; + lt.api.cublasLtDestroy = @ptrCast(&destroy); + lt.api.cublasLtMatmulDescCreate = desc; + lt.api.cublasLtMatmulDescDestroy = @ptrCast(&destroy); + lt.api.cublasLtMatmulDescSetAttribute = @ptrCast(&set); + lt.api.cublasLtMatrixLayoutCreate = layout; + lt.api.cublasLtMatrixLayoutDestroy = @ptrCast(&destroy); + lt.api.cublasLtMatmulPreferenceCreate = pref; + lt.api.cublasLtMatmulPreferenceDestroy = @ptrCast(&destroy); + lt.api.cublasLtMatmulPreferenceSetAttribute = @ptrCast(&set); + lt.api.cublasLtMatmulAlgoGetHeuristic = heuristic; + return lt; + } +}; + +test "prompt dense: a failed module load or allocation frees everything made before it" { + var d = Fake.driver(); + const image: [8]u8 align(8) = @splat(1); + const tail: cuda.Function = .{ .d = &d, .handle = null }; + Fake.reset(0, true); + try std.testing.expectError(error.NotReady, Prompt.make(std.testing.allocator, &d, Fake.library(), &image, tail, 256, 128, 128)); + try std.testing.expectEqual(Fake.made, Fake.gone); // the handle + for (1..5) |at| { + Fake.reset(at, false); + try std.testing.expectError(error.NotReady, Prompt.make(std.testing.allocator, &d, Fake.library(), &image, tail, 256, 128, 128)); + try std.testing.expectEqual(at + 1, Fake.made); // the handle, the module and the allocations before the failed one + try std.testing.expectEqual(Fake.made, Fake.gone); + } +} + +test "prompt dense: a plan whose insertion fails destroys its descriptor and layouts" { + var d = Fake.driver(); + const image: [8]u8 align(8) = @splat(1); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + Fake.reset(0, false); + var p = try Prompt.make(failing.allocator(), &d, Fake.library(), &image, .{ .d = &d, .handle = null }, 256, 128, 128); + const made = Fake.made; + const gone = Fake.gone; + try std.testing.expectError(error.OutOfMemory, p.plan(256, 128, 128)); + try std.testing.expectEqual(made + 5, Fake.made); // a descriptor, three layouts and a preference + try std.testing.expectEqual(gone + 5, Fake.gone); + try std.testing.expectEqual(@as(usize, 0), p.plans.items.len); +}