From f506be422a0c893e575cb972f384761a09ba03fe Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 3 Nov 2026 06:31:43 +0000 Subject: [PATCH 01/15] cuda: reconcile the BF16 prompt port with the landed tile Reuse #1764's existing kernel, resource records and required symbol bindings for the Qwen dense/MoE and Nemotron ModelOpt port. Keep one six-entry numerical/replacement/control set. Cache the serving choice: TF_CUDA_PROMPT_BF16=0 restores the lane but leaves required symbols bound. The threshold is fixed at 1024 rows. Host ABI and fixture-lifetime checks pass; fresh CUDA contract and checkpoint A/B receipts remain required on this rebased tree. Refs #1762, #1764. Co-authored-by: Armin <2369138+Arminova@users.noreply.github.com> --- docs/recipes/cuda.md | 5 + zig/build/cuda.zig | 2 + zig/build/prompt_bf16_host.zig | 21 ++++ zig/src/cuda/nvfp4.zig | 21 ++++ zig/src/cuda/prompt_bf16_host_test.zig | 103 ++++++++++++++++++ zig/src/cuda/qlinear.zig | 8 +- zig/src/cuda/root.zig | 1 + zig/src/families/nemotron/cuda_kernels.zig | 3 +- zig/src/families/qwen3_5/cuda_modelopt.zig | 3 +- zig/tests/cuda/contract_projection_set.zig | 49 +++++++++ zig/tests/cuda/contract_prompt_bf16.zig | 83 ++++++++++++++ .../cuda/contract_prompt_bf16_host_test.zig | 68 ++++++++++++ zig/tests/cuda/contract_tests.zig | 20 +--- 13 files changed, 368 insertions(+), 19 deletions(-) create mode 100644 zig/build/prompt_bf16_host.zig create mode 100644 zig/src/cuda/prompt_bf16_host_test.zig create mode 100644 zig/tests/cuda/contract_projection_set.zig create mode 100644 zig/tests/cuda/contract_prompt_bf16.zig create mode 100644 zig/tests/cuda/contract_prompt_bf16_host_test.zig diff --git a/docs/recipes/cuda.md b/docs/recipes/cuda.md index f9e9f23bc0f..45398bdc1ba 100644 --- a/docs/recipes/cuda.md +++ b/docs/recipes/cuda.md @@ -108,6 +108,11 @@ format ([prompt precision](#prompt-precision)): ## Native prompt controls +Qwen dense/MoE and Nemotron ModelOpt BF16 projections use the shared BF16 prompt tile from 1,024 rows. +`TF_CUDA_PROMPT_BF16=0` restores their lane projections; unset or any other value selects the tile. +The threshold is fixed. The prompt module always binds its required BF16 symbols, including with the switch off. +Flash Next keeps its own prompt selection and controls. + For Nemotron, the native `tensorfold run` command on a CUDA build accepts `--device N` to choose a CUDA ordinal. If the flag is absent, it uses `TF_CUDA_DEVICE`, then device 0. `--segments N` enables staggered prompt work for 1 through 4 whole 2,048-row chunks; without the flag it diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 35d165e1a85..7903f0ebc49 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -240,6 +240,8 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st const runtime_host = b.step("test-runtime-host", "Shared CUDA runtime and graph host regressions"); runtime_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda })).step); const mods = family(b, host, .ReleaseSafe, cuda, draft_ids); + const mods = family(b, host, .debug, cuda, draft_ids); + @import("prompt_bf16_host.zig").tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); @import("cuda_checkpoint_cache_host.zig").steps(b, step); b.step("test-lfm2-load-host", "LFM2 decision model metadata and load ownership without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lfm2Module(b, host, .debug, cuda, mods.core) })).step); engines_build.qwen3HostTest(b, engines_build.qwen3Module(b, host, .debug, cuda, mods.core, mods.lanes, mods.api), step); diff --git a/zig/build/prompt_bf16_host.zig b/zig/build/prompt_bf16_host.zig new file mode 100644 index 00000000000..b806e09bfd4 --- /dev/null +++ b/zig/build/prompt_bf16_host.zig @@ -0,0 +1,21 @@ +//! CPU-only dispatch and contract registration checks for opt-in BF16 prompt dispatch. +const std = @import("std"); + +pub fn tests(b: *std.Build, all: *std.Build.Step, debug_cuda: *std.Build.Module, fast_cuda: *std.Build.Module, core: *std.Build.Module) void { + const step = b.step("test-prompt-bf16-host", "BF16 prompt tile dispatch and old-path controls without devices"); + for ([_]*std.Build.Module{ debug_cuda, fast_cuda }, [_]std.builtin.OptimizeMode{ .debug, .fast }) |cuda, mode| { + const dispatch = b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"BF16 prompt"} })); + dispatch.has_side_effects = true; + step.dependOn(&dispatch.step); + const fixture = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/contract_prompt_bf16_host_test.zig"), + .target = b.graph.host, + .optimize = mode, + .link_libc = true, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } }, + }) })); + fixture.has_side_effects = true; + step.dependOn(&fixture.step); + } + all.dependOn(step); +} diff --git a/zig/src/cuda/nvfp4.zig b/zig/src/cuda/nvfp4.zig index 13cf22e4d30..4a3fd9a86c0 100644 --- a/zig/src/cuda/nvfp4.zig +++ b/zig/src/cuda/nvfp4.zig @@ -68,6 +68,7 @@ pub const Prompt = struct { fp4_f32: Function, // FP4 writing the fp32 sums unrounded bf16: Function, // BF16 on 2 x 4 warps, 3 stages, the lane's K slices (bf16Shared): the lane's bits bf16_f32: Function, + bf16_serving: bool = false, lean: Function, // prompt_lean FP4, bf16 out lean_f32: Function, // and fp32 out lean_swiglu: Function, // a gate/up pair on the lean tile, bf16(silu(gate) * up) out @@ -145,6 +146,16 @@ pub const Prompt = struct { return .{ .mod = mod, .fp4 = fp4, .fp8 = fp8, .fp4_f32 = fp4_f32, .bf16 = bf16, .bf16_f32 = bf16_f32, .lean = lean, .lean_f32 = lean_f32, .lean_swiglu = lean_swiglu, .sms = @intCast(@max(sms, 1)) }; } + /// Required BF16 symbols stay bound; the cached flag selects this family's serving path only. + pub fn enableBf16(p: *Prompt) !void { + const value = std.c.getenv("TF_CUDA_PROMPT_BF16"); + p.bf16_serving = bf16Enabled(if (value) |v| std.mem.span(v) else null); + } + + pub fn usesBf16(p: Prompt, rows: usize) bool { + return p.bf16_serving and rows >= 1024; + } + pub fn unload(p: *Prompt) void { p.mod.unload(); } @@ -284,3 +295,13 @@ test "scale tiles keep a column's four scales of each 64 inputs together" { try std.testing.expectEqual(s[1 * 8 + 4 + 2], out[((0 * 2 + 1) * 64 + 1) * 4 + 2]); // row 1, group 1, quarter 2 try std.testing.expectEqual(@as(u8, 0), out[((0 * 2 + 0) * 64 + 5) * 4]); // row 5: padding } + +pub fn bf16Enabled(value: ?[]const u8) bool { + return if (value) |v| !std.mem.eql(u8, v, "0") else true; +} + +test "BF16 prompt switch restores serving on the lane without changing required bindings" { + try std.testing.expect(!bf16Enabled("0")); + for ([_]?[]const u8{ null, "1", "", "invalid" }) |v| try std.testing.expect(bf16Enabled(v)); + try std.testing.expectEqual(@as(u32, 98304), Prompt.bf16Shared()); +} diff --git a/zig/src/cuda/prompt_bf16_host_test.zig b/zig/src/cuda/prompt_bf16_host_test.zig new file mode 100644 index 00000000000..d539c5a5e98 --- /dev/null +++ b/zig/src/cuda/prompt_bf16_host_test.zig @@ -0,0 +1,103 @@ +//! Observe real projection dispatch at the CUDA ABI without running a GPU. +const std = @import("std"); +const abi = @import("abi.zig"); +const Driver = @import("driver.zig").Driver; +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; +const qmmf = @import("qmmf.zig"); +const Prompt = @import("nvfp4.zig").Prompt; +const Linear = @import("qlinear.zig").Linear; + +const Mock = struct { + var handle: usize = 0; + var grid: [3]u32 = undefined; + var block: [3]u32 = undefined; + var shared: u32 = 0; + var args: [13]u64 = undefined; + var calls: usize = 0; + + fn launch(f: abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, by: c_uint, bz: c_uint, sm: c_uint, _: abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) abi.Result { + handle = @intFromPtr(f); + grid = .{ gx, gy, gz }; + block = .{ bx, by, bz }; + shared = sm; + const count: usize = if (handle >= 3) 11 else 13; + for (0..count) |i| { + const wide = i < (if (handle >= 3) @as(usize, 2) else 3) or i == (if (handle >= 3) @as(usize, 3) else 4) or (handle < 3 and i == 5); + args[i] = if (wide) @as(*align(1) const u64, @ptrCast(params.?[i].?)).* else @as(*align(1) const u32, @ptrCast(params.?[i].?)).*; + } + calls += 1; + return abi.success; + } +}; + +fn function(d: *const Driver, id: usize) Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; +} + +fn lane(d: *const Driver) qmmf.Lane { + const f = function(d, 1); + return .{ .mod = .{ .d = d, .handle = null }, .fns = @splat(@splat(f)), .f32_fns = @splat(@splat(f)), .reduce = @splat(f), .half = @splat(@splat(@splat(f))), .clusters = false }; +} + +fn prompt(d: *const Driver) Prompt { + const f = function(d, 2); + return .{ .mod = .{ .d = d, .handle = null }, .fp4 = f, .fp8 = f, .fp4_f32 = f, .lean = f, .lean_f32 = f, .sms = 16, .bf16_serving = true, .bf16 = function(d, 3), .bf16_f32 = function(d, 4) }; +} + +test "BF16 prompt port: threshold, family opt-in, cached switch and decode keep the lane" { + var d: Driver = undefined; + d.api.cuLaunchKernel = Mock.launch; + const s: Stream = .{ .d = &d, .handle = null }; + const l = lane(&d); + var p = prompt(&d); + var linear: Linear = .{ .lane = &l, .nvfp4_prompt = &p, .bf16_prompt = true }; + const w: qmmf.Weight = .{ .mode = .bf16, .codes = 0x2000, .scales = 0, .n = 48, .k = 5120, .npad = 128 }; + for ([_]usize{ 256, 512, 768, 1023, 1024, 1025, 1536, 2048 }) |rows| { + Mock.calls = 0; + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, rows); + try std.testing.expectEqual(@as(usize, if (rows >= 1024) 3 else 1), Mock.handle); + try std.testing.expectEqual(@as(usize, 1), Mock.calls); + } + try linear.decode(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, 1024); + try std.testing.expectEqual(@as(usize, 1), Mock.handle); + linear.bf16_prompt = false; + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, 1024); + try std.testing.expectEqual(@as(usize, 1), Mock.handle); + linear.bf16_prompt = true; + p.bf16_serving = false; + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, 1024); + try std.testing.expectEqual(@as(usize, 1), Mock.handle); + try std.testing.expectEqual(@as(usize, 3), @intFromPtr(p.bf16.handle.?)); + try std.testing.expectEqual(@as(usize, 4), @intFromPtr(p.bf16_f32.handle.?)); + linear.nvfp4_prompt = null; + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, 1024); + try std.testing.expectEqual(@as(usize, 1), Mock.handle); +} + +test "BF16 prompt port: actual tile ABI retains stride, scale, tail and shape-fixed K slices" { + var d: Driver = undefined; + d.api.cuLaunchKernel = Mock.launch; + const s: Stream = .{ .d = &d, .handle = null }; + const p = prompt(&d); + const l = lane(&d); + const linear: Linear = .{ .lane = &l, .nvfp4_prompt = &p, .bf16_prompt = true }; + for ([_][2]u32{ .{ 3072, 512 }, .{ 640, 1024 }, .{ 96, 2048 }, .{ 48, 5120 }, .{ 70, 128 } }, [_]u32{ 1, 2, 4, 8, 1 }) |nk, sk| { + const w: qmmf.Weight = .{ .mode = .bf16, .codes = 0x2200, .scales = 0, .scale = 0.125, .n = nk[0], .k = nk[1], .npad = @intCast(@import("nvfp4.zig").padded(nk[0])) }; + const stride = w.k + 64; + Mock.calls = 0; + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1100, .ldx = stride }, 0x3300, 1025); + try std.testing.expectEqual(@as(usize, 1), Mock.calls); + try std.testing.expectEqual(@as(usize, 3), Mock.handle); + try std.testing.expectEqual([3]u32{ 9 * ((w.n + 127) / 128), 1, 1 }, Mock.grid); + try std.testing.expectEqual([3]u32{ 256, 1, 1 }, Mock.block); + try std.testing.expectEqual(@as(u32, 98304), Mock.shared); + const band = @max(1, @min(9, (12 << 20) / (128 * @as(usize, w.k) * 2))); + try std.testing.expectEqualSlices(u64, &.{ 0x1100, 0x2200, @as(u32, @bitCast(w.scale)), 0x3300, 1025, w.n, w.k, sk, w.npad, stride, band }, Mock.args[0..11]); + try p.matmulOut(s, 0x1100, stride, 1025, w, 0x3300, .f32); + try std.testing.expectEqual(@as(usize, 4), Mock.handle); + } + const w: qmmf.Weight = .{ .mode = .bf16, .codes = 0, .scales = 0, .n = 48, .k = 5120, .npad = 128 }; + try p.matmulOut(s, 0x1100, 0, 1, w, 0x3300, .bf16); + try std.testing.expectEqual(@as(u64, w.k), Mock.args[9]); +} diff --git a/zig/src/cuda/qlinear.zig b/zig/src/cuda/qlinear.zig index b54968ecb3d..efe60978ee0 100644 --- a/zig/src/cuda/qlinear.zig +++ b/zig/src/cuda/qlinear.zig @@ -97,6 +97,7 @@ pub const Linear = struct { affine4: ?*const Affine4Kernels = null, lane: ?*const qmmf.Lane = null, // decode rows of every lane format; fp8g and bf16 prompt rows too nvfp4_prompt: ?*const nvfp4.Prompt = null, // the prompt GEMM: nvfp4 and fp8 prompt rows (linear.py's prefill) + bf16_prompt: bool = false, ck: ?*const ck.Ck = null, // the checkpoint's own math: an fp8 weight with an input scale takes e4m3 rows ck_rows: u64 = 0, // its e4m3 rows (at least rows * k bytes), and slice partials where no cluster meets them ck_part: u64 = 0, @@ -149,7 +150,12 @@ pub const Linear = struct { .mxfp8 => |q| return l.onLane(s, q, .mxfp8, in, out, rows), .nvfp4 => |q| return l.onPrompt(s, q, .fp4, in, out, rows), .fp8 => |q| return if (q.act != 0 and l.ck != null) l.checkpoint(s, l.ck.?, q, in, out, rows) else l.onPrompt(s, q, .fp8, in, out, rows), - .bf16 => |q| return l.onLane(s, q, .bf16, in, out, rows), + .bf16 => |q| { + if (l.bf16_prompt) if (l.nvfp4_prompt) |p| { + if (p.usesBf16(rows)) return l.onPrompt(s, q, .bf16, in, out, rows); + }; + return l.onLane(s, q, .bf16, in, out, rows); + }, // prompt rows always take the prompt GEMM: a row's bits must not depend on where a prompt's chunks are cut .q8_0, .iq2xxs => |q| return (l.ggml orelse return error.FormatNotLoaded).promptRows(s, q, in.x, in.ldx, rows, out, .bf16), } diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index b5cddb21199..998f61a2a58 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -185,6 +185,7 @@ test { test { _ = @import("context_health.zig"); + _ = @import("prompt_bf16_host_test.zig"); } test { diff --git a/zig/src/families/nemotron/cuda_kernels.zig b/zig/src/families/nemotron/cuda_kernels.zig index ee5ea671981..bbd699bda1f 100644 --- a/zig/src/families/nemotron/cuda_kernels.zig +++ b/zig/src/families/nemotron/cuda_kernels.zig @@ -194,6 +194,7 @@ pub const Kernels = struct { errdefer lane.unload(); var gemm = try cuda.nvfp4.Prompt.load(k.d); errdefer gemm.unload(); + try gemm.enableBf16(); var experts = try cuda.experts.Nvfp4Experts.load(k.d, sms); errdefer experts.unload(); k.modelopt = .{ .lane = lane, .gemm = gemm, .experts = experts, .pack = try cuda.modelopt.Packer.load(k.d) }; @@ -322,7 +323,7 @@ pub const Ops = struct { /// Every projection format the kernels loaded (cuda/qlinear.zig). pub fn linear(o: Ops) cuda.qlinear.Linear { const m = if (o.k.modelopt) |*x| x else null; - return .{ .affine4 = &o.k.affine, .lane = if (m) |x| &x.lane else null, .nvfp4_prompt = if (m) |x| &x.gemm else null, .ck = if (o.k.ck) |*x| x else null, .ck_rows = o.ck8, .ggml = if (o.k.ggml) |*g| g else null }; + return .{ .affine4 = &o.k.affine, .lane = if (m) |x| &x.lane else null, .nvfp4_prompt = if (m) |x| &x.gemm else null, .bf16_prompt = true, .ck = if (o.k.ck) |*x| x else null, .ck_rows = o.ck8, .ggml = if (o.k.ggml) |*g| g else null }; } /// Every grouped-expert format the kernels loaded (cuda/experts.zig). diff --git a/zig/src/families/qwen3_5/cuda_modelopt.zig b/zig/src/families/qwen3_5/cuda_modelopt.zig index da853b39ed4..a87d4cc9b67 100644 --- a/zig/src/families/qwen3_5/cuda_modelopt.zig +++ b/zig/src/families/qwen3_5/cuda_modelopt.zig @@ -253,6 +253,7 @@ pub const Kernels = struct { errdefer lane.unload(); var prompt = try cuda.nvfp4.Prompt.load(d); errdefer prompt.unload(); + try prompt.enableBf16(); var pack = try cuda.modelopt.Packer.load(d); errdefer pack.unload(); var experts: ?cuda.experts.Nvfp4Experts = if (moe) try cuda.experts.Nvfp4Experts.load(d, sms) else null; @@ -270,7 +271,7 @@ pub const Kernels = struct { } pub fn linear(k: *const Kernels) cuda.qlinear.Linear { - return .{ .lane = &k.lane, .nvfp4_prompt = &k.prompt }; + return .{ .lane = &k.lane, .nvfp4_prompt = &k.prompt, .bf16_prompt = true }; } /// The slice partials every projection of `e` takes below fused_rows (none with clusters). diff --git a/zig/tests/cuda/contract_projection_set.zig b/zig/tests/cuda/contract_projection_set.zig new file mode 100644 index 00000000000..352cafe0b71 --- /dev/null +++ b/zig/tests/cuda/contract_projection_set.zig @@ -0,0 +1,49 @@ +//! Packed projection fixtures own their contexts until every contract gate completes. +const std = @import("std"); +const cuda = @import("cuda"); +const g = @import("core").contract.gates; +const wide = @import("contract_projection_f32.zig"); +const bf16 = @import("contract_prompt_bf16.zig"); + +pub const Set = struct { + products: [wide.modes.len * 2]wide.Product, + narrow: [wide.bf16_modes.len * 2 + 1]wide.Product, + tiles: [6]bf16.Tile, + prompt: cuda.nvfp4.Prompt, + + pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, lane: *const cuda.qmmf.Lane, reduce: *const cuda.qmmf.Lane, prompt: *const cuda.nvfp4.Prompt) !Set { + var out: Set = undefined; + out.prompt = prompt.*; + for (wide.modes, 0..) |mode, i| { + out.products[i * 2] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = lane, .mode = mode, .clusters = true }; + out.products[i * 2 + 1] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = reduce, .mode = mode, .clusters = false }; + } + for (wide.bf16_modes, 0..) |mode, i| { + out.narrow[i * 2] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = lane, .mode = mode, .clusters = true, .out_kind = .bf16 }; + out.narrow[i * 2 + 1] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = reduce, .mode = mode, .clusters = false, .out_kind = .bf16 }; + } + out.narrow[out.narrow.len - 1] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = lane, .mode = .fp8, .clusters = true, .out_kind = .bf16, .prompt = prompt }; + for (&out.tiles, 0..) |*t, i| t.* = .{ + .product = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = reduce, .mode = .bf16, .clusters = false, .out_kind = if (i % 2 == 0) .bf16 else .f32 }, + .prompt = undefined, + .replacement = i >= 2, + .control = i >= 4, + }; + return out; + } + + pub fn deinit(set: *Set) void { + for (&set.products) |*p| p.deinit(); + for (&set.narrow) |*p| p.deinit(); + for (&set.tiles) |*t| t.deinit(); + } + + pub fn append(set: *Set, a: std.mem.Allocator, kernels: *std.ArrayList(g.Kernel)) !void { + for (&set.products) |*p| try kernels.append(a, p.kernel()); + for (&set.narrow) |*p| try kernels.append(a, p.kernel()); + for (&set.tiles) |*t| { + t.prompt = &set.prompt; + try kernels.append(a, t.kernel()); + } + } +}; diff --git a/zig/tests/cuda/contract_prompt_bf16.zig b/zig/tests/cuda/contract_prompt_bf16.zig new file mode 100644 index 00000000000..37cef394668 --- /dev/null +++ b/zig/tests/cuda/contract_prompt_bf16.zig @@ -0,0 +1,83 @@ +//! BF16 prompt tiles meet both the independent FP64 projection bound and the replaced lane's bytes. +const cuda = @import("cuda"); +const contract = @import("core").contract; +const c = contract.spec; +const g = contract.gates; +const Product = @import("contract_projection_f32.zig").Product; + +const served = [_]c.Shape{ + .{ .rows = 1024, .n = 48, .k = 5120 }, + .{ .rows = 1025, .n = 96, .k = 2048 }, + .{ .rows = 129, .n = 128, .k = 4096 }, + .{ .rows = 129, .n = 640, .k = 1024 }, + .{ .rows = 129, .n = 3072, .k = 512 }, + .{ .rows = 129, .n = 70, .k = 128 }, +}; + +fn depth(shape: c.Shape) usize { + return shape.k / 16 + 24; +} + +pub const Tile = struct { + product: Product, + rig: *@import("contract_rig.zig").Rig = undefined, + prompt: *const cuda.nvfp4.Prompt, + replacement: bool = true, + control: bool = false, + base: u64 = 0, + + pub fn deinit(t: *Tile) void { + t.product.deinit(); + } + + pub fn kernel(t: *Tile) g.Kernel { + t.rig = &t.product.rig; + return .{ .ctx = t, .vt = &g.hooks(Tile), .control = if (t.control) .shapes else null, .spec = .{ + .name = if (t.control) (if (t.product.out_kind == .f32) "control: BF16 prompt fp32 scaled" else "control: BF16 prompt scaled") else if (t.replacement) (if (t.product.out_kind == .f32) "cuda BF16 prompt fp32 lane replacement" else "cuda BF16 prompt lane replacement") else if (t.product.out_kind == .f32) "cuda BF16 prompt fp32 FP64" else "cuda BF16 prompt FP64", + .accum = .f32, + .depth = depth, + .out = if (t.product.out_kind == .f32) .f32 else .bf16, + .replaces = if (t.replacement) "qmmf BF16 lane with shape-fixed K slices" else null, + .tiles = .{ .{ .size = 128 }, .{ .size = 128, .min = 1 }, .{ .size = 128, .step = 128, .min = 128 } }, + .served = &served, + } }; + } + + pub fn prepare(t: *Tile, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!try t.product.prepare(shape, fill, seed)) return false; + t.base = try t.product.rig.scratch(t.count() * t.width()); + return true; + } + + fn width(t: *const Tile) usize { + return if (t.product.out_kind == .f32) 4 else 2; + } + + pub fn run(t: *Tile) !void { + const p = &t.product; + const sh = p.d.?.shape; + var w = p.weight; + if (t.control) w.scale *= 1.5; + try t.prompt.matmulOut(p.rig.s, p.x, sh.k, sh.rows, w, p.out, p.out_kind); + try p.rig.s.synchronize(); + } + + pub fn replaced(t: *Tile) ![]const u8 { + const p = &t.product; + const sh = p.d.?.shape; + try p.lane.matmulOut(p.rig.s, p.x, sh.k, sh.rows, p.weight, t.base, p.out_kind, p.part); + return p.rig.bytes(t.base, t.count() * t.width()); + } + + pub fn count(t: *Tile) usize { + return t.product.count(); + } + + pub fn reference(t: *Tile, want: []f64, mag: []f64) !void { + return t.product.reference(want, mag); + } + + pub fn simulate(t: *Tile, acc: c.Accum, order: g.Order, out: []f64) !void { + return t.product.simulate(acc, order, out); + } +}; diff --git a/zig/tests/cuda/contract_prompt_bf16_host_test.zig b/zig/tests/cuda/contract_prompt_bf16_host_test.zig new file mode 100644 index 00000000000..bf2dd9b326f --- /dev/null +++ b/zig/tests/cuda/contract_prompt_bf16_host_test.zig @@ -0,0 +1,68 @@ +//! The device contract stays reachable and covers every K-slice plan without a GPU. +const std = @import("std"); +const cuda = @import("cuda"); +const Tile = @import("contract_prompt_bf16.zig").Tile; +const Set = @import("contract_projection_set.zig").Set; + +test "BF16 prompt contract: both bounds, byte replacements and controls retain their hooks and slice plans" { + for ([_]cuda.qmmf.Out{ .bf16, .f32 }) |out| for ([_]bool{ false, true }) |replacement| { + var tile: Tile = .{ + .product = .{ .rig = undefined, .lane = undefined, .mode = .bf16, .clusters = false, .out_kind = out }, + .prompt = undefined, + .replacement = replacement, + }; + const kernel = tile.kernel(); + std.mem.doNotOptimizeAway(kernel); + try std.testing.expectEqual(replacement, kernel.spec.replaces != null); + try std.testing.expect(kernel.vt.replaced != null); + var slices: u16 = 0; + for (kernel.spec.served) |sh| { + slices |= @as(u16, 1) << @intCast(cuda.qmmf.splitK(sh.n, sh.k)); + try std.testing.expect(sh.k % 128 == 0); + } + try std.testing.expectEqual(@as(u16, (1 << 1) | (1 << 2) | (1 << 4) | (1 << 8)), slices); + tile.control = true; + try std.testing.expectEqual(@import("core").contract.gates.Gate.shapes, tile.kernel().control.?); + }; +} + +test "BF16 prompt contract: moved registration set binds stable contexts and keeps the original prompt unchanged" { + const Mock = struct { + fn function(out: *cuda.abi.Function, _: cuda.abi.Module, name: [*:0]const u8) callconv(.c) cuda.abi.Result { + const n = std.mem.span(name); + if (!std.mem.eql(u8, n, "tf_prompt_bf16") and !std.mem.eql(u8, n, "tf_prompt_bf16_f32")) return 500; + out.* = @ptrFromInt(3); + return cuda.abi.success; + } + fn attribute(_: cuda.abi.Function, _: cuda.abi.FunctionAttribute, bytes: c_int) callconv(.c) cuda.abi.Result { + return if (bytes == 98304) cuda.abi.success else 1; + } + fn sync(_: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return cuda.abi.success; + } + }; + var d: cuda.Driver = undefined; + d.api.cuModuleGetFunction = Mock.function; + d.api.cuFuncSetAttribute = Mock.attribute; + d.api.cuStreamSynchronize = Mock.sync; + var prompt: cuda.nvfp4.Prompt = undefined; + prompt.mod = .{ .d = &d, .handle = null }; + prompt.bf16 = .{ .d = &d, .handle = @ptrFromInt(3) }; + prompt.bf16_f32 = .{ .d = &d, .handle = @ptrFromInt(4) }; + prompt.bf16_serving = false; + var lane: cuda.qmmf.Lane = undefined; + var set = try Set.init(.{ .d = &d, .ctx = undefined, .gpa = std.testing.allocator, .io = std.testing.io }, .{ .d = &d, .handle = null }, &lane, &lane, &prompt); + defer set.deinit(); + var kernels: std.ArrayList(@import("core").contract.gates.Kernel) = .empty; + defer kernels.deinit(std.testing.allocator); + try set.append(std.testing.allocator, &kernels); + try std.testing.expectEqual(@as(usize, 21), kernels.items.len); + try std.testing.expectEqual(@as(usize, 3), @intFromPtr(prompt.bf16.handle.?)); + try std.testing.expectEqual(@as(usize, 4), @intFromPtr(prompt.bf16_f32.handle.?)); + try std.testing.expect(!prompt.bf16_serving); + for (&set.tiles, kernels.items[kernels.items.len - set.tiles.len ..]) |*tile, kernel| { + try std.testing.expectEqual(@intFromPtr(tile), @intFromPtr(kernel.ctx)); + try std.testing.expect(tile.rig == &tile.product.rig); + try std.testing.expect(tile.prompt == &set.prompt); + } +} diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index 3f426be1ff4..f1938ec9b11 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -17,7 +17,7 @@ const prefill_many_k = @import("contract_qmm_prefill_many.zig"); const prefill_tile22_k = @import("contract_qmm_prefill_tile22.zig"); const mx_k = @import("contract_mxfp8.zig"); const half_k = @import("contract_lane_half.zig"); -const wide_k = @import("contract_projection_f32.zig"); +const projection_set = @import("contract_projection_set.zig"); const rank_k = @import("contract_rank.zig"); const writeback_k = @import("contract_flashnext_writeback.zig"); const hcnorm_k = @import("contract_hc_normalize.zig"); @@ -240,21 +240,9 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { }; defer for (&halves) |*h| h.deinit(); for (&halves) |*h| try kernels.append(a, h.kernel()); - var wide: [wide_k.modes.len * 2]wide_k.Product = undefined; - for (wide_k.modes, 0..) |mode, i| { - wide[i * 2] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane, .mode = mode, .clusters = true }; - wide[i * 2 + 1] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane_reduce, .mode = mode, .clusters = false }; - } - defer for (&wide) |*m| m.deinit(); - for (&wide) |*m| try kernels.append(a, m.kernel()); - var narrow: [wide_k.bf16_modes.len * 2 + 3]wide_k.Product = undefined; // bf16 out (the 27B's ModelOpt layers) - for (wide_k.bf16_modes, 0..) |mode, i| { - narrow[i * 2] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane, .mode = mode, .clusters = true, .out_kind = .bf16 }; - narrow[i * 2 + 1] = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane_reduce, .mode = mode, .clusters = false, .out_kind = .bf16 }; - } - for ([_]cuda.qmmf.Mode{ .fp8, .bf16, .bf16 }, [_]cuda.qmmf.Out{ .bf16, .bf16, .f32 }, narrow[narrow.len - 3 ..]) |mode, out, *m| m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane, .mode = mode, .clusters = true, .out_kind = out, .prompt = &prompt }; - defer for (&narrow) |*m| m.deinit(); - for (&narrow) |*m| try kernels.append(a, m.kernel()); + var projections = try projection_set.Set.init(gpu, s, &lane, &lane_reduce, &prompt); + defer projections.deinit(); + try projections.append(a, &kernels); var rank = rank_k.Rank{ .rig = .{ .gpu = gpu, .s = s }, .sum = &rank_sum }; defer rank.deinit(); try kernels.append(a, rank.kernel()); From 6548ff140d38c572aafe269d75f9a07a8e236507 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 3 Nov 2026 06:37:32 +0000 Subject: [PATCH 02/15] cuda: use the BF16 prompt tile for Dory projections Dory packs its unquantized projections in the shared BF16 lane layout and runs prompt chunks through Linear. Opt it into #1764's existing tile at the fixed 1024-row threshold; TF_CUDA_PROMPT_BF16=0 restores the lane. The required symbols stay bound and decode stays on its existing path. Exercise the actual family projection at the CUDA ABI without a device. Fresh greedy and seeded token equality and a 2K prompt timing on a GB10 remain required. Refs #1762, #1764. --- docs/recipes/cuda.md | 2 +- zig/src/families/dory/cuda_kernels.zig | 40 ++++++++++++++++++++++++++ zig/src/families/dory/cuda_model.zig | 2 +- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/docs/recipes/cuda.md b/docs/recipes/cuda.md index 45398bdc1ba..5a7cf2448c6 100644 --- a/docs/recipes/cuda.md +++ b/docs/recipes/cuda.md @@ -108,7 +108,7 @@ format ([prompt precision](#prompt-precision)): ## Native prompt controls -Qwen dense/MoE and Nemotron ModelOpt BF16 projections use the shared BF16 prompt tile from 1,024 rows. +Qwen dense/MoE, Nemotron ModelOpt and Dory BF16 projections use the shared BF16 prompt tile from 1,024 rows. `TF_CUDA_PROMPT_BF16=0` restores their lane projections; unset or any other value selects the tile. The threshold is fixed. The prompt module always binds its required BF16 symbols, including with the switch off. Flash Next keeps its own prompt selection and controls. diff --git a/zig/src/families/dory/cuda_kernels.zig b/zig/src/families/dory/cuda_kernels.zig index d9dbf1ad3fc..70f0283d644 100644 --- a/zig/src/families/dory/cuda_kernels.zig +++ b/zig/src/families/dory/cuda_kernels.zig @@ -26,6 +26,7 @@ pub const Kernels = struct { errdefer k.lane.unload(); k.prompt = try cuda.nvfp4.Prompt.load(d); errdefer k.prompt.unload(); + try k.prompt.enableBf16(); k.embed = try cuda.embed_rows.EmbedRows.load(d); errdefer k.embed.unload(); k.norms = try cuda.norms.Norms.load(d); @@ -67,6 +68,10 @@ pub const Kernels = struct { k.lane.unload(); } + pub fn linear(k: *const Kernels) cuda.qlinear.Linear { + return .{ .lane = &k.lane, .nvfp4_prompt = &k.prompt, .bf16_prompt = true }; + } + /// Each row's argmax over `v` fp32 logits, the first maximum on ties (torch.argmax), into `out` (int32 a row). pub fn argmax(k: *const Kernels, s: cuda.Stream, logits: u64, rows: usize, v: usize, out: u64) !void { if (!k.served) return error.BuiltWithoutKernels; @@ -93,3 +98,38 @@ pub const Kernels = struct { test "the serving launches type-check against the shared operators" { std.testing.refAllDecls(Kernels); } + +test "BF16 prompt port: Dory observes the threshold, cached switch and decode path" { + const Mock = struct { + var selected: usize = 0; + + fn launch(f: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + selected = @intFromPtr(f); + return cuda.abi.success; + } + + fn function(d: *const cuda.Driver, id: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; + } + }; + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Mock.launch; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + const lane_fn = Mock.function(&d, 1); + const prompt_fn = Mock.function(&d, 2); + var k: Kernels = undefined; + k.lane = .{ .mod = .{ .d = &d, .handle = null }, .fns = @splat(@splat(lane_fn)), .f32_fns = @splat(@splat(lane_fn)), .reduce = @splat(lane_fn), .half = @splat(@splat(@splat(lane_fn))), .clusters = false }; + k.prompt = .{ .mod = .{ .d = &d, .handle = null }, .fp4 = prompt_fn, .fp8 = prompt_fn, .fp4_f32 = prompt_fn, .lean = prompt_fn, .lean_f32 = prompt_fn, .sms = 16, .bf16_serving = true, .bf16 = Mock.function(&d, 3), .bf16_f32 = Mock.function(&d, 4) }; + const linear = k.linear(); + const w: cuda.qmmf.Weight = .{ .mode = .bf16, .codes = 0x2000, .scales = 0, .n = 48, .k = 5120, .npad = 128 }; + for ([_]usize{ 1023, 1024, 2048 }) |rows| { + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, rows); + try std.testing.expectEqual(@as(usize, if (rows >= 1024) 3 else 1), Mock.selected); + } + k.prompt.bf16_serving = false; + try linear.prompt(s, .{ .bf16 = w }, .{ .x = 0x1000 }, 0x3000, 2048); + try std.testing.expectEqual(@as(usize, 1), Mock.selected); + k.prompt.bf16_serving = true; + try linear.decode(s, .{ .bf16 = w }, .{ .x = 0x1000, .part = 0x4000 }, 0x3000, 1); + try std.testing.expectEqual(@as(usize, 1), Mock.selected); +} diff --git a/zig/src/families/dory/cuda_model.zig b/zig/src/families/dory/cuda_model.zig index 65375f4b280..d4cc621eab5 100644 --- a/zig/src/families/dory/cuda_model.zig +++ b/zig/src/families/dory/cuda_model.zig @@ -374,7 +374,7 @@ pub const Model = struct { /// The forward's launches over staged ids, positions and slots: no host copies, so a graph can hold them. fn launch(m: *Model, k: *const Kernels, s: cuda.Stream, n: usize, prompt: bool, p0: usize, slot: usize, fslot: usize, flat: bool, head0: usize, heads: usize) !void { const c = m.c; - const lin: cuda.qlinear.Linear = .{ .lane = &k.lane, .nvfp4_prompt = &k.prompt }; + const lin = k.linear(); const d = c.hidden; const f = c.factors(); const x = m.s; From 6212c44e5f0029dc6f3a38190f1db046d05a8c71 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:30:53 +0000 Subject: [PATCH 03/15] cuda: normalize Qwen prompt rows on the GDN chain warps Adapt #1764's staged chain-warp gated norm to Qwen dense and MoE. Retain the old recurrence and post kernels and each BF16 boundary; TF_CUDA_GDN_CHAIN_NORM=0 restores their separate launches. Register byte replacements for rows, state, sums and chunk seams with source controls. Host ABI checks pass; device and compiler gates are pending. Refs #1762, #1764. Co-authored-by: Armin <2369138+Arminova@users.noreply.github.com> --- zig/build/cuda.zig | 1 + zig/build/gdn_chain_host.zig | 20 ++ zig/kernels/cuda/contract_controls.cu | 2 + zig/kernels/cuda/gdn_prefill.cu | 2 + zig/kernels/cuda/gdn_prefill_norm.cuh | 132 +++++++++++++ zig/src/core/contract/gdn_chain_records.zig | 7 + zig/src/core/contract/registry_joins.zig | 2 +- zig/src/cuda/gdn_chain.zig | 61 ++++++ zig/src/cuda/gdn_chain_host_test.zig | 67 +++++++ zig/src/cuda/root.zig | 5 + zig/src/families/qwen3_5/cuda_forward.zig | 7 +- zig/src/families/qwen3_5/cuda_prompt.zig | 27 ++- zig/tests/cuda/contract_gdn_chain.zig | 174 ++++++++++++++++++ .../cuda/contract_gdn_chain_host_test.zig | 53 ++++++ zig/tests/cuda/contract_tests.zig | 4 + 15 files changed, 551 insertions(+), 13 deletions(-) create mode 100644 zig/build/gdn_chain_host.zig create mode 100644 zig/kernels/cuda/gdn_prefill_norm.cuh create mode 100644 zig/src/core/contract/gdn_chain_records.zig create mode 100644 zig/src/cuda/gdn_chain.zig create mode 100644 zig/src/cuda/gdn_chain_host_test.zig create mode 100644 zig/tests/cuda/contract_gdn_chain.zig create mode 100644 zig/tests/cuda/contract_gdn_chain_host_test.zig diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 7903f0ebc49..d319e96aa2b 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -242,6 +242,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st const mods = family(b, host, .ReleaseSafe, cuda, draft_ids); const mods = family(b, host, .debug, cuda, draft_ids); @import("prompt_bf16_host.zig").tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); + @import("gdn_chain_host.zig").tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); @import("cuda_checkpoint_cache_host.zig").steps(b, step); b.step("test-lfm2-load-host", "LFM2 decision model metadata and load ownership without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lfm2Module(b, host, .debug, cuda, mods.core) })).step); engines_build.qwen3HostTest(b, engines_build.qwen3Module(b, host, .debug, cuda, mods.core, mods.lanes, mods.api), step); diff --git a/zig/build/gdn_chain_host.zig b/zig/build/gdn_chain_host.zig new file mode 100644 index 00000000000..1d14520c319 --- /dev/null +++ b/zig/build/gdn_chain_host.zig @@ -0,0 +1,20 @@ +//! Focused prompt recurrence dispatch and contract checks without loading an image. +const std = @import("std"); +pub fn tests(b: *std.Build, all: *std.Build.Step, debug: *std.Build.Module, fast: *std.Build.Module, core: *std.Build.Module) void { + const step = b.step("test-gdn-chain-host", "Qwen chain norm ABI, off switch and replacement registrations without devices"); + for ([_]*std.Build.Module{ debug, fast }, [_]std.builtin.OptimizeMode{ .debug, .fast }) |cuda, mode| { + const run = b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"GDN chain port:"} })); + run.has_side_effects = true; + step.dependOn(&run.step); + const fixture = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/contract_gdn_chain_host_test.zig"), + .target = b.graph.host, + .optimize = mode, + .link_libc = true, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } }, + }) })); + fixture.has_side_effects = true; + step.dependOn(&fixture.step); + } + all.dependOn(step); +} diff --git a/zig/kernels/cuda/contract_controls.cu b/zig/kernels/cuda/contract_controls.cu index cbd3041caf4..6060f998174 100644 --- a/zig/kernels/cuda/contract_controls.cu +++ b/zig/kernels/cuda/contract_controls.cu @@ -492,3 +492,5 @@ extern "C" __global__ void __launch_bounds__(256, 1) tf_ctl_pattn_64(const __nv_ } } // namespace tf_prefill_attention #include "contract_ctl_router.cuh" +#define TF_GDN_CHAIN_CONTROLS +#include "gdn_prefill.cu" diff --git a/zig/kernels/cuda/gdn_prefill.cu b/zig/kernels/cuda/gdn_prefill.cu index b4e05a968d4..3cfa4dc5d28 100644 --- a/zig/kernels/cuda/gdn_prefill.cu +++ b/zig/kernels/cuda/gdn_prefill.cu @@ -148,3 +148,5 @@ __global__ void __launch_bounds__(2 * ROWS) chain_kernel( template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, __nv_bfloat16, 64, 32>(const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const float* __restrict__, const __nv_bfloat16* __restrict__, const float*, float*, __nv_bfloat16* __restrict__, int, int, int); + +#include "gdn_prefill_norm.cuh" diff --git a/zig/kernels/cuda/gdn_prefill_norm.cuh b/zig/kernels/cuda/gdn_prefill_norm.cuh new file mode 100644 index 00000000000..dabf1aea7cc --- /dev/null +++ b/zig/kernels/cuda/gdn_prefill_norm.cuh @@ -0,0 +1,132 @@ +// Qwen whole-head prompt chain: the recurrence's eight warps also normalize its staged BF16 rows. +#pragma once +#include "common/reduce.cuh" + +namespace tf_gdn_prefill { + +template +__device__ __forceinline__ void chain_norm( + const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const __nv_bfloat16* __restrict__ v, + const float* __restrict__ g, const __nv_bfloat16* __restrict__ beta, const float* state, + float* last, __nv_bfloat16* __restrict__ y, int W, int hk, int hv, + const __nv_bfloat16* __restrict__ z, const __nv_bfloat16* __restrict__ nw, + __nv_bfloat16* __restrict__ mix, float* __restrict__ xs, float eps) { + using QK = __nv_bfloat16; + using B = __nv_bfloat16; + constexpr int ROWS = 128, STEPS = 16; + __shared__ __align__(16) __nv_bfloat16 ys[STEPS][DV]; + __shared__ float4 ks[STEPS][DK / 4], qs[STEPS][DK / 4]; + __shared__ float gs[STEPS], bs[STEPS]; + __shared__ __align__(16) __nv_bfloat16 vs[STEPS][ROWS]; + const int head = blockIdx.x, row = threadIdx.x >> 1, half = threadIdx.x & 1; + const int key_head = head / (hv / hk); + float s[64]; + const float* s0 = state + (static_cast(head) * DV + row) * DK; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 t = *reinterpret_cast(s0 + 8 * j + 4 * half); + s[4 * j] = t.x; s[4 * j + 1] = t.y; s[4 * j + 2] = t.z; s[4 * j + 3] = t.w; + } + Prefetch pf; // each stage's loads in flight during the one before + pf.fetch(q, k, v, g, beta, 0, W, hk, hv, head, key_head, 0); + for (int t0 = 0; t0 < W; t0 += STEPS) { + const int n = min(STEPS, W - t0); + __syncthreads(); + pf.store(ks, qs, gs, bs, vs); + __syncthreads(); + if (t0 + STEPS < W) pf.fetch(q, k, v, g, beta, t0 + STEPS, W, hk, hv, head, key_head, 0); + for (int tt = 0; tt < n; ++tt) { + const float gt = gs[tt], bt = bs[tt]; + const size_t vat = (static_cast(t0 + tt) * hv + head) * DV + row; + const float vt = __bfloat162float(vs[tt][threadIdx.x >> 1]); + float m[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 kk = ks[tt][2 * j + half]; + s[4 * j] = s[4 * j] * gt; + s[4 * j + 1] = s[4 * j + 1] * gt; + s[4 * j + 2] = s[4 * j + 2] * gt; + s[4 * j + 3] = s[4 * j + 3] * gt; + m[0] = __fmaf_rn(s[4 * j], kk.x, m[0]); + m[1] = __fmaf_rn(s[4 * j + 1], kk.y, m[1]); + m[2] = __fmaf_rn(s[4 * j + 2], kk.z, m[2]); + m[3] = __fmaf_rn(s[4 * j + 3], kk.w, m[3]); + } + float mem = (m[0] + m[1]) + (m[2] + m[3]); + mem = mem + __shfl_xor_sync(0xffffffffu, mem, 1); + const float delta = (vt - mem) * bt; + float o[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 kk = ks[tt][2 * j + half], qq = qs[tt][2 * j + half]; + s[4 * j] = __fmaf_rn(kk.x, delta, s[4 * j]); + s[4 * j + 1] = __fmaf_rn(kk.y, delta, s[4 * j + 1]); + s[4 * j + 2] = __fmaf_rn(kk.z, delta, s[4 * j + 2]); + s[4 * j + 3] = __fmaf_rn(kk.w, delta, s[4 * j + 3]); + o[0] = __fmaf_rn(s[4 * j], qq.x, o[0]); + o[1] = __fmaf_rn(s[4 * j + 1], qq.y, o[1]); + o[2] = __fmaf_rn(s[4 * j + 2], qq.z, o[2]); + o[3] = __fmaf_rn(s[4 * j + 3], qq.w, o[3]); + } + float out = (o[0] + o[1]) + (o[2] + o[3]); + out = out + __shfl_xor_sync(0xffffffffu, out, 1); + if (half == 0) { + const __nv_bfloat16 rounded = __float2bfloat16_rn(out); + y[vat] = rounded; + ys[tt][row] = rounded; + } + } + __syncthreads(); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + for (int tt = warp; tt < n; tt += 8) { + const size_t at = (static_cast(t0 + tt) * hv + head) * DV; + float yv[4], ss = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + yv[j] = __bfloat162float(ys[tt][lane * 4 + j]); + ss += yv[j] * yv[j]; + } + ss = tf_common::warp_sum(ss); + const float inv = rsqrtf(ss / static_cast(DV) + eps); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = lane * 4 + j; + const float x = __bfloat162float(__float2bfloat16_rn(__bfloat162float(nw[d]) * (yv[j] * inv))); + const float zf = __bfloat162float(z[at + d]); + const __nv_bfloat16 o = __float2bfloat16_rn((Fault == 1 ? 1.0f : zf / (1.0f + expf(-zf))) * x); + mix[at + d] = o; + ys[tt][d] = o; + } + if (xs != nullptr) { + __syncwarp(); + if (lane < DV / 64) { + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < 64; ++j) sum += __bfloat162float(ys[tt][lane * 64 + j]); + xs[at / 64 + lane] = sum; + } + } + } + } + float* s1 = last + (static_cast(head) * DV + (Fault == 2 ? (row + 1) % DV : row)) * DK; +#pragma unroll + for (int j = 0; j < 16; ++j) + *reinterpret_cast(s1 + 8 * j + 4 * half) = make_float4(s[4 * j], s[4 * j + 1], s[4 * j + 2], + s[4 * j + 3]); +} + +} // namespace tf_gdn_prefill + +#define TF_GDN_NORM_ENTRY(NAME, FAULT) \ +extern "C" __global__ void __launch_bounds__(256) NAME( \ + const __nv_bfloat16* q, const __nv_bfloat16* k, const __nv_bfloat16* v, const float* g, \ + const __nv_bfloat16* beta, const float* state, float* last, __nv_bfloat16* y, int W, int hk, int hv, \ + const __nv_bfloat16* z, const __nv_bfloat16* nw, __nv_bfloat16* mix, float* xs, float eps) { \ + tf_gdn_prefill::chain_norm(q, k, v, g, beta, state, last, y, W, hk, hv, z, nw, mix, xs, eps); \ +} +TF_GDN_NORM_ENTRY(tf_gdn_chain_norm, 0) +#ifdef TF_GDN_CHAIN_CONTROLS +TF_GDN_NORM_ENTRY(tf_gdn_chain_norm_bad_gate, 1) +TF_GDN_NORM_ENTRY(tf_gdn_chain_norm_bad_state, 2) +#endif +#undef TF_GDN_NORM_ENTRY diff --git a/zig/src/core/contract/gdn_chain_records.zig b/zig/src/core/contract/gdn_chain_records.zig new file mode 100644 index 00000000000..28867f1881a --- /dev/null +++ b/zig/src/core/contract/gdn_chain_records.zig @@ -0,0 +1,7 @@ +//! Whole-head chain and its unchanged baseline launches; compile usage must come from the device builder. +const registry = @import("registry.zig"); +pub const records = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "gdn_prefill tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "gdn_prefill", .threads = 256 }, .usage = registry.none }, + .{ .launch = .{ .name = "gdn_prefill chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "gdn_prefill", .threads = 128 }, .usage = registry.none }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_post", .symbol = "tf_q35_gdn_post", .image = "qwen35", .threads = 32 }, .usage = registry.none }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 6b4e5f243ef..05a8a90dd13 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -49,7 +49,7 @@ pub const nvcc_133_after = @import("flashnext_tile_records.zig").cuda_133 ++ @import("nvfp4_experts32_records.zig").cuda_133 ++ @import("paging_pending.zig").cuda_133 ++ @import("experts_bf16_records.zig").cuda_133; -pub const cuda_pending = @import("qwen_whole_records.zig").records ++ +pub const cuda_pending = @import("gdn_chain_records.zig").records ++ @import("qwen_whole_records.zig").records ++ @import("flashnext_tile_records.zig").pending ++ @import("exl3_prompt_pending.zig").records ++ @import("nemotron_draw_records.zig").records ++ diff --git a/zig/src/cuda/gdn_chain.zig b/zig/src/cuda/gdn_chain.zig new file mode 100644 index 00000000000..f5b239fb6f9 --- /dev/null +++ b/zig/src/cuda/gdn_chain.zig @@ -0,0 +1,61 @@ +//! Qwen prompt recurrence: the old half-head chain, or its whole-head chain and staged gated norm. +const std = @import("std"); +const module = @import("module.zig"); +const launch = @import("launch.zig"); +const Stream = @import("stream.zig").Stream; + +pub const old_symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii"; +pub const symbol = "tf_gdn_chain_norm"; + +pub const Buffers = struct { + q: u64, + k: u64, + v: u64, + g: u64, + beta: u64, + state: u64, + last: u64, + y: u64, + z: u64, + norm: u64, + mix: u64, + sums: u64 = 0, +}; + +pub const Chain = struct { + old: module.Function, + fused: ?module.Function = null, + + pub fn resolve(mod: module.Module) !Chain { + return resolveMode(mod, enabled()); + } + + pub fn enabled() bool { + const value = std.c.getenv("TF_CUDA_GDN_CHAIN_NORM"); + return enabledValue(if (value) |v| std.mem.span(v) else null); + } + + pub fn enabledValue(value: ?[]const u8) bool { + return value == null or !std.mem.eql(u8, value.?, "0"); + } + + pub fn resolveMode(mod: module.Module, on: bool) !Chain { + return .{ .old = try mod.function(old_symbol), .fused = if (on) try mod.function(symbol) else null }; + } + + /// Returns whether the norm was written; false requires the caller's original post launch. + pub fn run(f: Chain, s: Stream, b: Buffers, rows: usize, hk: usize, hv: usize, eps: f32) !bool { + if (rows == 0 or hk == 0 or hv == 0 or hv % hk != 0) return error.BadGdnChainShape; + var a: launch.Args = .{}; + for ([_]u64{ b.q, b.k, b.v, b.g, b.beta, b.state, b.last, b.y }) |v| a.add(v); + for ([_]usize{ rows, hk, hv }) |v| a.add(@as(c_int, @intCast(v))); + if (f.fused) |kernel| { + for ([_]u64{ b.z, b.norm, b.mix, b.sums }) |v| a.add(v); + a.add(eps); + try launch.launch(kernel, .{ .grid = .{ .x = @intCast(hv) }, .block = .{ .x = 256 } }, s, &a); + return true; + } + try launch.launch(f.old, .{ .grid = .{ .x = @intCast(hv), .y = 2 }, .block = .{ .x = 128 } }, s, &a); + return false; + } +}; diff --git a/zig/src/cuda/gdn_chain_host_test.zig b/zig/src/cuda/gdn_chain_host_test.zig new file mode 100644 index 00000000000..bf4582847e0 --- /dev/null +++ b/zig/src/cuda/gdn_chain_host_test.zig @@ -0,0 +1,67 @@ +//! Real chain dispatch and symbol binding recorded at the driver ABI, without a device. +const std = @import("std"); +const cuda = @import("root.zig"); +const chain = @import("gdn_chain.zig"); +const Mock = struct { + var id: usize = 0; + var grid: [3]u32 = undefined; + var block: [3]u32 = undefined; + var args: [16]u64 = undefined; + var bindings: usize = 0; + fn bind(out: *cuda.abi.Function, _: cuda.abi.Module, name: [*:0]const u8) callconv(.c) cuda.abi.Result { + const old = std.mem.eql(u8, std.mem.span(name), chain.old_symbol); + if (!old and !std.mem.eql(u8, std.mem.span(name), chain.symbol)) return 1; + out.* = @ptrFromInt(if (old) @as(usize, 1) else 2); + bindings += 1; + return 0; + } + fn launch(f: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, by: c_uint, bz: c_uint, sm: c_uint, _: cuda.abi.Stream, p: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + id = @intFromPtr(f); + grid = .{ gx, gy, gz }; + block = .{ bx, by, bz }; + if (sm != 0) return 1; + for (0..@as(usize, if (id == 1) 11 else 16)) |i| args[i] = if (i < 8 or (i >= 11 and i < 15)) @as(*align(1) const u64, @ptrCast(p.?[i].?)).* else @as(*align(1) const u32, @ptrCast(p.?[i].?)).*; + return 0; + } +}; +test "GDN chain port: off binds only the old symbol; on binds the fused kernel" { + try std.testing.expect(chain.Chain.enabledValue(null)); + try std.testing.expect(chain.Chain.enabledValue("1")); + try std.testing.expect(!chain.Chain.enabledValue("0")); + var d: cuda.Driver = undefined; + d.api.cuModuleGetFunction = Mock.bind; + const mod: cuda.Module = .{ .d = &d, .handle = null }; + for ([_]bool{ false, true }) |on| { + Mock.bindings = 0; + const f = try chain.Chain.resolveMode(mod, on); + try std.testing.expectEqual(@as(usize, if (on) 2 else 1), Mock.bindings); + try std.testing.expectEqual(on, f.fused != null); + } +} +test "GDN chain port: staged boundaries, family head groups, in-place state and optional sums keep the ABI" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Mock.launch; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + const b: chain.Buffers = .{ .q = 0x1000, .k = 0x2000, .v = 0x3000, .g = 0x4000, .beta = 0x5000, .state = 0x6000, .last = 0x6000, .y = 0x7000, .z = 0x8000, .norm = 0x9000, .mix = 0xa000, .sums = 0xb000 }; + for ([_]usize{ 1, 15, 16, 17, 31, 32, 33, 64, 65, 512, 2048 }) |rows| for ([_][2]usize{ .{ 16, 32 }, .{ 16, 48 }, .{ 16, 64 }, .{ 16, 128 } }) |heads| for ([_]bool{ false, true }) |on| { + const f: chain.Chain = .{ .old = .{ .d = &d, .handle = @ptrFromInt(1) }, .fused = if (on) .{ .d = &d, .handle = @ptrFromInt(2) } else null }; + try std.testing.expectEqual(on, try f.run(s, b, rows, heads[0], heads[1], 1e-6)); + try std.testing.expectEqual(@as(usize, if (on) 2 else 1), Mock.id); + try std.testing.expectEqual([3]u32{ @intCast(heads[1]), if (on) 1 else 2, 1 }, Mock.grid); + try std.testing.expectEqual([3]u32{ if (on) 256 else 128, 1, 1 }, Mock.block); + try std.testing.expectEqualSlices(u64, &.{ b.q, b.k, b.v, b.g, b.beta, b.state, b.last, b.y }, Mock.args[0..8]); + try std.testing.expectEqualSlices(u64, &.{ rows, heads[0], heads[1] }, Mock.args[8..11]); + if (on) { + try std.testing.expectEqualSlices(u64, &.{ b.z, b.norm, b.mix, b.sums }, Mock.args[11..15]); + try std.testing.expectEqual(@as(u64, @as(u32, @bitCast(@as(f32, 1e-6)))), Mock.args[15]); + var no_sums = b; + no_sums.sums = 0; + no_sums.last = 0xc000; + try std.testing.expect(try f.run(s, no_sums, rows, heads[0], heads[1], 1e-5)); + try std.testing.expectEqual(@as(u64, 0), Mock.args[14]); + try std.testing.expectEqual(no_sums.last, Mock.args[6]); + } + }; + const f: chain.Chain = .{ .old = .{ .d = &d, .handle = @ptrFromInt(1) } }; + for ([_][3]usize{ .{ 0, 16, 32 }, .{ 16, 0, 32 }, .{ 16, 16, 0 }, .{ 16, 16, 33 } }) |sh| try std.testing.expectError(error.BadGdnChainShape, f.run(s, b, sh[0], sh[1], sh[2], 1e-6)); +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 998f61a2a58..095dbae30f8 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -192,3 +192,8 @@ test { _ = @import("graph_instantiate_failure_test.zig"); } pub const qwen35_bf16_rows = @import("qwen35_bf16_rows.zig"); + +pub const gdn_chain = @import("gdn_chain.zig"); +test { + _ = @import("gdn_chain_host_test.zig"); +} diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 56ab6e16352..999ec4362a4 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -99,8 +99,11 @@ pub fn body(e: *E.Engine, shape: anytype) !void { try e.runPdl(e.fns.gdn_pre, .{ 1, 2 * g.k_heads + g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.qkv, t_segs, t_rows, t_par, layer, m.conv, e.a, e.b, m.a_log, m.dt_bias, e.q, e.k, e.v, e.g_, e.beta, t_params }); // one recorded window of 2+ rows: gdn_pre logged its tails, conv_commit would only return if (!(record and nseg == 1 and total > 1)) try e.run(e.fns.conv_commit, .{ (g.convWidth() + 255) / 256, nseg, 1 }, .{ 256, 1, 1 }, .{ geo, e.qkv, t_segs, t_par, layer, t_params }); - if (prompt and nseg == 1) try @import("cuda_prompt.zig").delta(e, di, total) else try e.deltaScan(record, shape.slots, nseg, layer); - try e.runPdl(e.fns.gdn_post, .{ 1, g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.y, e.z, m.norm, g.eps, e.mix, t_params, sums }); + const norm_done = if (prompt and nseg == 1) try @import("cuda_prompt.zig").delta(e, di, total, m.norm, sums) else blk: { + try e.deltaScan(record, shape.slots, nseg, layer); + break :blk false; + }; + if (!norm_done) try e.runPdl(e.fns.gdn_post, .{ 1, g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.y, e.z, m.norm, g.eps, e.mix, t_params, sums }); try e.projAgain(m.out, e.mix, e.r, total, prompt); di += 1; }, diff --git a/zig/src/families/qwen3_5/cuda_prompt.zig b/zig/src/families/qwen3_5/cuda_prompt.zig index d6e4fdd0bb2..c7d5f51ca19 100644 --- a/zig/src/families/qwen3_5/cuda_prompt.zig +++ b/zig/src/families/qwen3_5/cuda_prompt.zig @@ -14,7 +14,7 @@ pub const page_ids: u32 = 768; const hpc = 2; const block_rows = 16 * (8 / hpc); -pub const Fns = struct { bf16: cuda.Function, fp8: cuda.Function, bf16_whole: cuda.Function, fp8_whole: cuda.Function, bf16_p256: cuda.Function, bf16_p256_ids: cuda.Function, chain: cuda.Function }; +pub const Fns = struct { bf16: cuda.Function, fp8: cuda.Function, bf16_whole: cuda.Function, fp8_whole: cuda.Function, bf16_p256: cuda.Function, bf16_p256_ids: cuda.Function, chain: cuda.gdn_chain.Chain }; pub const symbols = struct { pub const bf16 = "_ZN20tf_prefill_attention13hpattn_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi"; @@ -25,11 +25,9 @@ pub const symbols = struct { pub const bf16_p256_ids = "_ZN20tf_prefill_attention22hpattn_p256_ids_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi"; pub const chain = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii"; }; -/// gdn_prefill.cu's value rows a block (two threads a row). -const chain_rows = 64; pub fn resolve(attention: cuda.Module, gdn: cuda.Module) !Fns { - const f: Fns = .{ .bf16 = try attention.function(symbols.bf16), .fp8 = try attention.function(symbols.fp8), .bf16_whole = try attention.function(symbols.bf16_whole), .fp8_whole = try attention.function(symbols.fp8_whole), .bf16_p256 = try attention.function(symbols.bf16_p256), .bf16_p256_ids = try attention.function(symbols.bf16_p256_ids), .chain = try gdn.function(symbols.chain) }; + const f: Fns = .{ .bf16 = try attention.function(symbols.bf16), .fp8 = try attention.function(symbols.fp8), .bf16_whole = try attention.function(symbols.bf16_whole), .fp8_whole = try attention.function(symbols.fp8_whole), .bf16_p256 = try attention.function(symbols.bf16_p256), .bf16_p256_ids = try attention.function(symbols.bf16_p256_ids), .chain = try cuda.gdn_chain.Chain.resolve(gdn) }; try f.bf16.allowDynamicShared(smem); try f.fp8.allowDynamicShared(smem); try f.bf16_whole.allowDynamicShared(smem); @@ -101,15 +99,24 @@ pub fn runFrom(e: *E.Engine, layer: usize, from: usize, end: usize) !void { } /// Linear layer `layer`'s delta rule: e.q, e.k, e.v, e.g_, e.beta into e.y, the stream's recurrence updated in place. -pub fn delta(e: *E.Engine, layer: usize, rows: usize) !void { +pub fn delta(e: *E.Engine, layer: usize, rows: usize, norm: u64, sums: u64) !bool { const g = e.g; const sg = std.mem.bytesToValue(Seg, e.staged.bytes[E.Engine.segs_at..][0..@sizeOf(Seg)]); const state = sg.rec + layer * g.v_heads * geometry.dk * geometry.dk * 4; - var a: cuda.Args = .{}; - for ([_]u64{ e.q, e.k, e.v, e.g_, e.beta, state, state, e.y }) |v| a.add(v); - for ([_]usize{ rows, g.k_heads, g.v_heads }) |v| a.add(@as(c_int, @intCast(v))); - const cfg: cuda.Config = .{ .grid = .{ .x = @intCast(g.v_heads), .y = @intCast(geometry.dk / chain_rows) }, .block = .{ .x = 2 * chain_rows } }; - try cuda.launch.launch(e.prompt_attn.chain, cfg, e.stream, &a); + return e.prompt_attn.chain.run(e.stream, .{ + .q = e.q, + .k = e.k, + .v = e.v, + .g = e.g_, + .beta = e.beta, + .state = state, + .last = state, + .y = e.y, + .z = e.z, + .norm = norm, + .mix = e.mix, + .sums = sums, + }, rows, g.k_heads, g.v_heads, g.eps); } test "Qwen prompt layout: whole ABI omits page metadata and keeps original layer and head strides" { diff --git a/zig/tests/cuda/contract_gdn_chain.zig b/zig/tests/cuda/contract_gdn_chain.zig new file mode 100644 index 00000000000..a16f915507f --- /dev/null +++ b/zig/tests/cuda/contract_gdn_chain.zig @@ -0,0 +1,174 @@ +//! Whole-head GDN chain, raw rows, state, gated rows and sums byte-equal to the original two launches. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const c = core.contract.spec; +const g = core.contract.gates; +const chain = cuda.gdn_chain; +const Geo = extern struct { hid: c_int = 2048, nk: c_int, nv: c_int, qh: c_int = 16, kvh: c_int = 2, nl: c_int = 1 }; +const eps: f32 = 1e-6; + +pub const Control = enum { none, gate, state }; +fn depth(_: c.Shape) usize { + return 0; +} +pub const served = [_]c.Shape{ + .{ .rows = 1, .n = 16, .k = 32 }, .{ .rows = 17, .n = 16, .k = 48 }, + .{ .rows = 33, .n = 16, .k = 64 }, .{ .rows = 65, .n = 16, .k = 128 }, + .{ .rows = 512, .n = 16, .k = 32 }, .{ .rows = 2048, .n = 16, .k = 48 }, +}; +pub const Case = struct { + rig: rig_.Rig, + f: chain.Chain, + post: cuda.Function, + sums: bool = false, + chunks: bool = false, + control: Control = .none, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + ins: [8]u64 = @splat(0), + output: u64 = 0, + base: u64 = 0, + seen: std.ArrayList(u8) = .empty, + + pub fn deinit(t: *Case) void { + t.seen.deinit(t.rig.gpu.gpa); + t.rig.deinit(); + } + pub fn kernel(t: *Case) g.Kernel { + return .{ .ctx = t, .vt = &g.hooks(Case), .control = if (t.control == .none) null else .shapes, .spec = .{ + .name = switch (t.control) { + .gate => "control: GDN chain without SiLU gate", + .state => "control: GDN chain rotating final state", + .none => if (t.chunks) (if (t.sums) "cuda GDN chain norm chunk seams and sums" else "cuda GDN chain norm chunk seams") else if (t.sums) "cuda GDN chain norm with sums" else "cuda GDN chain norm", + }, + .accum = .none, + .depth = depth, + .out = .raw, + .nan = .{ .stated = "every raw row, gated row, state and optional group sum equals the old chain then post bytes" }, + .replaces = "chain_kernel then tf_q35_gdn_post", + .tiles = .{ .{ .size = 16 }, .{}, .{} }, + .served = &served, + } }; + } + fn input(t: *Case, i: usize, len: usize, floats: bool, fill: g.Fill, rng: std.Random) !void { + const a = t.rig.gpu.gpa; + const bytes = try a.alloc(u8, len * @as(usize, if (floats) 4 else 2)); + defer a.free(bytes); + for (0..len) |j| { + var v = (rng.float(f32) - 0.5) * (if (i == 5) @as(f32, 0.05) else 0.5); + if (i == 3) v = 0.95 + rng.float(f32) * 0.04; + if (i == 4) v = 0.25 + rng.float(f32) * 0.5; + if (i == 7) v = 0.5 + rng.float(f32); + if (fill == .nonfinite and j < 3) v = switch (j) { + 0 => std.math.nan(f32), + 1 => std.math.inf(f32), + else => -std.math.inf(f32), + }; + if (floats) std.mem.writeInt(u32, bytes[j * 4 ..][0..4], @bitCast(v), .little) else std.mem.writeInt(u16, bytes[j * 2 ..][0..2], c.toBf16(v), .little); + } + t.ins[i] = try t.rig.input(bytes); + } + pub fn prepare(t: *Case, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k % shape.n != 0) return false; + t.rig.reset(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const r = prng.random(); + const rows = shape.rows; + const hk = shape.n; + const hv = shape.k; + const lens = [_]usize{ rows * hk * 128, rows * hk * 128, rows * hv * 128, rows * hv, rows * hv, hv * 128 * 128, rows * hv * 128, 128 }; + for (lens, 0..) |len, i| try t.input(i, len, i == 3 or i == 5, fill, r); + t.output = try t.rig.output(t.count()); + t.base = try t.rig.scratch(t.count()); + return true; + } + pub fn count(t: *Case) usize { + const s = t.shape; + return 2 * s.rows * s.k * 128 * 2 + s.k * 128 * 128 * 4 + (if (t.sums) s.rows * s.k * 2 * 4 else 0); + } + fn buffers(t: *Case, ptr: u64) chain.Buffers { + const width = t.shape.rows * t.shape.k * 128 * 2; + const state = ptr + 2 * width; + return .{ .q = t.ins[0], .k = t.ins[1], .v = t.ins[2], .g = t.ins[3], .beta = t.ins[4], .state = state, .last = state, .y = ptr, .z = t.ins[6], .norm = t.ins[7], .mix = ptr + width, .sums = if (t.sums) state + t.shape.k * 128 * 128 * 4 else 0 }; + } + fn resetState(t: *Case, b: chain.Buffers) !void { + const len = t.shape.k * 128 * 128 * 4; + const state: cuda.DeviceBuffer = .{ .d = t.rig.gpu.d, .ptr = b.state, .len = len }; + try state.copyFrom(0, t.ins[5], len, t.rig.s.handle); + } + pub fn run(t: *Case) !void { + var b = t.buffers(t.output); + try t.resetState(b); + var at: usize = 0; + while (at < t.shape.rows) { + const n = @min(t.shape.rows - at, if (t.chunks) @as(usize, 17) else t.shape.rows); + if (!try t.f.run(t.rig.s, b, n, t.shape.n, t.shape.k, eps)) return error.FusedKernelNotBound; + at += n; + b.q += n * t.shape.n * 128 * 2; + b.k += n * t.shape.n * 128 * 2; + b.v += n * t.shape.k * 128 * 2; + b.g += n * t.shape.k * 4; + b.beta += n * t.shape.k * 2; + b.y += n * t.shape.k * 128 * 2; + b.z += n * t.shape.k * 128 * 2; + b.mix += n * t.shape.k * 128 * 2; + if (b.sums != 0) b.sums += n * t.shape.k * 2 * 4; + } + try t.rig.s.synchronize(); + } + pub fn replaced(t: *Case) ![]const u8 { + const b = t.buffers(t.base); + try t.resetState(b); + var old = t.f; + old.fused = null; + _ = try old.run(t.rig.s, b, t.shape.rows, t.shape.n, t.shape.k, eps); + var args: cuda.Args = .{}; + args.add(Geo{ .nk = @intCast(t.shape.n), .nv = @intCast(t.shape.k) }); + for ([_]u64{ b.y, b.z, b.norm }) |v| args.add(v); + args.add(eps); + args.add(b.mix); + args.add(@as(u64, 0)); + args.add(b.sums); + try cuda.launch.launch(t.post, .{ .grid = .{ .y = @intCast(t.shape.k), .z = @intCast(t.shape.rows) }, .block = .{ .x = 32 } }, t.rig.s, &args); + return t.rig.bytes(t.base, t.count()); + } + pub fn check(t: *Case, _: g.Gate) !?[]const u8 { + t.seen.clearRetainingCapacity(); + try t.seen.appendSlice(t.rig.gpu.gpa, try t.rig.outputBytes()); + return if (std.mem.eql(u8, t.seen.items, try t.replaced())) null else "GDN bytes differ from the original chain and post"; + } + pub fn reference(_: *Case, _: []f64, _: []f64) !void { + return error.ReplacementOnly; + } +}; + +pub const Suite = struct { + gdn: cuda.Module, + qwen: cuda.Module, + cases: [6]Case, + pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, controls: cuda.Module) !Suite { + var gd = try cuda.Module.load(gpu.d, cuda.kernels.gdn_prefill); + errdefer gd.unload(); + var qw = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); + errdefer qw.unload(); + const f = try chain.Chain.resolveMode(gd, true); + const post = try qw.function("tf_q35_gdn_post"); + var cases: [6]Case = undefined; + for (&cases, 0..) |*case, i| { + var fns = f; + if (i >= 4) fns.fused = try controls.function(if (i == 4) "tf_gdn_chain_norm_bad_gate" else "tf_gdn_chain_norm_bad_state"); + case.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns, .post = post, .sums = i % 2 == 1 or i >= 4, .chunks = i == 2 or i == 3, .control = if (i == 4) .gate else if (i == 5) .state else .none }; + } + return .{ .gdn = gd, .qwen = qw, .cases = cases }; + } + pub fn append(t: *Suite, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + for (&t.cases) |*case| try list.append(a, case.kernel()); + } + pub fn deinit(t: *Suite) void { + for (&t.cases) |*case| case.deinit(); + t.qwen.unload(); + t.gdn.unload(); + } +}; diff --git a/zig/tests/cuda/contract_gdn_chain_host_test.zig b/zig/tests/cuda/contract_gdn_chain_host_test.zig new file mode 100644 index 00000000000..77c04d9b9ca --- /dev/null +++ b/zig/tests/cuda/contract_gdn_chain_host_test.zig @@ -0,0 +1,53 @@ +//! The device replacement and planted controls are live; no driver calls run here. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const suite = @import("contract_gdn_chain.zig"); +const g = core.contract.gates; + +export fn gdn_chain_contract_hooks(t: *suite.Case) *const g.VTable { + return t.kernel().vt; +} + +export fn gdn_chain_suite_compile(gpu: *const @import("check.zig").Gpu, s: *const cuda.Stream, m: *const cuda.Module) void { + var cases = suite.Suite.init(gpu.*, s.*, m.*) catch return; + defer cases.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(gpu.gpa); + cases.append(gpu.gpa, &list) catch return; +} + +test "GDN chain port: raw byte registration retains every output and both source controls" { + var t: suite.Case = undefined; + t.sums = false; + t.chunks = false; + t.control = .none; + t.shape = .{ .rows = 33, .n = 16, .k = 48 }; + const bytes = 2 * 33 * 48 * 128 * 2 + 48 * 128 * 128 * 4; + try std.testing.expectEqual(@as(usize, bytes), t.count()); + const k = t.kernel(); + try std.testing.expect(k.vt.replaced != null and k.vt.check != null and k.spec.replaces != null); + t.sums = true; + try std.testing.expectEqual(@as(usize, bytes + 33 * 48 * 2 * 4), t.count()); + for ([_]suite.Control{ .gate, .state }) |control| { + t.control = control; + try std.testing.expectEqual(g.Gate.shapes, t.kernel().control.?); + } + var found: usize = 0; + for (core.contract.registry.all_cuda) |r| if (std.mem.eql(u8, r.launch.symbol, cuda.gdn_chain.symbol)) { + found += 1; + try std.testing.expectEqual(@as(u32, 256), r.launch.threads); + try std.testing.expectEqual(core.contract.registry.none, r.usage); + }; + try std.testing.expectEqual(@as(usize, 1), found); +} + +test "GDN chain port: source control witnesses distinguish the SiLU and head-state placement" { + const y: f64 = 0.75; + const gate: f64 = 0.25; + const production = y * gate / (1 + @exp(-gate)); + try std.testing.expect(@abs(production - y) > 0.5); + const state = [_]u32{ 0x3f810000, 0x3f820000, 0x3f830000, 0x3f840000 }; + const rotated = [_]u32{ state[3], state[0], state[1], state[2] }; + try std.testing.expect(!std.mem.eql(u32, &state, &rotated)); +} diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index f1938ec9b11..155e6c9ccdc 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -43,6 +43,7 @@ const w4a8_k = @import("contract_w4a8.zig"); const round_k = @import("contract_tree_round.zig"); const act_k = @import("contract_act.zig"); const vit_g4_group = @import("contract_gemma_group.zig"); +const chain_k = @import("contract_gdn_chain.zig"); const gdn_k = @import("contract_gdn.zig"); const qk_k = @import("contract_qk.zig"); const wrows_k = @import("contract_window_rows.zig"); @@ -240,6 +241,9 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { }; defer for (&halves) |*h| h.deinit(); for (&halves) |*h| try kernels.append(a, h.kernel()); + var chain_suite = try chain_k.Suite.init(gpu, s, mods[5]); + defer chain_suite.deinit(); + try chain_suite.append(a, &kernels); var projections = try projection_set.Set.init(gpu, s, &lane, &lane_reduce, &prompt); defer projections.deinit(); try projections.append(a, &kernels); From dbdabc9cb82247a31eeb427481d13fd2d8e0973b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:49:23 +0000 Subject: [PATCH 04/15] cuda: schedule Qwen router expert blocks first Adapt #1764's expert-first grid to Qwen MoE's 16-row router. Retain each original FP32 FMA chain and the row-first kernel; TF_CUDA_MOE_EXPERT_FIRST=0 restores its symbol and launch grid. Add FP64 and byte-replacement contracts, padded/live-row cases and a source row-coupling control. Complete shared contract image routing, keep callback tables static, and compile GDN controls with the production chain so their compiler flags match. Device qualification is pending. Refs #1762, #1764. Co-authored-by: Armin <2369138+Arminova@users.noreply.github.com> --- zig/build/cuda.zig | 4 +- zig/build/moe_router_host.zig | 20 +++ zig/kernels/cuda/contract_controls.cu | 3 + zig/kernels/cuda/gdn_prefill.cu | 1 + zig/kernels/cuda/moe.cu | 2 + zig/kernels/cuda/moe_router_expert.cuh | 43 +++++ zig/src/core/contract/moe_router_records.zig | 5 + zig/src/core/contract/registry_joins.zig | 2 +- zig/src/cuda/moe.zig | 20 ++- zig/src/cuda/moe_router_host_test.zig | 66 +++++++ zig/src/cuda/root.zig | 4 + zig/tests/cuda/contract_gdn_chain.zig | 8 +- .../cuda/contract_gdn_chain_host_test.zig | 2 +- zig/tests/cuda/contract_limits.zig | 2 +- zig/tests/cuda/contract_moe_router.zig | 163 ++++++++++++++++++ .../cuda/contract_moe_router_host_test.zig | 63 +++++++ zig/tests/cuda/contract_tests.zig | 4 + 17 files changed, 400 insertions(+), 12 deletions(-) create mode 100644 zig/build/moe_router_host.zig create mode 100644 zig/kernels/cuda/moe_router_expert.cuh create mode 100644 zig/src/core/contract/moe_router_records.zig create mode 100644 zig/src/cuda/moe_router_host_test.zig create mode 100644 zig/tests/cuda/contract_moe_router.zig create mode 100644 zig/tests/cuda/contract_moe_router_host_test.zig diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index d319e96aa2b..3f872c68a62 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -241,8 +241,8 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st runtime_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda })).step); const mods = family(b, host, .ReleaseSafe, cuda, draft_ids); const mods = family(b, host, .debug, cuda, draft_ids); - @import("prompt_bf16_host.zig").tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); - @import("gdn_chain_host.zig").tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); + inline for (.{ @import("prompt_bf16_host.zig"), @import("gdn_chain_host.zig"), @import("moe_router_host.zig") }) |suite| + suite.tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); @import("cuda_checkpoint_cache_host.zig").steps(b, step); b.step("test-lfm2-load-host", "LFM2 decision model metadata and load ownership without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lfm2Module(b, host, .debug, cuda, mods.core) })).step); engines_build.qwen3HostTest(b, engines_build.qwen3Module(b, host, .debug, cuda, mods.core, mods.lanes, mods.api), step); diff --git a/zig/build/moe_router_host.zig b/zig/build/moe_router_host.zig new file mode 100644 index 00000000000..f17a86db102 --- /dev/null +++ b/zig/build/moe_router_host.zig @@ -0,0 +1,20 @@ +//! Qwen router grid dispatch and FP64 cancellation witnesses without a CUDA device. +const std = @import("std"); +pub fn tests(b: *std.Build, all: *std.Build.Step, debug: *std.Build.Module, fast: *std.Build.Module, core: *std.Build.Module) void { + const step = b.step("test-moe-router-host", "Expert-first router ABI, old-path switch and independent reference fixtures"); + for ([_]*std.Build.Module{ debug, fast }, [_]std.builtin.OptimizeMode{ .debug, .fast }) |cuda, mode| { + const run = b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"MoE router port:"} })); + run.has_side_effects = true; + step.dependOn(&run.step); + const fixture = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/contract_moe_router_host_test.zig"), + .target = b.graph.host, + .optimize = mode, + .link_libc = true, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } }, + }) })); + fixture.has_side_effects = true; + step.dependOn(&fixture.step); + } + all.dependOn(step); +} diff --git a/zig/kernels/cuda/contract_controls.cu b/zig/kernels/cuda/contract_controls.cu index 6060f998174..4f7411bd646 100644 --- a/zig/kernels/cuda/contract_controls.cu +++ b/zig/kernels/cuda/contract_controls.cu @@ -494,3 +494,6 @@ extern "C" __global__ void __launch_bounds__(256, 1) tf_ctl_pattn_64(const __nv_ #include "contract_ctl_router.cuh" #define TF_GDN_CHAIN_CONTROLS #include "gdn_prefill.cu" + +#define TF_MOE_ROUTER_CONTROLS +#include "moe_router_expert.cuh" diff --git a/zig/kernels/cuda/gdn_prefill.cu b/zig/kernels/cuda/gdn_prefill.cu index 3cfa4dc5d28..cc683a18203 100644 --- a/zig/kernels/cuda/gdn_prefill.cu +++ b/zig/kernels/cuda/gdn_prefill.cu @@ -149,4 +149,5 @@ template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, __nv_bfloat const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const float* __restrict__, const __nv_bfloat16* __restrict__, const float*, float*, __nv_bfloat16* __restrict__, int, int, int); +#define TF_GDN_CHAIN_CONTROLS #include "gdn_prefill_norm.cuh" diff --git a/zig/kernels/cuda/moe.cu b/zig/kernels/cuda/moe.cu index e2312f0a37c..2c25a341544 100644 --- a/zig/kernels/cuda/moe.cu +++ b/zig/kernels/cuda/moe.cu @@ -42,6 +42,8 @@ extern "C" __global__ void __launch_bounds__(256) tf_moe_router(const __nv_bfloa if (row0 + rr < R && e0 + ee < E) OUT[static_cast(row0 + rr) * E + e0 + ee] = acc; } +#include "moe_router_expert.cuh" + namespace { constexpr int MAXC = 8; // experts a lane holds: up to 256 routed experts diff --git a/zig/kernels/cuda/moe_router_expert.cuh b/zig/kernels/cuda/moe_router_expert.cuh new file mode 100644 index 00000000000..2c5317a829b --- /dev/null +++ b/zig/kernels/cuda/moe_router_expert.cuh @@ -0,0 +1,43 @@ +// Expert blocks first for Qwen's 16-row router; each dot retains the original FMA chain. +#pragma once +#include +#include +namespace tf_moe_expert_first { +constexpr int TILE = 16, KC = 256; +template +__device__ __forceinline__ void router(const __nv_bfloat16* __restrict__ X, int x_stride, + const __nv_bfloat16* __restrict__ W, float* __restrict__ OUT, + int R, int D, int E, const int* __restrict__ P) { + if (P != nullptr) R = min(R, P[2]); + if (static_cast(blockIdx.y) * TILE >= R) return; + __shared__ __nv_bfloat16 xs[TILE][KC + 2]; + __shared__ __nv_bfloat16 ws[TILE][KC + 2]; + const int row0 = blockIdx.y * TILE, e0 = blockIdx.x * TILE; + const int rr = threadIdx.x / TILE, ee = threadIdx.x % TILE; + float acc = 0.0f; + for (int k0 = 0; k0 < D; k0 += KC) { + __syncthreads(); + for (int c = threadIdx.x; c < TILE * KC; c += 256) { + const int r = c / KC, k = c % KC; + const bool kin = k0 + k < D; + xs[r][k] = kin && row0 + r < R ? X[static_cast(row0 + (BadRows ? 0 : r)) * x_stride + k0 + k] : __float2bfloat16_rn(0.0f); + ws[r][k] = kin && e0 + r < E ? W[static_cast(e0 + r) * D + k0 + k] : __float2bfloat16_rn(0.0f); + } + __syncthreads(); + const int kn = min(KC, D - k0); + for (int k = 0; k < kn; ++k) acc = __fmaf_rn(__bfloat162float(xs[rr][k]), __bfloat162float(ws[ee][k]), acc); + } + if (row0 + rr < R && e0 + ee < E) OUT[static_cast(row0 + rr) * E + e0 + ee] = acc; +} + +} // namespace tf_moe_expert_first +#define TF_MOE_EXPERT_ENTRY(NAME, BAD) \ +extern "C" __global__ void __launch_bounds__(256) NAME( \ + const __nv_bfloat16* x, int stride, const __nv_bfloat16* w, float* out, int rows, int dims, int experts, const int* p) { \ + tf_moe_expert_first::router(x, stride, w, out, rows, dims, experts, p); \ +} +TF_MOE_EXPERT_ENTRY(tf_moe_router_expert_first, false) +#ifdef TF_MOE_ROUTER_CONTROLS +TF_MOE_EXPERT_ENTRY(tf_moe_router_expert_bad_rows, true) +#endif +#undef TF_MOE_EXPERT_ENTRY diff --git a/zig/src/core/contract/moe_router_records.zig b/zig/src/core/contract/moe_router_records.zig new file mode 100644 index 00000000000..644b2443e5d --- /dev/null +++ b/zig/src/core/contract/moe_router_records.zig @@ -0,0 +1,5 @@ +//! Expert-first router launch; usage stays pending until compiled on each supported SM. +const registry = @import("registry.zig"); +pub const records = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "moe tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "moe", .threads = 256 }, .usage = registry.none }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 05a8a90dd13..e5dfd5392a1 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -49,7 +49,7 @@ pub const nvcc_133_after = @import("flashnext_tile_records.zig").cuda_133 ++ @import("nvfp4_experts32_records.zig").cuda_133 ++ @import("paging_pending.zig").cuda_133 ++ @import("experts_bf16_records.zig").cuda_133; -pub const cuda_pending = @import("gdn_chain_records.zig").records ++ @import("qwen_whole_records.zig").records ++ +pub const cuda_pending = @import("moe_router_records.zig").records ++ @import("gdn_chain_records.zig").records ++ @import("qwen_whole_records.zig").records ++ @import("flashnext_tile_records.zig").pending ++ @import("exl3_prompt_pending.zig").records ++ @import("nemotron_draw_records.zig").records ++ diff --git a/zig/src/cuda/moe.zig b/zig/src/cuda/moe.zig index 2cfb3ea3b5e..1cf85dc42ff 100644 --- a/zig/src/cuda/moe.zig +++ b/zig/src/cuda/moe.zig @@ -14,18 +14,28 @@ pub const max_top_k = 31; pub const Fns = struct { router_fn: Function, + router_expert: ?Function = null, topk_fn: Function, combine_fn: Function, router_tiles_fn: Function, /// From the loaded moe module (kernels.moe). pub fn resolve(mod: Module) !Fns { - return .{ .router_fn = try mod.function("tf_moe_router"), .topk_fn = try mod.function("tf_moe_topk"), .combine_fn = try mod.function("tf_moe_combine"), .router_tiles_fn = try mod.function("tf_moe_router_tiles") }; + const value = std.c.getenv("TF_CUDA_MOE_EXPERT_FIRST"); + return resolveMode(mod, expertFirst(if (value) |v| std.mem.span(v) else null)); + } + + pub fn expertFirst(value: ?[]const u8) bool { + return value == null or !std.mem.eql(u8, value.?, "0"); + } + + pub fn resolveMode(mod: Module, on: bool) !Fns { + return .{ .router_fn = try mod.function("tf_moe_router"), .router_expert = if (on) try mod.function("tf_moe_router_expert_first") else null, .topk_fn = try mod.function("tf_moe_topk"), .combine_fn = try mod.function("tf_moe_combine"), .router_tiles_fn = try mod.function("tf_moe_router_tiles") }; } /// logits[r][e] = fp32 x[r] . w[e], the gate last; `params` word 2 caps rows; wide calls on the same-bits tiles. pub fn route(f: Fns, s: Stream, x: u64, x_stride: usize, rows: usize, w: u64, logits: u64, dims: usize, count: usize, params: u64) !void { - if (tiled(x, x_stride, w, rows, dims)) return f.routeTiles(s, x, rows, w, logits, dims, count, params); + if (f.router_expert == null and tiled(x, x_stride, w, rows, dims)) return f.routeTiles(s, x, rows, w, logits, dims, count, params); var a: launch_.Args = .{}; a.add(x); a.add(int(x_stride)); @@ -33,8 +43,10 @@ pub const Fns = struct { a.add(logits); for ([_]usize{ rows, dims, count }) |v| a.add(int(v)); a.add(params); - const cfg: launch_.Config = .{ .grid = .{ .x = @intCast((rows + 15) / 16), .y = @intCast((count + 15) / 16), .z = 1 }, .block = .{ .x = 256 } }; - try launch_.launch(f.router_fn, cfg, s, &a); + const rt: u32 = @intCast((rows + 15) / 16); + const et: u32 = @intCast((count + 15) / 16); + const cfg: launch_.Config = .{ .grid = if (f.router_expert != null) .{ .x = et, .y = rt } else .{ .x = rt, .y = et }, .block = .{ .x = 256 } }; + try launch_.launch(f.router_expert orelse f.router_fn, cfg, s, &a); } /// Each row's top-k picks and bf16-rounded weights ([rows][top_k + 1]); slot top_k is the shared expert. diff --git a/zig/src/cuda/moe_router_host_test.zig b/zig/src/cuda/moe_router_host_test.zig new file mode 100644 index 00000000000..669c9c77e46 --- /dev/null +++ b/zig/src/cuda/moe_router_host_test.zig @@ -0,0 +1,66 @@ +//! Router symbols and grid order at the actual CUDA ABI, without executing a kernel. +const std = @import("std"); +const cuda = @import("root.zig"); +const Mock = struct { + var id: usize = 0; + var grid: [3]u32 = undefined; + var args: [8]u64 = undefined; + var bindings: usize = 0; + fn bind(out: *cuda.abi.Function, _: cuda.abi.Module, name: [*:0]const u8) callconv(.c) cuda.abi.Result { + const names = [_][]const u8{ "tf_moe_router", "tf_moe_router_expert_first", "tf_moe_topk", "tf_moe_combine" }; + for (names, 1..) |n, i| if (std.mem.eql(u8, n, std.mem.span(name))) { + out.* = @ptrFromInt(i); + bindings += 1; + return 0; + }; + return 1; + } + fn launch(f: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, by: c_uint, bz: c_uint, sm: c_uint, _: cuda.abi.Stream, p: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + id = @intFromPtr(f); + grid = .{ gx, gy, gz }; + if (bx != 256 or by != 1 or bz != 1 or sm != 0) return 1; + for (0..8) |i| args[i] = if (i == 0 or i == 2 or i == 3 or i == 7) @as(*align(1) const u64, @ptrCast(p.?[i].?)).* else @as(*align(1) const u32, @ptrCast(p.?[i].?)).*; + return 0; + } +}; +test "MoE router port: off avoids the new symbol and restores the row-first grid" { + try std.testing.expect(cuda.moe.Fns.expertFirst(null)); + try std.testing.expect(cuda.moe.Fns.expertFirst("1")); + try std.testing.expect(!cuda.moe.Fns.expertFirst("0")); + var d: cuda.Driver = undefined; + d.api.cuModuleGetFunction = Mock.bind; + d.api.cuLaunchKernel = Mock.launch; + const mod: cuda.Module = .{ .d = &d, .handle = null }; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + for ([_]bool{ false, true }) |on| { + Mock.bindings = 0; + const f = try cuda.moe.Fns.resolveMode(mod, on); + try std.testing.expectEqual(@as(usize, if (on) 4 else 3), Mock.bindings); + for ([_]usize{ 1, 15, 16, 17, 31, 32, 33, 128, 512, 1024, 2048 }) |rows| for ([_]usize{ 1, 15, 16, 17, 255, 256, 257 }) |experts| for ([_]usize{ 128, 2048, 2055 }) |dims| for ([_]u64{ 0, 0xbeef }) |params| { + try f.route(s, 0x1000, dims + 16, rows, 0x2000, 0x3000, dims, experts, params); + try std.testing.expectEqual(@as(usize, if (on) 2 else 1), Mock.id); + const rt: u32 = @intCast((rows + 15) / 16); + const et: u32 = @intCast((experts + 15) / 16); + try std.testing.expectEqual([3]u32{ if (on) et else rt, if (on) rt else et, 1 }, Mock.grid); + try std.testing.expectEqualSlices(u64, &.{ 0x1000, dims + 16, 0x2000, 0x3000, rows, dims, experts, params }, &Mock.args); + }; + } +} + +test "MoE router port: expert-first coordinates cover each row and expert tile once" { + for ([_][2]usize{ .{ 17, 257 }, .{ 33, 17 }, .{ 2048, 257 } }) |sh| { + const rt = (sh[0] + 15) / 16; + const et = (sh[1] + 15) / 16; + const seen = try std.testing.allocator.alloc(bool, rt * et); + defer std.testing.allocator.free(seen); + @memset(seen, false); + for (0..rt * et) |block| { + const row = block / et; + const expert = block % et; + const at = row * et + expert; + try std.testing.expect(!seen[at]); + seen[at] = true; + } + for (seen) |v| try std.testing.expect(v); + } +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 095dbae30f8..13509191b1f 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -197,3 +197,7 @@ pub const gdn_chain = @import("gdn_chain.zig"); test { _ = @import("gdn_chain_host_test.zig"); } + +test { + _ = @import("moe_router_host_test.zig"); +} diff --git a/zig/tests/cuda/contract_gdn_chain.zig b/zig/tests/cuda/contract_gdn_chain.zig index a16f915507f..a476a99e6a1 100644 --- a/zig/tests/cuda/contract_gdn_chain.zig +++ b/zig/tests/cuda/contract_gdn_chain.zig @@ -36,7 +36,7 @@ pub const Case = struct { t.rig.deinit(); } pub fn kernel(t: *Case) g.Kernel { - return .{ .ctx = t, .vt = &g.hooks(Case), .control = if (t.control == .none) null else .shapes, .spec = .{ + return .{ .ctx = t, .vt = &vt, .control = if (t.control == .none) null else .shapes, .spec = .{ .name = switch (t.control) { .gate => "control: GDN chain without SiLU gate", .state => "control: GDN chain rotating final state", @@ -45,12 +45,14 @@ pub const Case = struct { .accum = .none, .depth = depth, .out = .raw, + .in_place = true, .nan = .{ .stated = "every raw row, gated row, state and optional group sum equals the old chain then post bytes" }, .replaces = "chain_kernel then tf_q35_gdn_post", .tiles = .{ .{ .size = 16 }, .{}, .{} }, .served = &served, } }; } + const vt = g.hooks(Case); fn input(t: *Case, i: usize, len: usize, floats: bool, fill: g.Fill, rng: std.Random) !void { const a = t.rig.gpu.gpa; const bytes = try a.alloc(u8, len * @as(usize, if (floats) 4 else 2)); @@ -148,7 +150,7 @@ pub const Suite = struct { gdn: cuda.Module, qwen: cuda.Module, cases: [6]Case, - pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, controls: cuda.Module) !Suite { + pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, _: cuda.Module) !Suite { var gd = try cuda.Module.load(gpu.d, cuda.kernels.gdn_prefill); errdefer gd.unload(); var qw = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); @@ -158,7 +160,7 @@ pub const Suite = struct { var cases: [6]Case = undefined; for (&cases, 0..) |*case, i| { var fns = f; - if (i >= 4) fns.fused = try controls.function(if (i == 4) "tf_gdn_chain_norm_bad_gate" else "tf_gdn_chain_norm_bad_state"); + if (i >= 4) fns.fused = try gd.function(if (i == 4) "tf_gdn_chain_norm_bad_gate" else "tf_gdn_chain_norm_bad_state"); case.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns, .post = post, .sums = i % 2 == 1 or i >= 4, .chunks = i == 2 or i == 3, .control = if (i == 4) .gate else if (i == 5) .state else .none }; } return .{ .gdn = gd, .qwen = qw, .cases = cases }; diff --git a/zig/tests/cuda/contract_gdn_chain_host_test.zig b/zig/tests/cuda/contract_gdn_chain_host_test.zig index 77c04d9b9ca..fd0a246d6c3 100644 --- a/zig/tests/cuda/contract_gdn_chain_host_test.zig +++ b/zig/tests/cuda/contract_gdn_chain_host_test.zig @@ -26,7 +26,7 @@ test "GDN chain port: raw byte registration retains every output and both source const bytes = 2 * 33 * 48 * 128 * 2 + 48 * 128 * 128 * 4; try std.testing.expectEqual(@as(usize, bytes), t.count()); const k = t.kernel(); - try std.testing.expect(k.vt.replaced != null and k.vt.check != null and k.spec.replaces != null); + try std.testing.expect(k.vt.replaced != null and k.vt.check != null and k.spec.replaces != null and k.spec.in_place); t.sums = true; try std.testing.expectEqual(@as(usize, bytes + 33 * 48 * 2 * 4), t.count()); for ([_]suite.Control{ .gate, .state }) |control| { diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 2cce732c70e..8bb1f969206 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -31,7 +31,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "tree_round", "act_rows", "gdn_prep", "gdn_prefill", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; diff --git a/zig/tests/cuda/contract_moe_router.zig b/zig/tests/cuda/contract_moe_router.zig new file mode 100644 index 00000000000..ce7c4d4d5be --- /dev/null +++ b/zig/tests/cuda/contract_moe_router.zig @@ -0,0 +1,163 @@ +//! Expert-first Qwen router against the frozen row-first kernel and independent FP64 dots. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const c = core.contract.spec; +const g = core.contract.gates; +const Dense = core.contract.dense.Dense; +fn depth(s: c.Shape) usize { + return s.k; +} +pub const served = [_]c.Shape{ + .{ .rows = 17, .n = 257, .k = 2048 }, .{ .rows = 33, .n = 257, .k = 4096 }, + .{ .rows = 128, .n = 257, .k = 2055 }, .{ .rows = 2048, .n = 257, .k = 2048 }, +}; + +pub const Inputs = struct { + d: Dense, + weights: []u16, + x: []u16, + stride: usize, + pub fn init(a: std.mem.Allocator, s: c.Shape, pad: usize, fill: g.Fill, seed: u64) !Inputs { + const d = try Dense.init(a, s, 1); + errdefer d.deinit(); + d.fillX(fill, seed, 4); + const w = try a.alloc(u16, d.w.len); + errdefer a.free(w); + var prng = std.Random.DefaultPrng.init(seed ^ 0x77); + const r = prng.random(); + for (w, 0..) |*v, i| { + const k = i % s.k; + const z: f32 = if (fill == .stress) @floatFromInt(1 + ((k % (s.k / 2)) * 7 + i / s.k) % 7) else r.float(f32) * 2 - 1; + v.* = c.toBf16(if (fill == .stress and k >= s.k / 2) -z else z); + } + for (d.w, w) |*v, b| v.* = c.fromBf16(b); + const stride = s.k + pad; + const x = try a.alloc(u16, s.rows * stride); + @memset(x, 0x7fc1); + for (0..s.rows) |row| @memcpy(x[row * stride ..][0..s.k], d.x[row * s.k ..][0..s.k]); + return .{ .d = d, .weights = w, .x = x, .stride = stride }; + } + pub fn deinit(t: Inputs) void { + t.d.a.free(t.x); + t.d.a.free(t.weights); + t.d.deinit(); + } +}; + +pub const Case = struct { + rig: @import("contract_rig.zig").Rig, + f: cuda.moe.Fns, + replacement: bool = true, + live: bool = false, + pad: usize = 0, + control: bool = false, + data: ?Inputs = null, + p: [5]u64 = @splat(0), + seen: std.ArrayList(u8) = .empty, + pub fn deinit(t: *Case) void { + if (t.data) |d| d.deinit(); + t.seen.deinit(t.rig.gpu.gpa); + t.rig.deinit(); + } + pub fn kernel(t: *Case) g.Kernel { + return .{ .ctx = t, .vt = if (t.live) &raw else &numeric, .control = if (t.control) .shapes else null, .spec = .{ + .name = if (t.control) "control: MoE expert-first router reads row zero" else if (t.live) "cuda MoE expert-first live rows replacement" else if (!t.replacement) "cuda MoE expert-first router FP64" else if (t.pad != 0) "cuda MoE expert-first padded input replacement" else "cuda MoE expert-first router replacement", + .out = if (t.live) .raw else .f32, + .accum = if (t.live) .none else .f32, + .depth = depth, + .nan = if (t.live) .{ .stated = "all bytes equal the old router, including unwritten bucket padding" } else .propagate, + .replaces = if (t.replacement) "tf_moe_router" else null, + .tiles = .{ .{ .size = 16 }, .{ .size = 16 }, .{ .size = 256 } }, + .served = &served, + } }; + } + const raw = g.hooks(Case); + const numeric = blk: { + var vt = raw; + vt.check = null; + break :blk vt; + }; + pub fn prepare(t: *Case, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.n == 0 or s.k == 0) return false; + if (t.data) |d| d.deinit(); + t.data = null; + t.rig.reset(); + t.data = try Inputs.init(t.rig.gpu.gpa, s, t.pad, fill, seed); + const d = &t.data.?; + t.p[0] = try t.rig.input(std.mem.sliceAsBytes(d.x)); + t.p[1] = try t.rig.input(std.mem.sliceAsBytes(d.weights)); + t.p[2] = try t.rig.output(d.d.outputs() * 4); + t.p[3] = try t.rig.scratch(d.d.outputs() * 4); + const params = [3]i32{ 0, 0, @intCast(s.rows - @as(usize, if (t.live) 1 else 0)) }; + t.p[4] = if (t.live) try t.rig.input(std.mem.sliceAsBytes(¶ms)) else 0; + return true; + } + fn launch(t: *Case, old: bool, output: u64) !void { + const d = t.data.?; + const s = d.d.shape; + var f = t.f; + if (old) f.router_expert = null; + try f.route(t.rig.s, t.p[0], d.stride, s.rows, t.p[1], output, s.k, s.n, t.p[4]); + try t.rig.s.synchronize(); + } + pub fn run(t: *Case) !void { + return t.launch(false, t.p[2]); + } + pub fn replaced(t: *Case) ![]const u8 { + const len = t.data.?.d.outputs() * 4; + const b: cuda.DeviceBuffer = .{ .d = t.rig.gpu.d, .ptr = t.p[3], .len = len }; + try b.fill8(0xff, t.rig.s.handle); + try t.launch(true, t.p[3]); + return t.rig.bytes(t.p[3], len); + } + pub fn check(t: *Case, _: g.Gate) !?[]const u8 { + if (!t.live) return t.classes(); + t.seen.clearRetainingCapacity(); + try t.seen.appendSlice(t.rig.gpu.gpa, try t.rig.outputBytes()); + return if (std.mem.eql(u8, t.seen.items, try t.replaced())) null else "router live/padding bytes differ from the old path"; + } + fn classes(t: *Case) !?[]const u8 { + const a = t.rig.gpu.gpa; + const n = t.data.?.d.outputs(); + const values = try a.alloc(f64, n * 2); + defer a.free(values); + try t.reference(values[0..n], values[n..]); + const out = try t.rig.outputBytes(); + for (values[0..n], 0..) |v, i| if (c.classOf(c.read(.f32, out, i)) != c.classOf(v)) return "router classes differ from FP64"; + return null; + } + pub fn count(t: *Case) usize { + return t.data.?.d.outputs() * @as(usize, if (t.live) 4 else 1); + } + pub fn reference(t: *Case, want: []f64, mag: []f64) !void { + return t.data.?.d.reference(want, mag); + } + pub fn simulate(t: *Case, acc: c.Accum, order: g.Order, out: []f64) !void { + return t.data.?.d.simulate(acc, order, out); + } +}; + +pub const Suite = struct { + mod: cuda.Module, + cases: [5]Case, + pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, controls: cuda.Module) !Suite { + var mod = try cuda.Module.load(gpu.d, cuda.kernels.moe); + errdefer mod.unload(); + const f = try cuda.moe.Fns.resolveMode(mod, true); + var cases: [5]Case = undefined; + for (&cases, 0..) |*case, i| { + var fns = f; + if (i == 4) fns.router_expert = try controls.function("tf_moe_router_expert_bad_rows"); + case.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns, .replacement = i != 1, .pad = if (i == 2 or i == 3) 16 else 0, .live = i == 3, .control = i == 4 }; + } + return .{ .mod = mod, .cases = cases }; + } + pub fn append(t: *Suite, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + for (&t.cases) |*case| try list.append(a, case.kernel()); + } + pub fn deinit(t: *Suite) void { + for (&t.cases) |*case| case.deinit(); + t.mod.unload(); + } +}; diff --git a/zig/tests/cuda/contract_moe_router_host_test.zig b/zig/tests/cuda/contract_moe_router_host_test.zig new file mode 100644 index 00000000000..c20c12e70ca --- /dev/null +++ b/zig/tests/cuda/contract_moe_router_host_test.zig @@ -0,0 +1,63 @@ +//! The router fixture's cancellation and row-coupling witnesses, without a device. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const suite = @import("contract_moe_router.zig"); +const g = core.contract.gates; + +export fn moe_router_suite_compile(gpu: *const @import("check.zig").Gpu, s: *const cuda.Stream, m: *const cuda.Module) void { + var cases = suite.Suite.init(gpu.*, s.*, m.*) catch return; + defer cases.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(gpu.gpa); + cases.append(gpu.gpa, &list) catch return; +} +test "MoE router port: independent FP64 hooks and raw live-row byte hooks stay distinct" { + var t: suite.Case = undefined; + t.replacement = false; + t.live = false; + t.pad = 0; + t.control = false; + const fp64 = t.kernel(); + try std.testing.expect(fp64.spec.replaces == null and fp64.vt.check == null and fp64.vt.simulate != null); + t.live = true; + t.replacement = true; + const live = t.kernel(); + try std.testing.expect(live.vt.check != null and live.vt.replaced != null); + try std.testing.expectEqual(core.contract.spec.Elem.raw, live.spec.out); +} +test "MoE router port: padded tails are NaN and the real fixture exposes coupled rows" { + const input = try suite.Inputs.init(std.testing.allocator, .{ .rows = 3, .n = 17, .k = 257 }, 16, .random, 49); + defer input.deinit(); + var want: [51]f64 = undefined; + var mag: [51]f64 = undefined; + try input.d.reference(&want, &mag); + try std.testing.expect(!std.mem.eql(f64, want[0..17], want[17..34])); + for (0..3) |row| for (input.x[row * input.stride + 257 ..][0..16]) |v| try std.testing.expectEqual(@as(u16, 0x7fc1), v); + const input_nf = try suite.Inputs.init(std.testing.allocator, .{ .rows = 5, .n = 17, .k = 257 }, 0, .nonfinite, 9); + defer input_nf.deinit(); + var nf: [85]f64 = undefined; + var nm: [85]f64 = undefined; + try input_nf.d.reference(&nf, &nm); + try std.testing.expect(std.math.isNan(nf[0])); +} +test "MoE router port: production stress fixture is exact in FP32 and rejects reduced sums in every order" { + const input = try suite.Inputs.init(std.testing.allocator, .{ .rows = 4, .n = 17, .k = 4096 }, 0, .stress, 31); + defer input.deinit(); + var want: [68]f64 = undefined; + var mag: [68]f64 = undefined; + var got: [68]f64 = undefined; + try input.d.reference(&want, &mag); + for ([_]g.Order{ .sequential, .pairwise, .strided }) |order| { + try input.d.simulate(.f32, order, &got); + try std.testing.expectEqualSlices(f64, &want, &got); + for ([_]core.contract.spec.Accum{ .f16, .bf16 }) |acc| { + try input.d.simulate(acc, order, &got); + var red = false; + for (got, want) |actual, expected| if (!std.math.isFinite(actual) or @abs(actual - expected) > 100 * @abs(expected) * 0x1p-24) { + red = true; + }; + try std.testing.expect(red); + } + } +} diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index 155e6c9ccdc..c4b35969537 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -43,6 +43,7 @@ const w4a8_k = @import("contract_w4a8.zig"); const round_k = @import("contract_tree_round.zig"); const act_k = @import("contract_act.zig"); const vit_g4_group = @import("contract_gemma_group.zig"); +const moe_router_k = @import("contract_moe_router.zig"); const chain_k = @import("contract_gdn_chain.zig"); const gdn_k = @import("contract_gdn.zig"); const qk_k = @import("contract_qk.zig"); @@ -241,6 +242,9 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { }; defer for (&halves) |*h| h.deinit(); for (&halves) |*h| try kernels.append(a, h.kernel()); + var router_suite = try moe_router_k.Suite.init(gpu, s, mods[5]); + defer router_suite.deinit(); + try router_suite.append(a, &kernels); var chain_suite = try chain_k.Suite.init(gpu, s, mods[5]); defer chain_suite.deinit(); try chain_suite.append(a, &kernels); From c99538b1cf19d6f61c086fb46a3d014e91c972ea Mon Sep 17 00:00:00 2001 From: akol1 <15747200+akol1@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:34:25 -0800 Subject: [PATCH 05/15] cuda: retain BF16 prompt contract callbacks beyond registration (cherry picked from commit d8f5efbc9352fec063e496cc158b73c1372bf64c) --- zig/tests/cuda/contract_prompt_bf16.zig | 3 ++- zig/tests/cuda/contract_prompt_bf16_host_test.zig | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/zig/tests/cuda/contract_prompt_bf16.zig b/zig/tests/cuda/contract_prompt_bf16.zig index 37cef394668..91adcc6b248 100644 --- a/zig/tests/cuda/contract_prompt_bf16.zig +++ b/zig/tests/cuda/contract_prompt_bf16.zig @@ -19,6 +19,7 @@ fn depth(shape: c.Shape) usize { } pub const Tile = struct { + pub const callbacks = g.hooks(Tile); product: Product, rig: *@import("contract_rig.zig").Rig = undefined, prompt: *const cuda.nvfp4.Prompt, @@ -32,7 +33,7 @@ pub const Tile = struct { pub fn kernel(t: *Tile) g.Kernel { t.rig = &t.product.rig; - return .{ .ctx = t, .vt = &g.hooks(Tile), .control = if (t.control) .shapes else null, .spec = .{ + return .{ .ctx = t, .vt = &callbacks, .control = if (t.control) .shapes else null, .spec = .{ .name = if (t.control) (if (t.product.out_kind == .f32) "control: BF16 prompt fp32 scaled" else "control: BF16 prompt scaled") else if (t.replacement) (if (t.product.out_kind == .f32) "cuda BF16 prompt fp32 lane replacement" else "cuda BF16 prompt lane replacement") else if (t.product.out_kind == .f32) "cuda BF16 prompt fp32 FP64" else "cuda BF16 prompt FP64", .accum = .f32, .depth = depth, diff --git a/zig/tests/cuda/contract_prompt_bf16_host_test.zig b/zig/tests/cuda/contract_prompt_bf16_host_test.zig index bf2dd9b326f..f2a51a5e206 100644 --- a/zig/tests/cuda/contract_prompt_bf16_host_test.zig +++ b/zig/tests/cuda/contract_prompt_bf16_host_test.zig @@ -66,3 +66,12 @@ test "BF16 prompt contract: moved registration set binds stable contexts and kee try std.testing.expect(tile.prompt == &set.prompt); } } + +test "BF16 prompt contract: callback storage survives the registration call" { + var tile: Tile = .{ + .product = .{ .rig = undefined, .lane = undefined, .mode = .bf16, .clusters = false }, + .prompt = undefined, + }; + const registered = tile.kernel(); + try std.testing.expect(registered.vt == &Tile.callbacks); +} From 52604c183bd2622b3e4d6791bd7f67066baf227e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:07:11 -0800 Subject: [PATCH 06/15] contract: record Qwen prompt glue launches for nvcc 13.0 Fill the four five-SM launch receipts from nvcc 13.0.88. Keep later compiler records pending and test the real registry lookups and limits. --- zig/src/core/contract/gdn_chain_records.zig | 8 +-- zig/src/core/contract/moe_router_records.zig | 4 +- .../core/contract/qwen_glue_receipts_test.zig | 49 +++++++++++++++++++ zig/src/core/contract/registry.zig | 1 + 4 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 zig/src/core/contract/qwen_glue_receipts_test.zig diff --git a/zig/src/core/contract/gdn_chain_records.zig b/zig/src/core/contract/gdn_chain_records.zig index 28867f1881a..01596ff65c5 100644 --- a/zig/src/core/contract/gdn_chain_records.zig +++ b/zig/src/core/contract/gdn_chain_records.zig @@ -1,7 +1,7 @@ -//! Whole-head chain and its unchanged baseline launches; compile usage must come from the device builder. +//! Whole-head chain and baseline launch resource records. const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "gdn_prefill tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "gdn_prefill", .threads = 256 }, .usage = registry.none }, - .{ .launch = .{ .name = "gdn_prefill chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "gdn_prefill", .threads = 128 }, .usage = registry.none }, - .{ .launch = .{ .name = "qwen35 tf_q35_gdn_post", .symbol = "tf_q35_gdn_post", .image = "qwen35", .threads = 32 }, .usage = registry.none }, + .{ .launch = .{ .name = "gdn_prefill tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "gdn_prefill", .threads = 256 }, .usage = .{ .{ .regs = 176, .static = 24704, .bound = 256 }, .{ .regs = 184, .static = 24704, .bound = 256 }, .{ .regs = 184, .static = 24704, .bound = 256 }, .{ .regs = 183, .static = 24704, .bound = 256 }, .{ .regs = 183, .static = 24704, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "gdn_prefill chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "gdn_prefill", .threads = 128 }, .usage = .{ .{ .regs = 229, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_post", .symbol = "tf_q35_gdn_post", .image = "qwen35", .threads = 32 }, .usage = .{ .{ .regs = 28, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 } }, .later_pending = true }, }; diff --git a/zig/src/core/contract/moe_router_records.zig b/zig/src/core/contract/moe_router_records.zig index 644b2443e5d..e27d5a55f60 100644 --- a/zig/src/core/contract/moe_router_records.zig +++ b/zig/src/core/contract/moe_router_records.zig @@ -1,5 +1,5 @@ -//! Expert-first router launch; usage stays pending until compiled on each supported SM. +//! Expert-first router launch resource records. const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "moe tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "moe", .threads = 256 }, .usage = registry.none }, + .{ .launch = .{ .name = "moe tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "moe", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 } }, .later_pending = true }, }; diff --git a/zig/src/core/contract/qwen_glue_receipts_test.zig b/zig/src/core/contract/qwen_glue_receipts_test.zig new file mode 100644 index 00000000000..2aed374fb5b --- /dev/null +++ b/zig/src/core/contract/qwen_glue_receipts_test.zig @@ -0,0 +1,49 @@ +//! The four prompt-glue launch receipts must reach the real registry in the five-SM order. +const std = @import("std"); +const reg = @import("registry.zig"); +const limits = @import("limits.zig"); +const t = std.testing; + +const receipts = [_]struct { name: []const u8, regs: [5]u32, shared: u32, bound: u32 }{ + .{ .name = "moe tf_moe_router_expert_first", .regs = .{ 32, 48, 48, 63, 63 }, .shared = 16512, .bound = 256 }, + .{ .name = "gdn_prefill tf_gdn_chain_norm", .regs = .{ 176, 184, 184, 183, 183 }, .shared = 24704, .bound = 256 }, + .{ .name = "gdn_prefill chain_kernel", .regs = .{ 229, 231, 231, 193, 193 }, .shared = 37120, .bound = 128 }, + .{ .name = "qwen35 tf_q35_gdn_post", .regs = .{ 28, 29, 29, 31, 31 }, .shared = 256, .bound = 32 }, +}; + +fn record(name: []const u8) !reg.CudaRecord { + var found: ?reg.CudaRecord = null; + for (reg.all_cuda) |r| if (std.mem.eql(u8, r.launch.name, name)) { + try t.expect(found == null); + found = r; + }; + try t.expect(found != null); + return found.?; +} + +test "Qwen glue receipts: measured resources fit the actual served launch on every SM" { + for (receipts) |receipt| { + const r = try record(receipt.name); + try t.expectEqual(@as(usize, 0), try reg.checkCuda(t.allocator, &.{r}, true)); + } +} + +test "Qwen glue receipts: measured compiles reach every launch and SM through the registry" { + for (limits.sms, [_]u32{ 80, 86, 89, 120, 121 }) |sm, want| try t.expectEqual(want, sm.sm); + const measured = [_]?limits.Nvcc{ null, .{ .major = 13, .minor = 0 } }; + for (measured) |release| { + for (receipts) |receipt| { + const r = try record(receipt.name); + const usage = reg.usageFor(r, release); + for (usage, receipt.regs) |got, regs| { + try t.expectEqualDeep(limits.Usage{ .regs = regs, .static = receipt.shared, .bound = receipt.bound }, got); + } + } + } + for (receipts) |receipt| { + const r = try record(receipt.name); + for ([_]limits.Nvcc{ .{ .major = 13, .minor = 2 }, .{ .major = 13, .minor = 3 } }) |release| { + try t.expectEqualDeep(reg.none, reg.usageFor(r, release)); + } + } +} diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 69de9f49c9f..5252651d235 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -458,6 +458,7 @@ test "the registered launches fit every Apple family and every SM, and each plan } test { _ = @import("registry_sets_test.zig"); + _ = @import("qwen_glue_receipts_test.zig"); _ = @import("nvfp4_tile_pending.zig"); _ = paging; _ = @import("minimax_records.zig"); From 7a62b27e8fc0ba768f8cc7cbaddefc880ef63cfd Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 5 Nov 2026 08:56:56 +0000 Subject: [PATCH 07/15] contract: the glue receipts' test line moves out of the full registry file --- zig/src/core/contract/moe_router_records.zig | 4 ++++ zig/src/core/contract/registry.zig | 1 - 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/zig/src/core/contract/moe_router_records.zig b/zig/src/core/contract/moe_router_records.zig index e27d5a55f60..2d0f91ee39d 100644 --- a/zig/src/core/contract/moe_router_records.zig +++ b/zig/src/core/contract/moe_router_records.zig @@ -3,3 +3,7 @@ const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ .{ .launch = .{ .name = "moe tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "moe", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 } }, .later_pending = true }, }; + +test { + _ = @import("qwen_glue_receipts_test.zig"); +} diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 5252651d235..69de9f49c9f 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -458,7 +458,6 @@ test "the registered launches fit every Apple family and every SM, and each plan } test { _ = @import("registry_sets_test.zig"); - _ = @import("qwen_glue_receipts_test.zig"); _ = @import("nvfp4_tile_pending.zig"); _ = paging; _ = @import("minimax_records.zig"); From 234d479a90a0d99485ee162add1533f76fa6ce8d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:29:10 +0000 Subject: [PATCH 08/15] tests: the GDN chain launch has records now; the numbers are pinned by the glue receipts --- zig/tests/cuda/contract_gdn_chain_host_test.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/cuda/contract_gdn_chain_host_test.zig b/zig/tests/cuda/contract_gdn_chain_host_test.zig index fd0a246d6c3..204ef41b6a2 100644 --- a/zig/tests/cuda/contract_gdn_chain_host_test.zig +++ b/zig/tests/cuda/contract_gdn_chain_host_test.zig @@ -37,7 +37,7 @@ test "GDN chain port: raw byte registration retains every output and both source for (core.contract.registry.all_cuda) |r| if (std.mem.eql(u8, r.launch.symbol, cuda.gdn_chain.symbol)) { found += 1; try std.testing.expectEqual(@as(u32, 256), r.launch.threads); - try std.testing.expectEqual(core.contract.registry.none, r.usage); + try std.testing.expect(!std.meta.eql(core.contract.registry.none, r.usage)); }; try std.testing.expectEqual(@as(usize, 1), found); } From bb1f688ecf26447755915e9968f401d5b992d968 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:29:06 +0000 Subject: [PATCH 09/15] build: reuse the existing CUDA host family modules --- zig/build/cuda.zig | 1 - 1 file changed, 1 deletion(-) diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 3f872c68a62..09764cf8472 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -240,7 +240,6 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st const runtime_host = b.step("test-runtime-host", "Shared CUDA runtime and graph host regressions"); runtime_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda })).step); const mods = family(b, host, .ReleaseSafe, cuda, draft_ids); - const mods = family(b, host, .debug, cuda, draft_ids); inline for (.{ @import("prompt_bf16_host.zig"), @import("gdn_chain_host.zig"), @import("moe_router_host.zig") }) |suite| suite.tests(b, step, cuda, runtime(b, host, .fast, &.{}), mods.core); @import("cuda_checkpoint_cache_host.zig").steps(b, step); From 6b38b2117ccd7684ef250b5fec51b36b68f5debc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:46:53 -0800 Subject: [PATCH 10/15] cuda: isolate Qwen prompt glue in ModelOpt-only images Keep the MLX image recipes, kernel sources and launch ABI equal to main. Retain the BF16 tile ports and keep new image resource records pending measurement. --- docs/recipes/cuda.md | 3 +- zig/build/cuda_family_host.zig | 3 + zig/build/cuda_kernels.zig | 2 + zig/kernels/cuda/contract_controls.cu | 5 - zig/kernels/cuda/gdn_prefill.cu | 3 - zig/kernels/cuda/moe.cu | 2 - zig/kernels/cuda/qwen_gdn_bf16.cu | 4 + zig/kernels/cuda/qwen_router_bf16.cu | 4 + zig/qwen35_modelopt_host.zig | 3 +- zig/src/core/contract/gdn_chain_records.zig | 3 +- zig/src/core/contract/moe_router_records.zig | 2 +- .../core/contract/qwen_glue_receipts_test.zig | 16 ++- zig/src/cuda/gdn_chain.zig | 12 +-- zig/src/cuda/gdn_chain_host_test.zig | 6 +- zig/src/cuda/kernels.zig | 2 + zig/src/cuda/moe.zig | 20 +--- zig/src/cuda/moe_bf16.zig | 26 +++++ zig/src/cuda/moe_router_host_test.zig | 12 +-- zig/src/cuda/nvfp4.zig | 12 +-- zig/src/cuda/root.zig | 2 + zig/src/families/qwen3_5/cuda.zig | 4 + zig/src/families/qwen3_5/cuda_forward.zig | 2 +- zig/src/families/qwen3_5/cuda_modelopt.zig | 6 +- .../families/qwen3_5/cuda_modelopt_prompt.zig | 35 ++++++ .../qwen3_5/cuda_modelopt_prompt_test.zig | 102 ++++++++++++++++++ zig/src/families/qwen3_5/cuda_prompt.zig | 27 ++--- zig/src/families/qwen3_5/cuda_routed.zig | 2 +- zig/src/platform/environment.zig | 3 + zig/src/platform/environment_test.zig | 6 ++ zig/tests/cuda/contract_gdn_chain.zig | 2 +- .../cuda/contract_gdn_chain_host_test.zig | 3 +- zig/tests/cuda/contract_limits.zig | 2 +- zig/tests/cuda/contract_moe_router.zig | 10 +- 33 files changed, 261 insertions(+), 85 deletions(-) create mode 100644 zig/kernels/cuda/qwen_gdn_bf16.cu create mode 100644 zig/kernels/cuda/qwen_router_bf16.cu create mode 100644 zig/src/cuda/moe_bf16.zig create mode 100644 zig/src/families/qwen3_5/cuda_modelopt_prompt.zig create mode 100644 zig/src/families/qwen3_5/cuda_modelopt_prompt_test.zig diff --git a/docs/recipes/cuda.md b/docs/recipes/cuda.md index 5a7cf2448c6..a6d179830e5 100644 --- a/docs/recipes/cuda.md +++ b/docs/recipes/cuda.md @@ -109,9 +109,10 @@ format ([prompt precision](#prompt-precision)): ## Native prompt controls Qwen dense/MoE, Nemotron ModelOpt and Dory BF16 projections use the shared BF16 prompt tile from 1,024 rows. -`TF_CUDA_PROMPT_BF16=0` restores their lane projections; unset or any other value selects the tile. +`TF_CUDA_PROMPT_BF16=0` restores their lane projections; unset or 1 selects the tile; malformed values are refused by name. The threshold is fixed. The prompt module always binds its required BF16 symbols, including with the switch off. Flash Next keeps its own prompt selection and controls. +Qwen ModelOpt alone loads the fused GDN norm and expert-first router; MLX keeps the standard images and launches. For Nemotron, the native `tensorfold run` command on a CUDA build accepts `--device N` to choose a CUDA ordinal. If the flag is absent, it uses `TF_CUDA_DEVICE`, then device 0. `--segments N` enables diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 1046ed10c47..16326fc76ea 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -2,6 +2,9 @@ const std = @import("std"); pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.Build.Step) void { + const mlx_prompt = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"MLX prompt isolation:"} })); + b.step("test-qwen35-mlx-prompt-host", "MLX recurrence/router launch equality and ModelOpt-only prompt glue").dependOn(&mlx_prompt.step); + step.dependOn(&mlx_prompt.step); const host = b.graph.host; const sm110 = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"SM110"} })); b.step("test-qwen35-sm110-host", "SM110 startup refusals without device or weight loading").dependOn(&sm110.step); diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 2af39b4855f..cf658a3cbae 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -110,6 +110,8 @@ pub const kernels = [_]Kernel{ .{ .name = "qwen35_keep", .flags = &.{"-O3"} }, // ours: a verified window's kept path applied to its stream's state .{ .name = "qwen_vision", .flags = &.{ "-O3", "--fmad=false" } }, // ours: the Qwen3.5 vision tower's glue and attention .{ .name = "gdn_prefill", .flags = &.{ "-O3", "--fmad=false" } }, // ours: a prompt chunk's gated delta rule (v0.6.6's chain) + .{ .name = "qwen_gdn_bf16", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "qwen_router_bf16", .flags = &.{"-O3"} }, .{ .name = "qwen35_kv8", .flags = &.{"-O3"} }, // ours: --kv-cache fp8's e4m3 attention rows for the Qwen3.5 hybrids .{ .name = "qwen35_bf16_rows", .flags = &.{"-O3"} }, // ours: bf16 token rows and small bf16 dense projections (qwen3_5/cuda_bf16_rows.zig) .{ .name = "joint_schema", .flags = glue }, // HIP's joint_schema.hip ported: Clef's joint schema head (cuda/joint_schema/) diff --git a/zig/kernels/cuda/contract_controls.cu b/zig/kernels/cuda/contract_controls.cu index 4f7411bd646..cbd3041caf4 100644 --- a/zig/kernels/cuda/contract_controls.cu +++ b/zig/kernels/cuda/contract_controls.cu @@ -492,8 +492,3 @@ extern "C" __global__ void __launch_bounds__(256, 1) tf_ctl_pattn_64(const __nv_ } } // namespace tf_prefill_attention #include "contract_ctl_router.cuh" -#define TF_GDN_CHAIN_CONTROLS -#include "gdn_prefill.cu" - -#define TF_MOE_ROUTER_CONTROLS -#include "moe_router_expert.cuh" diff --git a/zig/kernels/cuda/gdn_prefill.cu b/zig/kernels/cuda/gdn_prefill.cu index cc683a18203..b4e05a968d4 100644 --- a/zig/kernels/cuda/gdn_prefill.cu +++ b/zig/kernels/cuda/gdn_prefill.cu @@ -148,6 +148,3 @@ __global__ void __launch_bounds__(2 * ROWS) chain_kernel( template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, __nv_bfloat16, 64, 32>(const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const float* __restrict__, const __nv_bfloat16* __restrict__, const float*, float*, __nv_bfloat16* __restrict__, int, int, int); - -#define TF_GDN_CHAIN_CONTROLS -#include "gdn_prefill_norm.cuh" diff --git a/zig/kernels/cuda/moe.cu b/zig/kernels/cuda/moe.cu index 2c25a341544..e2312f0a37c 100644 --- a/zig/kernels/cuda/moe.cu +++ b/zig/kernels/cuda/moe.cu @@ -42,8 +42,6 @@ extern "C" __global__ void __launch_bounds__(256) tf_moe_router(const __nv_bfloa if (row0 + rr < R && e0 + ee < E) OUT[static_cast(row0 + rr) * E + e0 + ee] = acc; } -#include "moe_router_expert.cuh" - namespace { constexpr int MAXC = 8; // experts a lane holds: up to 256 routed experts diff --git a/zig/kernels/cuda/qwen_gdn_bf16.cu b/zig/kernels/cuda/qwen_gdn_bf16.cu new file mode 100644 index 00000000000..0b540fa36f8 --- /dev/null +++ b/zig/kernels/cuda/qwen_gdn_bf16.cu @@ -0,0 +1,4 @@ +// ModelOpt-only prompt recurrence; the standard GDN translation unit stays unchanged. +#include "gdn_prefill.cu" +#define TF_GDN_CHAIN_CONTROLS +#include "gdn_prefill_norm.cuh" diff --git a/zig/kernels/cuda/qwen_router_bf16.cu b/zig/kernels/cuda/qwen_router_bf16.cu new file mode 100644 index 00000000000..659051d1000 --- /dev/null +++ b/zig/kernels/cuda/qwen_router_bf16.cu @@ -0,0 +1,4 @@ +// ModelOpt-only expert-first router; the standard MoE translation unit stays unchanged. +#include "moe.cu" +#define TF_MOE_ROUTER_CONTROLS +#include "moe_router_expert.cuh" diff --git a/zig/qwen35_modelopt_host.zig b/zig/qwen35_modelopt_host.zig index b88c5c0b405..4cefae9d96f 100644 --- a/zig/qwen35_modelopt_host.zig +++ b/zig/qwen35_modelopt_host.zig @@ -90,7 +90,7 @@ fn fullKernels(d: *cuda.Driver) modelopt.Kernels { d.api.cuLaunchKernel = Recorded.launch; d.api.cuMemcpyHtoD_v2 = Recorded.copy; d.api.cuStreamSynchronize = Recorded.sync; - var out: modelopt.Kernels = .{ .lane = undefined, .prompt = undefined, .pack = undefined, .embed = undefined }; + var out: modelopt.Kernels = .{ .lane = undefined, .prompt = undefined, .pack = undefined, .embed = undefined, .glue = undefined }; out.lane.clusters = false; for (&out.lane.fns) |*set| for (set) |*f| { f.* = function(d, 2); @@ -102,6 +102,7 @@ fn fullKernels(d: *cuda.Driver) modelopt.Kernels { out.prompt.lean = function(d, 3); out.prompt.lean_f32 = function(d, 3); out.prompt.sms = 48; + out.prompt.bf16_serving = false; out.pack.fp8_lane = function(d, 1); return out; } diff --git a/zig/src/core/contract/gdn_chain_records.zig b/zig/src/core/contract/gdn_chain_records.zig index 01596ff65c5..11e1ff1a05e 100644 --- a/zig/src/core/contract/gdn_chain_records.zig +++ b/zig/src/core/contract/gdn_chain_records.zig @@ -1,7 +1,8 @@ //! Whole-head chain and baseline launch resource records. const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "gdn_prefill tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "gdn_prefill", .threads = 256 }, .usage = .{ .{ .regs = 176, .static = 24704, .bound = 256 }, .{ .regs = 184, .static = 24704, .bound = 256 }, .{ .regs = 184, .static = 24704, .bound = 256 }, .{ .regs = 183, .static = 24704, .bound = 256 }, .{ .regs = 183, .static = 24704, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "qwen_gdn_bf16", .threads = 256 }, .usage = registry.none, .later_pending = true }, .{ .launch = .{ .name = "gdn_prefill chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "gdn_prefill", .threads = 128 }, .usage = .{ .{ .regs = 229, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen_gdn_bf16 chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "qwen_gdn_bf16", .threads = 128 }, .usage = registry.none, .later_pending = true }, .{ .launch = .{ .name = "qwen35 tf_q35_gdn_post", .symbol = "tf_q35_gdn_post", .image = "qwen35", .threads = 32 }, .usage = .{ .{ .regs = 28, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 } }, .later_pending = true }, }; diff --git a/zig/src/core/contract/moe_router_records.zig b/zig/src/core/contract/moe_router_records.zig index 2d0f91ee39d..79b1836e18d 100644 --- a/zig/src/core/contract/moe_router_records.zig +++ b/zig/src/core/contract/moe_router_records.zig @@ -1,7 +1,7 @@ //! Expert-first router launch resource records. const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "moe tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "moe", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "qwen_router_bf16", .threads = 256 }, .usage = registry.none, .later_pending = true }, }; test { diff --git a/zig/src/core/contract/qwen_glue_receipts_test.zig b/zig/src/core/contract/qwen_glue_receipts_test.zig index 2aed374fb5b..d5c891a1b02 100644 --- a/zig/src/core/contract/qwen_glue_receipts_test.zig +++ b/zig/src/core/contract/qwen_glue_receipts_test.zig @@ -1,12 +1,13 @@ -//! The four prompt-glue launch receipts must reach the real registry in the five-SM order. +//! The prompt-glue launch receipts must reach the real registry in the five-SM order. const std = @import("std"); const reg = @import("registry.zig"); const limits = @import("limits.zig"); const t = std.testing; -const receipts = [_]struct { name: []const u8, regs: [5]u32, shared: u32, bound: u32 }{ - .{ .name = "moe tf_moe_router_expert_first", .regs = .{ 32, 48, 48, 63, 63 }, .shared = 16512, .bound = 256 }, - .{ .name = "gdn_prefill tf_gdn_chain_norm", .regs = .{ 176, 184, 184, 183, 183 }, .shared = 24704, .bound = 256 }, +const receipts = [_]struct { name: []const u8, regs: [5]u32 = @splat(0), shared: u32 = 0, bound: u32 = 0, pending: bool = false }{ + .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .pending = true }, + .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .pending = true }, + .{ .name = "qwen_gdn_bf16 chain_kernel", .pending = true }, .{ .name = "gdn_prefill chain_kernel", .regs = .{ 229, 231, 231, 193, 193 }, .shared = 37120, .bound = 128 }, .{ .name = "qwen35 tf_q35_gdn_post", .regs = .{ 28, 29, 29, 31, 31 }, .shared = 256, .bound = 32 }, }; @@ -24,7 +25,8 @@ fn record(name: []const u8) !reg.CudaRecord { test "Qwen glue receipts: measured resources fit the actual served launch on every SM" { for (receipts) |receipt| { const r = try record(receipt.name); - try t.expectEqual(@as(usize, 0), try reg.checkCuda(t.allocator, &.{r}, true)); + const problems = try reg.checkCuda(t.allocator, &.{r}, true); + if (receipt.pending) try t.expect(problems > 0) else try t.expectEqual(@as(usize, 0), problems); } } @@ -35,6 +37,10 @@ test "Qwen glue receipts: measured compiles reach every launch and SM through th for (receipts) |receipt| { const r = try record(receipt.name); const usage = reg.usageFor(r, release); + if (receipt.pending) { + try t.expectEqualDeep(reg.none, usage); + continue; + } for (usage, receipt.regs) |got, regs| { try t.expectEqualDeep(limits.Usage{ .regs = regs, .static = receipt.shared, .bound = receipt.bound }, got); } diff --git a/zig/src/cuda/gdn_chain.zig b/zig/src/cuda/gdn_chain.zig index f5b239fb6f9..6535665ea04 100644 --- a/zig/src/cuda/gdn_chain.zig +++ b/zig/src/cuda/gdn_chain.zig @@ -27,16 +27,14 @@ pub const Chain = struct { fused: ?module.Function = null, pub fn resolve(mod: module.Module) !Chain { - return resolveMode(mod, enabled()); + return resolveMode(mod, try enabled()); } - pub fn enabled() bool { - const value = std.c.getenv("TF_CUDA_GDN_CHAIN_NORM"); - return enabledValue(if (value) |v| std.mem.span(v) else null); + pub fn enabled() !bool { + return @import("sys").environment.read(bool, "TF_CUDA_GDN_CHAIN_NORM", true); } - - pub fn enabledValue(value: ?[]const u8) bool { - return value == null or !std.mem.eql(u8, value.?, "0"); + pub fn enabledValue(value: ?[]const u8) !bool { + return (try @import("sys").environment.parse("TF_CUDA_GDN_CHAIN_NORM", value) orelse 1) != 0; } pub fn resolveMode(mod: module.Module, on: bool) !Chain { diff --git a/zig/src/cuda/gdn_chain_host_test.zig b/zig/src/cuda/gdn_chain_host_test.zig index bf4582847e0..abb0e772973 100644 --- a/zig/src/cuda/gdn_chain_host_test.zig +++ b/zig/src/cuda/gdn_chain_host_test.zig @@ -25,9 +25,9 @@ const Mock = struct { } }; test "GDN chain port: off binds only the old symbol; on binds the fused kernel" { - try std.testing.expect(chain.Chain.enabledValue(null)); - try std.testing.expect(chain.Chain.enabledValue("1")); - try std.testing.expect(!chain.Chain.enabledValue("0")); + try std.testing.expect(try chain.Chain.enabledValue(null)); + try std.testing.expect(try chain.Chain.enabledValue("1")); + try std.testing.expect(!try chain.Chain.enabledValue("0")); var d: cuda.Driver = undefined; d.api.cuModuleGetFunction = Mock.bind; const mod: cuda.Module = .{ .d = &d, .handle = null }; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index adc58505802..7d5ce78d056 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -85,6 +85,8 @@ pub const joint_schema: []const u8 = if (available) &Blob("fatbin_joint_schema") pub const qwen_vision: []const u8 = if (available) &Blob("fatbin_qwen_vision").bytes else &.{}; pub const qwen35_kv8: []const u8 = if (available) &Blob("fatbin_qwen35_kv8").bytes else &.{}; pub const qwen35_bf16_rows: []const u8 = if (available) &Blob("fatbin_qwen35_bf16_rows").bytes else &.{}; +pub const qwen_gdn_bf16: []const u8 = if (available) &Blob("fatbin_qwen_gdn_bf16").bytes else &.{}; +pub const qwen_router_bf16: []const u8 = if (available) &Blob("fatbin_qwen_router_bf16").bytes else &.{}; pub const gdn_prefill: []const u8 = if (available) &Blob("fatbin_gdn_prefill").bytes else &.{}; pub const qmmf: []const u8 = if (available) &Blob("fatbin_qmmf").bytes else &.{}; pub const prompt16: []const u8 = if (available) &Blob("fatbin_prompt16").bytes else &.{}; diff --git a/zig/src/cuda/moe.zig b/zig/src/cuda/moe.zig index 1cf85dc42ff..2cfb3ea3b5e 100644 --- a/zig/src/cuda/moe.zig +++ b/zig/src/cuda/moe.zig @@ -14,28 +14,18 @@ pub const max_top_k = 31; pub const Fns = struct { router_fn: Function, - router_expert: ?Function = null, topk_fn: Function, combine_fn: Function, router_tiles_fn: Function, /// From the loaded moe module (kernels.moe). pub fn resolve(mod: Module) !Fns { - const value = std.c.getenv("TF_CUDA_MOE_EXPERT_FIRST"); - return resolveMode(mod, expertFirst(if (value) |v| std.mem.span(v) else null)); - } - - pub fn expertFirst(value: ?[]const u8) bool { - return value == null or !std.mem.eql(u8, value.?, "0"); - } - - pub fn resolveMode(mod: Module, on: bool) !Fns { - return .{ .router_fn = try mod.function("tf_moe_router"), .router_expert = if (on) try mod.function("tf_moe_router_expert_first") else null, .topk_fn = try mod.function("tf_moe_topk"), .combine_fn = try mod.function("tf_moe_combine"), .router_tiles_fn = try mod.function("tf_moe_router_tiles") }; + return .{ .router_fn = try mod.function("tf_moe_router"), .topk_fn = try mod.function("tf_moe_topk"), .combine_fn = try mod.function("tf_moe_combine"), .router_tiles_fn = try mod.function("tf_moe_router_tiles") }; } /// logits[r][e] = fp32 x[r] . w[e], the gate last; `params` word 2 caps rows; wide calls on the same-bits tiles. pub fn route(f: Fns, s: Stream, x: u64, x_stride: usize, rows: usize, w: u64, logits: u64, dims: usize, count: usize, params: u64) !void { - if (f.router_expert == null and tiled(x, x_stride, w, rows, dims)) return f.routeTiles(s, x, rows, w, logits, dims, count, params); + if (tiled(x, x_stride, w, rows, dims)) return f.routeTiles(s, x, rows, w, logits, dims, count, params); var a: launch_.Args = .{}; a.add(x); a.add(int(x_stride)); @@ -43,10 +33,8 @@ pub const Fns = struct { a.add(logits); for ([_]usize{ rows, dims, count }) |v| a.add(int(v)); a.add(params); - const rt: u32 = @intCast((rows + 15) / 16); - const et: u32 = @intCast((count + 15) / 16); - const cfg: launch_.Config = .{ .grid = if (f.router_expert != null) .{ .x = et, .y = rt } else .{ .x = rt, .y = et }, .block = .{ .x = 256 } }; - try launch_.launch(f.router_expert orelse f.router_fn, cfg, s, &a); + const cfg: launch_.Config = .{ .grid = .{ .x = @intCast((rows + 15) / 16), .y = @intCast((count + 15) / 16), .z = 1 }, .block = .{ .x = 256 } }; + try launch_.launch(f.router_fn, cfg, s, &a); } /// Each row's top-k picks and bf16-rounded weights ([rows][top_k + 1]); slot top_k is the shared expert. diff --git a/zig/src/cuda/moe_bf16.zig b/zig/src/cuda/moe_bf16.zig new file mode 100644 index 00000000000..bdad26db787 --- /dev/null +++ b/zig/src/cuda/moe_bf16.zig @@ -0,0 +1,26 @@ +//! ModelOpt's expert-first router, with the standard router owning every fallback launch. +const cuda = @import("root.zig"); +pub const Fns = struct { + base: cuda.moe.Fns, + router_expert: ?cuda.Function = null, + pub fn resolve(mod: cuda.Module) !Fns { + return resolveMode(mod, try @import("sys").environment.read(bool, "TF_CUDA_MOE_EXPERT_FIRST", true)); + } + pub fn expertFirst(value: ?[]const u8) !bool { + return (try @import("sys").environment.parse("TF_CUDA_MOE_EXPERT_FIRST", value) orelse 1) != 0; + } + pub fn resolveMode(mod: cuda.Module, on: bool) !Fns { + return .{ .base = try cuda.moe.Fns.resolve(mod), .router_expert = if (on) try mod.function("tf_moe_router_expert_first") else null }; + } + pub fn route(f: Fns, s: cuda.Stream, x: u64, stride: usize, rows: usize, w: u64, logits: u64, dims: usize, count: usize, params: u64) !void { + const kernel = f.router_expert orelse return f.base.route(s, x, stride, rows, w, logits, dims, count, params); + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(c_int, @intCast(stride))); + a.add(w); + a.add(logits); + for ([_]usize{ rows, dims, count }) |n| a.add(@as(c_int, @intCast(n))); + a.add(params); + try cuda.launch.launch(kernel, .{ .grid = .{ .x = @intCast((count + 15) / 16), .y = @intCast((rows + 15) / 16) }, .block = .{ .x = 256 } }, s, &a); + } +}; diff --git a/zig/src/cuda/moe_router_host_test.zig b/zig/src/cuda/moe_router_host_test.zig index 669c9c77e46..0c37e12eee3 100644 --- a/zig/src/cuda/moe_router_host_test.zig +++ b/zig/src/cuda/moe_router_host_test.zig @@ -7,7 +7,7 @@ const Mock = struct { var args: [8]u64 = undefined; var bindings: usize = 0; fn bind(out: *cuda.abi.Function, _: cuda.abi.Module, name: [*:0]const u8) callconv(.c) cuda.abi.Result { - const names = [_][]const u8{ "tf_moe_router", "tf_moe_router_expert_first", "tf_moe_topk", "tf_moe_combine" }; + const names = [_][]const u8{ "tf_moe_router", "tf_moe_router_expert_first", "tf_moe_topk", "tf_moe_combine", "tf_moe_router_tiles" }; for (names, 1..) |n, i| if (std.mem.eql(u8, n, std.mem.span(name))) { out.* = @ptrFromInt(i); bindings += 1; @@ -24,9 +24,9 @@ const Mock = struct { } }; test "MoE router port: off avoids the new symbol and restores the row-first grid" { - try std.testing.expect(cuda.moe.Fns.expertFirst(null)); - try std.testing.expect(cuda.moe.Fns.expertFirst("1")); - try std.testing.expect(!cuda.moe.Fns.expertFirst("0")); + try std.testing.expect(try cuda.moe_bf16.Fns.expertFirst(null)); + try std.testing.expect(try cuda.moe_bf16.Fns.expertFirst("1")); + try std.testing.expect(!try cuda.moe_bf16.Fns.expertFirst("0")); var d: cuda.Driver = undefined; d.api.cuModuleGetFunction = Mock.bind; d.api.cuLaunchKernel = Mock.launch; @@ -34,8 +34,8 @@ test "MoE router port: off avoids the new symbol and restores the row-first grid const s: cuda.Stream = .{ .d = &d, .handle = null }; for ([_]bool{ false, true }) |on| { Mock.bindings = 0; - const f = try cuda.moe.Fns.resolveMode(mod, on); - try std.testing.expectEqual(@as(usize, if (on) 4 else 3), Mock.bindings); + const f = try cuda.moe_bf16.Fns.resolveMode(mod, on); + try std.testing.expectEqual(@as(usize, if (on) 5 else 4), Mock.bindings); for ([_]usize{ 1, 15, 16, 17, 31, 32, 33, 128, 512, 1024, 2048 }) |rows| for ([_]usize{ 1, 15, 16, 17, 255, 256, 257 }) |experts| for ([_]usize{ 128, 2048, 2055 }) |dims| for ([_]u64{ 0, 0xbeef }) |params| { try f.route(s, 0x1000, dims + 16, rows, 0x2000, 0x3000, dims, experts, params); try std.testing.expectEqual(@as(usize, if (on) 2 else 1), Mock.id); diff --git a/zig/src/cuda/nvfp4.zig b/zig/src/cuda/nvfp4.zig index 4a3fd9a86c0..1ad1c95de54 100644 --- a/zig/src/cuda/nvfp4.zig +++ b/zig/src/cuda/nvfp4.zig @@ -148,8 +148,7 @@ pub const Prompt = struct { /// Required BF16 symbols stay bound; the cached flag selects this family's serving path only. pub fn enableBf16(p: *Prompt) !void { - const value = std.c.getenv("TF_CUDA_PROMPT_BF16"); - p.bf16_serving = bf16Enabled(if (value) |v| std.mem.span(v) else null); + p.bf16_serving = try @import("sys").environment.read(bool, "TF_CUDA_PROMPT_BF16", true); } pub fn usesBf16(p: Prompt, rows: usize) bool { @@ -296,12 +295,13 @@ test "scale tiles keep a column's four scales of each 64 inputs together" { try std.testing.expectEqual(@as(u8, 0), out[((0 * 2 + 0) * 64 + 5) * 4]); // row 5: padding } -pub fn bf16Enabled(value: ?[]const u8) bool { - return if (value) |v| !std.mem.eql(u8, v, "0") else true; +pub fn bf16Enabled(value: ?[]const u8) !bool { + return (try @import("sys").environment.parse("TF_CUDA_PROMPT_BF16", value) orelse 1) != 0; } test "BF16 prompt switch restores serving on the lane without changing required bindings" { - try std.testing.expect(!bf16Enabled("0")); - for ([_]?[]const u8{ null, "1", "", "invalid" }) |v| try std.testing.expect(bf16Enabled(v)); + try std.testing.expect(!try bf16Enabled("0")); + for ([_]?[]const u8{ null, "1", "" }) |v| try std.testing.expect(try bf16Enabled(v)); + try std.testing.expectError(error.InvalidEnvironment, bf16Enabled("invalid")); try std.testing.expectEqual(@as(u32, 98304), Prompt.bf16Shared()); } diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 13509191b1f..0f580038eab 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -201,3 +201,5 @@ test { test { _ = @import("moe_router_host_test.zig"); } + +pub const moe_bf16 = @import("moe_bf16.zig"); diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 4d3375563b5..2815e211097 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -120,3 +120,7 @@ test "the shard plan's head widths are the kernels'" { test { _ = @import("cuda_request_starts_test.zig"); } + +test { + _ = @import("cuda_modelopt_prompt_test.zig"); +} diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 999ec4362a4..4b2e641ef4f 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -99,7 +99,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { try e.runPdl(e.fns.gdn_pre, .{ 1, 2 * g.k_heads + g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.qkv, t_segs, t_rows, t_par, layer, m.conv, e.a, e.b, m.a_log, m.dt_bias, e.q, e.k, e.v, e.g_, e.beta, t_params }); // one recorded window of 2+ rows: gdn_pre logged its tails, conv_commit would only return if (!(record and nseg == 1 and total > 1)) try e.run(e.fns.conv_commit, .{ (g.convWidth() + 255) / 256, nseg, 1 }, .{ 256, 1, 1 }, .{ geo, e.qkv, t_segs, t_par, layer, t_params }); - const norm_done = if (prompt and nseg == 1) try @import("cuda_prompt.zig").delta(e, di, total, m.norm, sums) else blk: { + const norm_done = if (prompt and nseg == 1) try @import("cuda_modelopt_prompt.zig").delta(e, di, total, m.norm, sums) else blk: { try e.deltaScan(record, shape.slots, nseg, layer); break :blk false; }; diff --git a/zig/src/families/qwen3_5/cuda_modelopt.zig b/zig/src/families/qwen3_5/cuda_modelopt.zig index a87d4cc9b67..7c34ad2784f 100644 --- a/zig/src/families/qwen3_5/cuda_modelopt.zig +++ b/zig/src/families/qwen3_5/cuda_modelopt.zig @@ -242,6 +242,7 @@ pub const Kernels = struct { prompt: cuda.nvfp4.Prompt, pack: cuda.modelopt.Packer, embed: cuda.embed_rows.EmbedRows, + glue: @import("cuda_modelopt_prompt.zig").Glue, /// Slice partials where no cluster meets them (before sm_90): the most any projection takes below fused_rows. part: ?DeviceBuffer = null, experts: ?cuda.experts.Nvfp4Experts = null, // a MoE's routed experts (cuda_modelopt_experts.zig) @@ -258,10 +259,13 @@ pub const Kernels = struct { errdefer pack.unload(); var experts: ?cuda.experts.Nvfp4Experts = if (moe) try cuda.experts.Nvfp4Experts.load(d, sms) else null; errdefer if (experts) |*x| x.unload(); - return .{ .lane = lane, .prompt = prompt, .pack = pack, .embed = try cuda.embed_rows.EmbedRows.load(d), .experts = experts }; + var glue = try @import("cuda_modelopt_prompt.zig").Glue.load(d, moe); + errdefer glue.unload(); + return .{ .lane = lane, .prompt = prompt, .pack = pack, .embed = try cuda.embed_rows.EmbedRows.load(d), .experts = experts, .glue = glue }; } pub fn unload(k: *Kernels) void { + k.glue.unload(); if (k.part) |*p| p.free(); if (k.experts) |*x| x.unload(); k.embed.unload(); diff --git a/zig/src/families/qwen3_5/cuda_modelopt_prompt.zig b/zig/src/families/qwen3_5/cuda_modelopt_prompt.zig new file mode 100644 index 00000000000..b2ee2933778 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_modelopt_prompt.zig @@ -0,0 +1,35 @@ +//! ModelOpt prompt glue lives outside the MLX CUDA modules and dispatch path. +const std = @import("std"); +const cuda = @import("cuda"); +const geometry = @import("cuda_geometry.zig"); +const Seg = @import("cuda_cache.zig").Seg; +pub const Glue = struct { + gdn: cuda.Module, + router_module: ?cuda.Module, + chain: cuda.gdn_chain.Chain, + router: ?cuda.moe_bf16.Fns, + pub fn load(d: *const cuda.Driver, moe: bool) !Glue { + var gd = try cuda.Module.load(d, cuda.kernels.qwen_gdn_bf16); + errdefer gd.unload(); + var rt: ?cuda.Module = if (moe) try cuda.Module.load(d, cuda.kernels.qwen_router_bf16) else null; + errdefer if (rt) |*m| m.unload(); + return .{ .gdn = gd, .router_module = rt, .chain = try cuda.gdn_chain.Chain.resolve(gd), .router = if (rt) |m| try cuda.moe_bf16.Fns.resolve(m) else null }; + } + pub fn unload(g: *Glue) void { + if (g.router_module) |*m| m.unload(); + g.gdn.unload(); + } +}; +pub fn delta(e: anytype, layer: usize, rows: usize, norm: u64, sums: u64) !bool { + if (e.mo) |m| { + const sg = std.mem.bytesToValue(Seg, e.staged.bytes[@TypeOf(e.*).segs_at..][0..@sizeOf(Seg)]); + const state = sg.rec + layer * e.g.v_heads * geometry.dk * geometry.dk * 4; + return m.glue.chain.run(e.stream, .{ .q = e.q, .k = e.k, .v = e.v, .g = e.g_, .beta = e.beta, .state = state, .last = state, .y = e.y, .z = e.z, .norm = norm, .mix = e.mix, .sums = sums }, rows, e.g.k_heads, e.g.v_heads, e.g.eps); + } + try @import("cuda_prompt.zig").delta(e, layer, rows); + return false; +} +pub fn route(e: anytype, x: u64, rows: usize, weights: u64, logits: u64, count: usize, params: u64) !void { + if (e.mo) |m| if (m.glue.router) |f| return f.route(e.stream, x, e.g.hidden, rows, weights, logits, e.g.hidden, count, params); + return e.moe.route(e.stream, x, e.g.hidden, rows, weights, logits, e.g.hidden, count, params); +} diff --git a/zig/src/families/qwen3_5/cuda_modelopt_prompt_test.zig b/zig/src/families/qwen3_5/cuda_modelopt_prompt_test.zig new file mode 100644 index 00000000000..dc45d914d15 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_modelopt_prompt_test.zig @@ -0,0 +1,102 @@ +//! MLX dispatch equals main at the actual driver ABI; ModelOpt alone takes the additional kernels. +const std = @import("std"); +const cuda = @import("cuda"); +const E = @import("cuda_engine.zig").Engine; +const geometry = @import("cuda_geometry.zig"); +const Seg = @import("cuda_cache.zig").Seg; +const helper = @import("cuda_modelopt_prompt.zig"); +const chain_rows = 64; +const Snapshot = struct { id: usize = 0, grid: [3]u32 = @splat(0), block: [3]u32 = @splat(0), shared: u32 = 0, args: [16]u64 = @splat(0) }; +const Mock = struct { + var now: Snapshot = .{}; + fn function(d: *const cuda.Driver, id: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; + } + fn launch(f: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, by: c_uint, bz: c_uint, sm: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + const id = @intFromPtr(f); + now = .{ .id = id, .grid = .{ gx, gy, gz }, .block = .{ bx, by, bz }, .shared = sm }; + const n: usize = if (id == 1) 11 else if (id == 2) 16 else 8; + for (0..n) |i| { + const wide = if (id <= 2) i < 8 or (i >= 11 and i < 15) else i == 0 or i == 2 or i == 3 or i == 7; + now.args[i] = if (wide) @as(*align(1) const u64, @ptrCast(args.?[i].?)).* else @as(*align(1) const u32, @ptrCast(args.?[i].?)).*; + } + return cuda.abi.success; + } +}; +fn baselineDelta(e: *E, layer: usize, rows: usize) !void { + const g = e.g; + const sg = std.mem.bytesToValue(Seg, e.staged.bytes[E.segs_at..][0..@sizeOf(Seg)]); + const state = sg.rec + layer * g.v_heads * geometry.dk * geometry.dk * 4; + var a: cuda.Args = .{}; + for ([_]u64{ e.q, e.k, e.v, e.g_, e.beta, state, state, e.y }) |v| a.add(v); + for ([_]usize{ rows, g.k_heads, g.v_heads }) |v| a.add(@as(c_int, @intCast(v))); + const cfg: cuda.Config = .{ .grid = .{ .x = @intCast(g.v_heads), .y = @intCast(geometry.dk / chain_rows) }, .block = .{ .x = 2 * chain_rows } }; + try cuda.launch.launch(e.prompt_attn.chain, cfg, e.stream, &a); +} + +test "MLX prompt isolation: recurrence launch and norm fallthrough equal the frozen main sequence" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Mock.launch; + var bytes: [E.segs_at + @sizeOf(Seg)]u8 align(16) = @splat(0); + var sg = std.mem.zeroes(Seg); + sg.rec = 0x100000; + @memcpy(bytes[E.segs_at..][0..@sizeOf(Seg)], std.mem.asBytes(&sg)); + var e: E = undefined; + e.staged = .{ .d = &d, .bytes = &bytes }; + e.stream = .{ .d = &d, .handle = null }; + e.prompt_attn.chain = Mock.function(&d, 1); + e.q = 0x1000; + e.k = 0x2000; + e.v = 0x3000; + e.g_ = 0x4000; + e.beta = 0x5000; + e.y = 0x6000; + e.z = 0x7000; + e.mix = 0x8000; + e.g.k_heads = 16; + e.g.v_heads = 48; + e.g.eps = 1e-6; + e.mo = null; + for ([_]usize{ 1, 16, 64, 65, 1023, 1024, 2048 }) |rows| for ([_]usize{ 0, 3, 17 }) |layer| { + try baselineDelta(&e, layer, rows); + const before = Mock.now; + try std.testing.expect(!try helper.delta(&e, layer, rows, 0x9000, 0xa000)); + try std.testing.expectEqualDeep(before, Mock.now); + var mo: @import("cuda_modelopt.zig").Kernels = undefined; + mo.glue.chain = .{ .old = Mock.function(&d, 1), .fused = Mock.function(&d, 2) }; + e.mo = mo; + try std.testing.expect(try helper.delta(&e, layer, rows, 0x9000, 0xa000)); + try std.testing.expectEqual(@as(usize, 2), Mock.now.id); + try std.testing.expectEqual([3]u32{ 48, 1, 1 }, Mock.now.grid); + mo.glue.chain.fused = null; + e.mo = mo; + try std.testing.expect(!try helper.delta(&e, layer, rows, 0x9000, 0xa000)); + try std.testing.expectEqualDeep(before, Mock.now); + e.mo = null; + }; +} +test "MLX prompt isolation: row router and large-row tiles retain main kernels grids and arguments" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Mock.launch; + var e: E = undefined; + e.stream = .{ .d = &d, .handle = null }; + e.moe = .{ .router_fn = Mock.function(&d, 3), .router_tiles_fn = Mock.function(&d, 5), .topk_fn = Mock.function(&d, 6), .combine_fn = Mock.function(&d, 7) }; + for ([_]usize{ 1, 16, 256, 257, 512, 1024, 2048 }) |rows| for ([_]usize{ 17, 257 }) |experts| for ([_]usize{ 2048, 2055 }) |dims| { + e.mo = null; + e.g.hidden = dims; + try e.moe.route(e.stream, 0x1000, dims, rows, 0x2000, 0x3000, dims, experts, 0xbeef); + const before = Mock.now; + try helper.route(&e, 0x1000, rows, 0x2000, 0x3000, experts, 0xbeef); + try std.testing.expectEqualDeep(before, Mock.now); + var mo: @import("cuda_modelopt.zig").Kernels = undefined; + mo.glue.router = .{ .base = e.moe, .router_expert = Mock.function(&d, 4) }; + e.mo = mo; + try helper.route(&e, 0x1000, rows, 0x2000, 0x3000, experts, 0xbeef); + try std.testing.expectEqual(@as(usize, 4), Mock.now.id); + try std.testing.expectEqual([3]u32{ @intCast((experts + 15) / 16), @intCast((rows + 15) / 16), 1 }, Mock.now.grid); + mo.glue.router.?.router_expert = null; + e.mo = mo; + try helper.route(&e, 0x1000, rows, 0x2000, 0x3000, experts, 0xbeef); + try std.testing.expectEqualDeep(before, Mock.now); + }; +} diff --git a/zig/src/families/qwen3_5/cuda_prompt.zig b/zig/src/families/qwen3_5/cuda_prompt.zig index c7d5f51ca19..d6e4fdd0bb2 100644 --- a/zig/src/families/qwen3_5/cuda_prompt.zig +++ b/zig/src/families/qwen3_5/cuda_prompt.zig @@ -14,7 +14,7 @@ pub const page_ids: u32 = 768; const hpc = 2; const block_rows = 16 * (8 / hpc); -pub const Fns = struct { bf16: cuda.Function, fp8: cuda.Function, bf16_whole: cuda.Function, fp8_whole: cuda.Function, bf16_p256: cuda.Function, bf16_p256_ids: cuda.Function, chain: cuda.gdn_chain.Chain }; +pub const Fns = struct { bf16: cuda.Function, fp8: cuda.Function, bf16_whole: cuda.Function, fp8_whole: cuda.Function, bf16_p256: cuda.Function, bf16_p256_ids: cuda.Function, chain: cuda.Function }; pub const symbols = struct { pub const bf16 = "_ZN20tf_prefill_attention13hpattn_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi"; @@ -25,9 +25,11 @@ pub const symbols = struct { pub const bf16_p256_ids = "_ZN20tf_prefill_attention22hpattn_p256_ids_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi"; pub const chain = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii"; }; +/// gdn_prefill.cu's value rows a block (two threads a row). +const chain_rows = 64; pub fn resolve(attention: cuda.Module, gdn: cuda.Module) !Fns { - const f: Fns = .{ .bf16 = try attention.function(symbols.bf16), .fp8 = try attention.function(symbols.fp8), .bf16_whole = try attention.function(symbols.bf16_whole), .fp8_whole = try attention.function(symbols.fp8_whole), .bf16_p256 = try attention.function(symbols.bf16_p256), .bf16_p256_ids = try attention.function(symbols.bf16_p256_ids), .chain = try cuda.gdn_chain.Chain.resolve(gdn) }; + const f: Fns = .{ .bf16 = try attention.function(symbols.bf16), .fp8 = try attention.function(symbols.fp8), .bf16_whole = try attention.function(symbols.bf16_whole), .fp8_whole = try attention.function(symbols.fp8_whole), .bf16_p256 = try attention.function(symbols.bf16_p256), .bf16_p256_ids = try attention.function(symbols.bf16_p256_ids), .chain = try gdn.function(symbols.chain) }; try f.bf16.allowDynamicShared(smem); try f.fp8.allowDynamicShared(smem); try f.bf16_whole.allowDynamicShared(smem); @@ -99,24 +101,15 @@ pub fn runFrom(e: *E.Engine, layer: usize, from: usize, end: usize) !void { } /// Linear layer `layer`'s delta rule: e.q, e.k, e.v, e.g_, e.beta into e.y, the stream's recurrence updated in place. -pub fn delta(e: *E.Engine, layer: usize, rows: usize, norm: u64, sums: u64) !bool { +pub fn delta(e: *E.Engine, layer: usize, rows: usize) !void { const g = e.g; const sg = std.mem.bytesToValue(Seg, e.staged.bytes[E.Engine.segs_at..][0..@sizeOf(Seg)]); const state = sg.rec + layer * g.v_heads * geometry.dk * geometry.dk * 4; - return e.prompt_attn.chain.run(e.stream, .{ - .q = e.q, - .k = e.k, - .v = e.v, - .g = e.g_, - .beta = e.beta, - .state = state, - .last = state, - .y = e.y, - .z = e.z, - .norm = norm, - .mix = e.mix, - .sums = sums, - }, rows, g.k_heads, g.v_heads, g.eps); + var a: cuda.Args = .{}; + for ([_]u64{ e.q, e.k, e.v, e.g_, e.beta, state, state, e.y }) |v| a.add(v); + for ([_]usize{ rows, g.k_heads, g.v_heads }) |v| a.add(@as(c_int, @intCast(v))); + const cfg: cuda.Config = .{ .grid = .{ .x = @intCast(g.v_heads), .y = @intCast(geometry.dk / chain_rows) }, .block = .{ .x = 2 * chain_rows } }; + try cuda.launch.launch(e.prompt_attn.chain, cfg, e.stream, &a); } test "Qwen prompt layout: whole ABI omits page metadata and keeps original layer and head strides" { diff --git a/zig/src/families/qwen3_5/cuda_routed.zig b/zig/src/families/qwen3_5/cuda_routed.zig index 636d1bfc673..e511c281f0c 100644 --- a/zig/src/families/qwen3_5/cuda_routed.zig +++ b/zig/src/families/qwen3_5/cuda_routed.zig @@ -45,7 +45,7 @@ pub fn rows(e: *E.Engine, router: u64, layer: cuda.experts.Layer, x: u64, out: u const items = cuda.grouped.maxItems(pairs, count, tile); const plan: cuda.grouped.Plan = .{ .members = s.members, .items = s.items, .counts = s.counts, .rank = s.rank, .hist = s.hist }; const grouped: cuda.experts.Grouped = .{ .affine4 = &e.experts, .affine3 = &e.experts3, .exl3 = if (e.kit) |k| &k.grouped else null }; - try e.moe.route(e.stream, x, g.hidden, total, router, s.logits, g.hidden, count, params); + try @import("cuda_modelopt_prompt.zig").route(e, x, total, router, s.logits, count, params); try e.moe.pick(e.stream, s.logits, s.picks, s.wts, total, g.experts, g.top_k, params); try e.plan.routeRows(e.stream, s.picks, pairs, count, tile, plan, if (params == 0) 0 else params + 2 * 4, slots); const rows_in: cuda.experts.Rows = .{ .x = x, .stride = g.hidden, .slots = slots }; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 37a6e68359f..a7fc1e4e88d 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -60,6 +60,9 @@ pub const rules = [_]Rule{ .{ .name = "TENSORFOLD_TOOL_ID_KEY_FILE", .scope = .common, .kind = .path, .forms = "a path without control characters to a file only its owner can read, holding at least 32 key bytes" }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .scope = .cuda, .kind = .path, .forms = "a captured kernel set's folder without control characters, or native for the engine's own kernels" }, .{ .name = "TF_NCCL_LIB", .scope = .cuda, .kind = .path, .forms = "an NCCL library path without control characters, or blank for libnccl.so.2" }, + .{ .name = "TF_CUDA_PROMPT_BF16", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 1)" }, + .{ .name = "TF_CUDA_GDN_CHAIN_NORM", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 1)" }, + .{ .name = "TF_CUDA_MOE_EXPERT_FIRST", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_CUDA_DEVICE", .scope = .cuda, .kind = .device, .trim = " ", .forms = "a whole GPU ordinal from 0 to 4294967295, or empty for the default" }, .{ .name = "TF_CUDA_SEGMENTS", .scope = .cuda, .kind = .segments, .trim = " ", .forms = "a whole number from 1 to 4, or empty for the default" }, .{ .name = "TF_CUDA_CARVEOUT", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 6f8286185e8..5bfd57cbeb6 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -62,6 +62,12 @@ const valid = [_]Case{ .{ .name = "TF_STARTUP_RECEIPT", .raw = "1", .n = 1 }, .{ .name = "TF_SHARED_PRICE_LOG", .raw = "0", .n = 0 }, .{ .name = "TF_SHARED_PRICE_LOG", .raw = "1", .n = 1 }, + .{ .name = "TF_CUDA_PROMPT_BF16", .raw = "0", .n = 0 }, + .{ .name = "TF_CUDA_PROMPT_BF16", .raw = "1", .n = 1 }, + .{ .name = "TF_CUDA_GDN_CHAIN_NORM", .raw = "0", .n = 0 }, + .{ .name = "TF_CUDA_GDN_CHAIN_NORM", .raw = "1", .n = 1 }, + .{ .name = "TF_CUDA_MOE_EXPERT_FIRST", .raw = "0", .n = 0 }, + .{ .name = "TF_CUDA_MOE_EXPERT_FIRST", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_DEVICE_CHECK", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_DEVICE_CHECK", .raw = "1", .n = 1 }, .{ .name = "TF_CUDA_DEVICE", .raw = " 3 ", .n = 3 }, diff --git a/zig/tests/cuda/contract_gdn_chain.zig b/zig/tests/cuda/contract_gdn_chain.zig index a476a99e6a1..724eb67e266 100644 --- a/zig/tests/cuda/contract_gdn_chain.zig +++ b/zig/tests/cuda/contract_gdn_chain.zig @@ -151,7 +151,7 @@ pub const Suite = struct { qwen: cuda.Module, cases: [6]Case, pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, _: cuda.Module) !Suite { - var gd = try cuda.Module.load(gpu.d, cuda.kernels.gdn_prefill); + var gd = try cuda.Module.load(gpu.d, cuda.kernels.qwen_gdn_bf16); errdefer gd.unload(); var qw = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); errdefer qw.unload(); diff --git a/zig/tests/cuda/contract_gdn_chain_host_test.zig b/zig/tests/cuda/contract_gdn_chain_host_test.zig index 204ef41b6a2..72e6c34af2d 100644 --- a/zig/tests/cuda/contract_gdn_chain_host_test.zig +++ b/zig/tests/cuda/contract_gdn_chain_host_test.zig @@ -37,7 +37,8 @@ test "GDN chain port: raw byte registration retains every output and both source for (core.contract.registry.all_cuda) |r| if (std.mem.eql(u8, r.launch.symbol, cuda.gdn_chain.symbol)) { found += 1; try std.testing.expectEqual(@as(u32, 256), r.launch.threads); - try std.testing.expect(!std.meta.eql(core.contract.registry.none, r.usage)); + try std.testing.expectEqualDeep(core.contract.registry.none, r.usage); + try std.testing.expectEqualStrings("qwen_gdn_bf16", r.launch.image); }; try std.testing.expectEqual(@as(usize, 1), found); } diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 8bb1f969206..dd64093c207 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -31,7 +31,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "tree_round", "act_rows", "gdn_prep", "gdn_prefill", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "tree_round", "act_rows", "gdn_prep", "gdn_prefill", "qwen_gdn_bf16", "qwen_router_bf16", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; diff --git a/zig/tests/cuda/contract_moe_router.zig b/zig/tests/cuda/contract_moe_router.zig index ce7c4d4d5be..abafa0c98fc 100644 --- a/zig/tests/cuda/contract_moe_router.zig +++ b/zig/tests/cuda/contract_moe_router.zig @@ -47,7 +47,7 @@ pub const Inputs = struct { pub const Case = struct { rig: @import("contract_rig.zig").Rig, - f: cuda.moe.Fns, + f: cuda.moe_bf16.Fns, replacement: bool = true, live: bool = false, pad: usize = 0, @@ -141,14 +141,14 @@ pub const Case = struct { pub const Suite = struct { mod: cuda.Module, cases: [5]Case, - pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, controls: cuda.Module) !Suite { - var mod = try cuda.Module.load(gpu.d, cuda.kernels.moe); + pub fn init(gpu: @import("check.zig").Gpu, s: cuda.Stream, _: cuda.Module) !Suite { + var mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen_router_bf16); errdefer mod.unload(); - const f = try cuda.moe.Fns.resolveMode(mod, true); + const f = try cuda.moe_bf16.Fns.resolveMode(mod, true); var cases: [5]Case = undefined; for (&cases, 0..) |*case, i| { var fns = f; - if (i == 4) fns.router_expert = try controls.function("tf_moe_router_expert_bad_rows"); + if (i == 4) fns.router_expert = try mod.function("tf_moe_router_expert_bad_rows"); case.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns, .replacement = i != 1, .pad = if (i == 2 or i == 3) 16 else 0, .live = i == 3, .control = i == 4 }; } return .{ .mod = mod, .cases = cases }; From 0e4aa1e94e503fa9fcbb04909c5b4b0efd2ce9dc Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:50:45 +0000 Subject: [PATCH 11/15] contract: record the ModelOpt prompt glue launches' GB10 resources The GB10 (sm_121) kernel contract on the PR head measured the three launches in the new qwen_gdn_bf16 and qwen_router_bf16 images: chain_kernel 193 registers and 37120 static shared bytes at 128 threads, tf_gdn_chain_norm 183 and 24704 at 256, and tf_moe_router_expert_first 63 and 16512 at 256. Record them on sm_121 only, as nvcc 13.0's receipt. sm_80, sm_86, sm_89 and sm_120 stay pending until a device run measures them, and later compilers stay pending as before. --- zig/src/core/contract/gdn_chain_records.zig | 13 ++++++++-- zig/src/core/contract/moe_router_records.zig | 2 +- .../core/contract/qwen_glue_receipts_test.zig | 24 ++++++++----------- .../cuda/contract_gdn_chain_host_test.zig | 2 +- 4 files changed, 23 insertions(+), 18 deletions(-) diff --git a/zig/src/core/contract/gdn_chain_records.zig b/zig/src/core/contract/gdn_chain_records.zig index 11e1ff1a05e..7350b1fa3eb 100644 --- a/zig/src/core/contract/gdn_chain_records.zig +++ b/zig/src/core/contract/gdn_chain_records.zig @@ -1,8 +1,17 @@ //! Whole-head chain and baseline launch resource records. const registry = @import("registry.zig"); +const limits = @import("limits.zig"); +/// An nvcc 13.0 receipt from the GB10 live contract; the other four SMs and later compilers stay pending. +pub fn gb10(u: limits.Usage) [limits.sms.len]limits.Usage { + var out = registry.none; + for (limits.sms, &out) |sm, *o| if (sm.sm == 121) { + o.* = u; + }; + return out; +} pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "qwen_gdn_bf16", .threads = 256 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "qwen_gdn_bf16", .threads = 256 }, .usage = gb10(.{ .regs = 183, .static = 24704, .bound = 256 }), .later_pending = true }, .{ .launch = .{ .name = "gdn_prefill chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "gdn_prefill", .threads = 128 }, .usage = .{ .{ .regs = 229, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "qwen_gdn_bf16 chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "qwen_gdn_bf16", .threads = 128 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "qwen_gdn_bf16 chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "qwen_gdn_bf16", .threads = 128 }, .usage = gb10(.{ .regs = 193, .static = 37120, .bound = 128 }), .later_pending = true }, .{ .launch = .{ .name = "qwen35 tf_q35_gdn_post", .symbol = "tf_q35_gdn_post", .image = "qwen35", .threads = 32 }, .usage = .{ .{ .regs = 28, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 } }, .later_pending = true }, }; diff --git a/zig/src/core/contract/moe_router_records.zig b/zig/src/core/contract/moe_router_records.zig index 79b1836e18d..a70b5d35afe 100644 --- a/zig/src/core/contract/moe_router_records.zig +++ b/zig/src/core/contract/moe_router_records.zig @@ -1,7 +1,7 @@ //! Expert-first router launch resource records. const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "qwen_router_bf16", .threads = 256 }, .usage = registry.none, .later_pending = true }, + .{ .launch = .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "qwen_router_bf16", .threads = 256 }, .usage = @import("gdn_chain_records.zig").gb10(.{ .regs = 63, .static = 16512, .bound = 256 }), .later_pending = true }, }; test { diff --git a/zig/src/core/contract/qwen_glue_receipts_test.zig b/zig/src/core/contract/qwen_glue_receipts_test.zig index d5c891a1b02..9a5f1595189 100644 --- a/zig/src/core/contract/qwen_glue_receipts_test.zig +++ b/zig/src/core/contract/qwen_glue_receipts_test.zig @@ -4,10 +4,11 @@ const reg = @import("registry.zig"); const limits = @import("limits.zig"); const t = std.testing; -const receipts = [_]struct { name: []const u8, regs: [5]u32 = @splat(0), shared: u32 = 0, bound: u32 = 0, pending: bool = false }{ - .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .pending = true }, - .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .pending = true }, - .{ .name = "qwen_gdn_bf16 chain_kernel", .pending = true }, +// A zero register count is an SM the receipt has not measured yet (the ModelOpt images: GB10 only). +const receipts = [_]struct { name: []const u8, regs: [5]u32, shared: u32, bound: u32 }{ + .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .regs = .{ 0, 0, 0, 0, 63 }, .shared = 16512, .bound = 256 }, + .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .regs = .{ 0, 0, 0, 0, 183 }, .shared = 24704, .bound = 256 }, + .{ .name = "qwen_gdn_bf16 chain_kernel", .regs = .{ 0, 0, 0, 0, 193 }, .shared = 37120, .bound = 128 }, .{ .name = "gdn_prefill chain_kernel", .regs = .{ 229, 231, 231, 193, 193 }, .shared = 37120, .bound = 128 }, .{ .name = "qwen35 tf_q35_gdn_post", .regs = .{ 28, 29, 29, 31, 31 }, .shared = 256, .bound = 32 }, }; @@ -22,11 +23,10 @@ fn record(name: []const u8) !reg.CudaRecord { return found.?; } -test "Qwen glue receipts: measured resources fit the actual served launch on every SM" { +test "Qwen glue receipts: measured resources fit the actual served launch on every measured SM" { for (receipts) |receipt| { const r = try record(receipt.name); - const problems = try reg.checkCuda(t.allocator, &.{r}, true); - if (receipt.pending) try t.expect(problems > 0) else try t.expectEqual(@as(usize, 0), problems); + try t.expectEqual(std.mem.countScalar(u32, &receipt.regs, 0), try reg.checkCuda(t.allocator, &.{r}, true)); } } @@ -36,13 +36,9 @@ test "Qwen glue receipts: measured compiles reach every launch and SM through th for (measured) |release| { for (receipts) |receipt| { const r = try record(receipt.name); - const usage = reg.usageFor(r, release); - if (receipt.pending) { - try t.expectEqualDeep(reg.none, usage); - continue; - } - for (usage, receipt.regs) |got, regs| { - try t.expectEqualDeep(limits.Usage{ .regs = regs, .static = receipt.shared, .bound = receipt.bound }, got); + for (reg.usageFor(r, release), receipt.regs) |got, regs| { + const want: limits.Usage = if (regs == 0) .{ .regs = 0, .static = 0 } else .{ .regs = regs, .static = receipt.shared, .bound = receipt.bound }; + try t.expectEqualDeep(want, got); } } } diff --git a/zig/tests/cuda/contract_gdn_chain_host_test.zig b/zig/tests/cuda/contract_gdn_chain_host_test.zig index 72e6c34af2d..e245c92fd3f 100644 --- a/zig/tests/cuda/contract_gdn_chain_host_test.zig +++ b/zig/tests/cuda/contract_gdn_chain_host_test.zig @@ -37,7 +37,7 @@ test "GDN chain port: raw byte registration retains every output and both source for (core.contract.registry.all_cuda) |r| if (std.mem.eql(u8, r.launch.symbol, cuda.gdn_chain.symbol)) { found += 1; try std.testing.expectEqual(@as(u32, 256), r.launch.threads); - try std.testing.expectEqualDeep(core.contract.registry.none, r.usage); + try std.testing.expect(!std.meta.eql(core.contract.registry.none, r.usage)); try std.testing.expectEqualStrings("qwen_gdn_bf16", r.launch.image); }; try std.testing.expectEqual(@as(usize, 1), found); From 15e4a2e9eb04c57a1ddca87ed45c49154d5d36e3 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:49:01 +0000 Subject: [PATCH 12/15] cuda contract: record nvcc 13.0's launch limits for the BF16 prompt tile's Qwen kernels tf_moe_router_expert_first, tf_gdn_chain_norm and the qwen_gdn_bf16 chain_kernel held a GB10 receipt only, so sm_80, sm_86, sm_89 and sm_120 had no compiled usage and kernel-contract-limits counted 12 stale records. The five-SM limits audit of c4920d4c23's fatbins (nvcc 13.0, -Dsm=80,86,89,120,121) gives every SM; its RECORD lines are now the records, and the glue receipts test pins all five. The GB10-only helper has no users left and goes. --- zig/src/core/contract/gdn_chain_records.zig | 13 ++----------- zig/src/core/contract/moe_router_records.zig | 2 +- zig/src/core/contract/qwen_glue_receipts_test.zig | 8 ++++---- 3 files changed, 7 insertions(+), 16 deletions(-) diff --git a/zig/src/core/contract/gdn_chain_records.zig b/zig/src/core/contract/gdn_chain_records.zig index 7350b1fa3eb..68bdc0dfc52 100644 --- a/zig/src/core/contract/gdn_chain_records.zig +++ b/zig/src/core/contract/gdn_chain_records.zig @@ -1,17 +1,8 @@ //! Whole-head chain and baseline launch resource records. const registry = @import("registry.zig"); -const limits = @import("limits.zig"); -/// An nvcc 13.0 receipt from the GB10 live contract; the other four SMs and later compilers stay pending. -pub fn gb10(u: limits.Usage) [limits.sms.len]limits.Usage { - var out = registry.none; - for (limits.sms, &out) |sm, *o| if (sm.sm == 121) { - o.* = u; - }; - return out; -} pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "qwen_gdn_bf16", .threads = 256 }, .usage = gb10(.{ .regs = 183, .static = 24704, .bound = 256 }), .later_pending = true }, + .{ .launch = .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .symbol = "tf_gdn_chain_norm", .image = "qwen_gdn_bf16", .threads = 256 }, .usage = .{ .{ .regs = 176, .static = 24704, .bound = 256 }, .{ .regs = 184, .static = 24704, .bound = 256 }, .{ .regs = 184, .static = 24704, .bound = 256 }, .{ .regs = 183, .static = 24704, .bound = 256 }, .{ .regs = 183, .static = 24704, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "gdn_prefill chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "gdn_prefill", .threads = 128 }, .usage = .{ .{ .regs = 229, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "qwen_gdn_bf16 chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "qwen_gdn_bf16", .threads = 128 }, .usage = gb10(.{ .regs = 193, .static = 37120, .bound = 128 }), .later_pending = true }, + .{ .launch = .{ .name = "qwen_gdn_bf16 chain_kernel", .symbol = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16S1_Li64ELi32EEEvPKT_S4_PKS1_PKfPKT0_S8_PfPS1_iii", .image = "qwen_gdn_bf16", .threads = 128 }, .usage = .{ .{ .regs = 229, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 231, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 }, .{ .regs = 193, .static = 37120, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "qwen35 tf_q35_gdn_post", .symbol = "tf_q35_gdn_post", .image = "qwen35", .threads = 32 }, .usage = .{ .{ .regs = 28, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 29, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 }, .{ .regs = 31, .static = 256, .bound = 32 } }, .later_pending = true }, }; diff --git a/zig/src/core/contract/moe_router_records.zig b/zig/src/core/contract/moe_router_records.zig index a70b5d35afe..b323a241724 100644 --- a/zig/src/core/contract/moe_router_records.zig +++ b/zig/src/core/contract/moe_router_records.zig @@ -1,7 +1,7 @@ //! Expert-first router launch resource records. const registry = @import("registry.zig"); pub const records = [_]registry.CudaRecord{ - .{ .launch = .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "qwen_router_bf16", .threads = 256 }, .usage = @import("gdn_chain_records.zig").gb10(.{ .regs = 63, .static = 16512, .bound = 256 }), .later_pending = true }, + .{ .launch = .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .symbol = "tf_moe_router_expert_first", .image = "qwen_router_bf16", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 48, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 }, .{ .regs = 63, .static = 16512, .bound = 256 } }, .later_pending = true }, }; test { diff --git a/zig/src/core/contract/qwen_glue_receipts_test.zig b/zig/src/core/contract/qwen_glue_receipts_test.zig index 9a5f1595189..4211d65a1bd 100644 --- a/zig/src/core/contract/qwen_glue_receipts_test.zig +++ b/zig/src/core/contract/qwen_glue_receipts_test.zig @@ -4,11 +4,11 @@ const reg = @import("registry.zig"); const limits = @import("limits.zig"); const t = std.testing; -// A zero register count is an SM the receipt has not measured yet (the ModelOpt images: GB10 only). +// nvcc 13.0 on all five SMs; a zero register count would be an SM the receipt has not measured yet. const receipts = [_]struct { name: []const u8, regs: [5]u32, shared: u32, bound: u32 }{ - .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .regs = .{ 0, 0, 0, 0, 63 }, .shared = 16512, .bound = 256 }, - .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .regs = .{ 0, 0, 0, 0, 183 }, .shared = 24704, .bound = 256 }, - .{ .name = "qwen_gdn_bf16 chain_kernel", .regs = .{ 0, 0, 0, 0, 193 }, .shared = 37120, .bound = 128 }, + .{ .name = "qwen_router_bf16 tf_moe_router_expert_first", .regs = .{ 32, 48, 48, 63, 63 }, .shared = 16512, .bound = 256 }, + .{ .name = "qwen_gdn_bf16 tf_gdn_chain_norm", .regs = .{ 176, 184, 184, 183, 183 }, .shared = 24704, .bound = 256 }, + .{ .name = "qwen_gdn_bf16 chain_kernel", .regs = .{ 229, 231, 231, 193, 193 }, .shared = 37120, .bound = 128 }, .{ .name = "gdn_prefill chain_kernel", .regs = .{ 229, 231, 231, 193, 193 }, .shared = 37120, .bound = 128 }, .{ .name = "qwen35 tf_q35_gdn_post", .regs = .{ 28, 29, 29, 31, 31 }, .shared = 256, .bound = 32 }, }; From 2c2aaec4ab7314c78bad043de1b242ea30d03afd Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:40:40 +0000 Subject: [PATCH 13/15] tests: re-pin the four CUDA serving sources #2008 changes, on today's main kernels.zig, nvfp4.zig, qlinear.zig and root.zig changed on main since this branch was rebased, and the merge with main matched neither pin. --- zig/tests/fixtures/gradient-serving.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ae5d06a0eb5..841edb76f6d 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 d348915a2365645f8a0aa1106e73a34572ad13cc52e2d8c042d5de32fdde8d49 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered +zig/src/cuda/kernels.zig d348915a2365645f8a0aa1106e73a34572ad13cc52e2d8c042d5de32fdde8d49 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered; #2008 rebase on f0a54bdf56 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 b45ab3fb420c31b78236f168c490b1dddb1f9c28 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:08:39 +0000 Subject: [PATCH 14/15] tests: the BF16 prompt mocks set main's lean_swiglu, on today's main Main added Prompt.lean_swiglu (the lean tile's gate/up kernel) after this series' base. The two test mocks that build a Prompt by hand (cuda/prompt_bf16_host_test.zig and dory/cuda_kernels.zig's prompt-tile test) set it to their mock function, as they set the other lean entries. No served code changes. --- zig/src/cuda/prompt_bf16_host_test.zig | 2 +- zig/src/families/dory/cuda_kernels.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/cuda/prompt_bf16_host_test.zig b/zig/src/cuda/prompt_bf16_host_test.zig index d539c5a5e98..f85babaf232 100644 --- a/zig/src/cuda/prompt_bf16_host_test.zig +++ b/zig/src/cuda/prompt_bf16_host_test.zig @@ -42,7 +42,7 @@ fn lane(d: *const Driver) qmmf.Lane { fn prompt(d: *const Driver) Prompt { const f = function(d, 2); - return .{ .mod = .{ .d = d, .handle = null }, .fp4 = f, .fp8 = f, .fp4_f32 = f, .lean = f, .lean_f32 = f, .sms = 16, .bf16_serving = true, .bf16 = function(d, 3), .bf16_f32 = function(d, 4) }; + return .{ .mod = .{ .d = d, .handle = null }, .fp4 = f, .fp8 = f, .fp4_f32 = f, .lean = f, .lean_f32 = f, .lean_swiglu = f, .sms = 16, .bf16_serving = true, .bf16 = function(d, 3), .bf16_f32 = function(d, 4) }; } test "BF16 prompt port: threshold, family opt-in, cached switch and decode keep the lane" { diff --git a/zig/src/families/dory/cuda_kernels.zig b/zig/src/families/dory/cuda_kernels.zig index 70f0283d644..45a75f7262b 100644 --- a/zig/src/families/dory/cuda_kernels.zig +++ b/zig/src/families/dory/cuda_kernels.zig @@ -119,7 +119,7 @@ test "BF16 prompt port: Dory observes the threshold, cached switch and decode pa const prompt_fn = Mock.function(&d, 2); var k: Kernels = undefined; k.lane = .{ .mod = .{ .d = &d, .handle = null }, .fns = @splat(@splat(lane_fn)), .f32_fns = @splat(@splat(lane_fn)), .reduce = @splat(lane_fn), .half = @splat(@splat(@splat(lane_fn))), .clusters = false }; - k.prompt = .{ .mod = .{ .d = &d, .handle = null }, .fp4 = prompt_fn, .fp8 = prompt_fn, .fp4_f32 = prompt_fn, .lean = prompt_fn, .lean_f32 = prompt_fn, .sms = 16, .bf16_serving = true, .bf16 = Mock.function(&d, 3), .bf16_f32 = Mock.function(&d, 4) }; + k.prompt = .{ .mod = .{ .d = &d, .handle = null }, .fp4 = prompt_fn, .fp8 = prompt_fn, .fp4_f32 = prompt_fn, .lean = prompt_fn, .lean_f32 = prompt_fn, .lean_swiglu = prompt_fn, .sms = 16, .bf16_serving = true, .bf16 = Mock.function(&d, 3), .bf16_f32 = Mock.function(&d, 4) }; const linear = k.linear(); const w: cuda.qmmf.Weight = .{ .mode = .bf16, .codes = 0x2000, .scales = 0, .n = 48, .k = 5120, .npad = 128 }; for ([_]usize{ 1023, 1024, 2048 }) |rows| { From d5595e6af5c3ebc2937099c73dcc0288f0b559f0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:40:11 +0000 Subject: [PATCH 15/15] tests: refresh serving pins for the BF16 prompt rebase --- zig/tests/fixtures/gradient-serving.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 841edb76f6d..21fbb587e81 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 d348915a2365645f8a0aa1106e73a34572ad13cc52e2d8c042d5de32fdde8d49 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered; #2008 rebase on f0a54bdf56 +zig/src/cuda/kernels.zig 35df329a2516ead420ae823874493e04408cc4b7a8ff8f5c9cc3d70c10df82f3 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered; #2008 rebase on f0a54bdf56 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 @@ -101,11 +101,11 @@ zig/src/cuda/module.zig 1f0a141cf7149a87ad456e96cb1830f0c137ad98af70071721918989 zig/src/cuda/mxfp8.zig 2bbe9ea41b462f633b68e7a32c06814a28e34dee284383788c0a8f06e8df2af4 raw zig/src/cuda/nccl.zig 005a4dd9ed6929b6022c4daff8d8d82c0ee43ea3e468221fd4a8de9ae6dde640 raw commits 53abe4556, ba1a9a2bb, 05350da4c, 40dccba55, 6bdb12918, b923e554c, 7c9d845c0, 98a5dc657, 143ed758f, 6636e6964; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; #3106 (Library.open reads TF_NCCL_LIB through pathFrom, shared with the TP session's settings; unset, empty and blank keep libnccl.so.2) zig/src/cuda/norms.zig c6ac613ff91b31257b5bce55311d8cf38a785862bfad9eb0c7bf0b2ba7b0df95 raw -zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7fb90928 raw #3252: launcher for the lean SwiGLU pair -zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate +zig/src/cuda/nvfp4.zig ed1ccbeac29c323582942b574e103f558fd7185c9b47b463b842d41c8338b14d raw #3252: launcher for the lean SwiGLU pair +zig/src/cuda/qlinear.zig 5af377bf7f471bf2c7acc8eb1996c3602aaedac362c566390b2adcd0de7c7643 raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/qmmf.zig d95cbbce9598ee49b4677468f6672773470d9c52db5cb79ee20531963b2409fb raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fuse_split_n, default 0: main's kernels); threshold owned by Flash Next's lane, other families keep 0 zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig acf7f9d879a577622b705bfde274264ebb8ff8f4d6a4fb34b8828fff1642bcd5 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items) +zig/src/cuda/root.zig fee4ae793cd179bd2e77e439caf004c5f8ca6065e2de81212688a1a251c4d177 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items) zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw