diff --git a/docs/recipes/cuda.md b/docs/recipes/cuda.md index f9e9f23bc0f..a6d179830e5 100644 --- a/docs/recipes/cuda.md +++ b/docs/recipes/cuda.md @@ -108,6 +108,12 @@ 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 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 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..09764cf8472 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); + 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/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/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/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/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/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/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/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 new file mode 100644 index 00000000000..68bdc0dfc52 --- /dev/null +++ b/zig/src/core/contract/gdn_chain_records.zig @@ -0,0 +1,8 @@ +//! Whole-head chain and baseline launch resource records. +const registry = @import("registry.zig"); +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 = .{ .{ .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 = .{ .{ .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 new file mode 100644 index 00000000000..b323a241724 --- /dev/null +++ b/zig/src/core/contract/moe_router_records.zig @@ -0,0 +1,9 @@ +//! 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 = .{ .{ .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/qwen_glue_receipts_test.zig b/zig/src/core/contract/qwen_glue_receipts_test.zig new file mode 100644 index 00000000000..4211d65a1bd --- /dev/null +++ b/zig/src/core/contract/qwen_glue_receipts_test.zig @@ -0,0 +1,51 @@ +//! 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; + +// 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 = .{ 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 }, +}; + +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 measured SM" { + for (receipts) |receipt| { + const r = try record(receipt.name); + try t.expectEqual(std.mem.countScalar(u32, &receipt.regs, 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); + 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); + } + } + } + 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_joins.zig b/zig/src/core/contract/registry_joins.zig index 6b4e5f243ef..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("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/gdn_chain.zig b/zig/src/cuda/gdn_chain.zig new file mode 100644 index 00000000000..6535665ea04 --- /dev/null +++ b/zig/src/cuda/gdn_chain.zig @@ -0,0 +1,59 @@ +//! 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, try enabled()); + } + + pub fn enabled() !bool { + return @import("sys").environment.read(bool, "TF_CUDA_GDN_CHAIN_NORM", true); + } + 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 { + 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..abb0e772973 --- /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(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 }; + 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/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_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 new file mode 100644 index 00000000000..0c37e12eee3 --- /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", "tf_moe_router_tiles" }; + 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(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; + 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_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); + 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/nvfp4.zig b/zig/src/cuda/nvfp4.zig index 13cf22e4d30..1ad1c95de54 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,15 @@ 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 { + p.bf16_serving = try @import("sys").environment.read(bool, "TF_CUDA_PROMPT_BF16", true); + } + + 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 +294,14 @@ 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 (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(!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/prompt_bf16_host_test.zig b/zig/src/cuda/prompt_bf16_host_test.zig new file mode 100644 index 00000000000..f85babaf232 --- /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, .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" { + 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..0f580038eab 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -185,9 +185,21 @@ test { test { _ = @import("context_health.zig"); + _ = @import("prompt_bf16_host_test.zig"); } 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"); +} + +test { + _ = @import("moe_router_host_test.zig"); +} + +pub const moe_bf16 = @import("moe_bf16.zig"); diff --git a/zig/src/families/dory/cuda_kernels.zig b/zig/src/families/dory/cuda_kernels.zig index d9dbf1ad3fc..45a75f7262b 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, .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| { + 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; 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.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 56ab6e16352..4b2e641ef4f 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_modelopt_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_modelopt.zig b/zig/src/families/qwen3_5/cuda_modelopt.zig index da853b39ed4..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) @@ -253,14 +254,18 @@ 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; 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(); @@ -270,7 +275,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/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_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 new file mode 100644 index 00000000000..724eb67e266 --- /dev/null +++ b/zig/tests/cuda/contract_gdn_chain.zig @@ -0,0 +1,176 @@ +//! 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 = &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", + .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, + .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)); + 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, _: cuda.Module) !Suite { + 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(); + 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 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 }; + } + 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..e245c92fd3f --- /dev/null +++ b/zig/tests/cuda/contract_gdn_chain_host_test.zig @@ -0,0 +1,54 @@ +//! 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 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| { + 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.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); +} + +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_limits.zig b/zig/tests/cuda/contract_limits.zig index 2cce732c70e..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", "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 new file mode 100644 index 00000000000..abafa0c98fc --- /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_bf16.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, _: cuda.Module) !Suite { + var mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen_router_bf16); + errdefer mod.unload(); + 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 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 }; + } + 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_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..91adcc6b248 --- /dev/null +++ b/zig/tests/cuda/contract_prompt_bf16.zig @@ -0,0 +1,84 @@ +//! 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 { + pub const callbacks = g.hooks(Tile); + 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 = &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, + .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..f2a51a5e206 --- /dev/null +++ b/zig/tests/cuda/contract_prompt_bf16_host_test.zig @@ -0,0 +1,77 @@ +//! 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); + } +} + +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); +} diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index 3f426be1ff4..c4b35969537 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"); @@ -43,6 +43,8 @@ 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"); const wrows_k = @import("contract_window_rows.zig"); @@ -240,21 +242,15 @@ 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 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); + 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()); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ae5d06a0eb5..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 +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