diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index ca58ba7ac48..f553eabff99 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -5,7 +5,6 @@ const golden_build = @import("golden.zig"); const catalog = @import("cuda_kernels.zig"); pub const Kernel = catalog.Kernel; pub const kernels = catalog.kernels; - pub const runtime = @import("cuda_runtime.zig").runtime; const stagger = @import("cuda_runtime.zig").stagger; const engines_build = @import("cuda_engines.zig"); @@ -131,12 +130,13 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu q35.addImport("cuda", cuda); q35.addImport("core", mods.core); q35.addImport("qwen35", mods.qwen35); - b.installArtifact(b.addExecutable(.{ .name = "tf-qwen35-cuda", .root_module = q35 })); + const q35_install = b.addInstallArtifact(b.addExecutable(.{ .name = "tf-qwen35-cuda", .root_module = q35 }), .{}); + b.getInstallStep().dependOn(&q35_install.step); + b.step("qwen35-cuda", "Build the Qwen CUDA forward and raw state receipt tool").dependOn(&q35_install.step); const d3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, mods.core) } } }); const d3_exe = b.addExecutable(.{ .name = "drama3-generate", .root_module = d3_tool }); b.step("drama3-generate", "Drama generation and replay controls on CUDA").dependOn(&b.addInstallArtifact(d3_exe, .{}).step); } - /// The Kolibri-1 CUDA family over the runtime, the core and the lane core. const kolibri1Module = @import("kolibri.zig").module; diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index afd20c59612..340a019b6f2 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -94,5 +94,14 @@ pub fn cuda(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build const run = b.addRunArtifact(runner); run.addArg("kernel-contract"); b.step("kernel-contract", "Every registered CUDA kernel through the contract's gates on this GPU, each control red").dependOn(&run.step); + const prefill_many = b.addRunArtifact(runner); + prefill_many.addArg("qmm-prefill-many-contract"); + b.step("qmm-prefill-many-contract", "GB10 bit-exact multi-projection prompt launch against separate launches").dependOn(&prefill_many.step); + const prefill_tile22 = b.addRunArtifact(runner); + prefill_tile22.addArg("qmm-prefill-tile22-contract"); + b.step("qmm-prefill-tile22-contract", "GB10 large-prompt 2x2 tile against the default tile").dependOn(&prefill_tile22.step); + const prefill_many_bench = b.addRunArtifact(runner); + prefill_many_bench.addArg("qmm-prefill-many-bench"); + b.step("qmm-prefill-many-bench", "Same-process A-B-A screening for the GB10 prompt launch fusion").dependOn(&prefill_many_bench.step); return install; } diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index fa1ebe5c2ce..46dc41dbfb6 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -15,7 +15,7 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt const group = @embedFile("kernels/cuda/qmm_group.cu"); try std.testing.expectEqualStrings("3b27b8e964f6e7453e962cd7a259253ae7e1940297439b4b518f05da04dd1041", &hash(group[0..16132])); try std.testing.expectEqualStrings("25172d5cd98fe2768a216183336f7eb9c23a66b0a56cfff77b9825ef66a481a6", &hash(group)); - try std.testing.expectEqualStrings("2e4f98ea301a4d87639c55b93c37577a9fd7f3cda0cbae055c7ba4958f019bfd", &hash(@embedFile("kernels/cuda/qmm_prefill.cu"))); + try std.testing.expectEqualStrings("b5c2016899f701ba865f9bac6ba1e240b98256633356b95f958f8a014804b229", &hash(@embedFile("kernels/cuda/qmm_prefill.cu"))); try std.testing.expectEqualStrings("0a78ac9b394106ef27053a786660e440292f42cc3a49abca432f4522d4488b63", &hash(@embedFile("kernels/cuda/qwen35.cu"))); try std.testing.expectEqualStrings("c145572fa895e22c32960a1f6f65bf6bb11ced11b7d65121d7261a4f84a0faa2", &hash(@embedFile("kernels/cuda/qwen35.cuh"))); try std.testing.expectEqualStrings("60ffcb12aaf8155d8b82274299a0e21cb007d06e540c47cfeaeb6de2e69a6317", &hash(@embedFile("kernels/cuda/qwen35_draft.cu"))); diff --git a/zig/kernels/cuda/qmm_prefill.cu b/zig/kernels/cuda/qmm_prefill.cu index 9af0ad2e411..1c997716df3 100644 --- a/zig/kernels/cuda/qmm_prefill.cu +++ b/zig/kernels/cuda/qmm_prefill.cu @@ -10,6 +10,21 @@ namespace tf_qmm_prefill { using namespace qmm_frag; +constexpr int PARTS = 4; + +struct PrefillPart { + const uint32_t* w; + const __nv_bfloat16* scales; + const __nv_bfloat16* biases; + void* out; + int n, npad, first; +}; + +struct PrefillParts { + PrefillPart p[PARTS]; + int count; +}; + template struct Tile { static constexpr int THREADS = WM * WN * 32; @@ -30,6 +45,122 @@ __device__ __forceinline__ uint32_t fma2(uint32_t a, uint32_t b, uint32_t c) { return d; } +template +__device__ __forceinline__ void prefill_body( + const __nv_bfloat16* __restrict__ x, const uint32_t* __restrict__ w, const __nv_bfloat16* __restrict__ scales, + const __nv_bfloat16* __restrict__ biases, void* __restrict__ out, int M, int N, int K, int npad, int ldx, + int group, unsigned int block) { + using T = Tile; + extern __shared__ __align__(128) unsigned char buf[]; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int wm = warp / WN, wn = warp % WN; + const int KG = K / GS, per = KG, g0 = 0; + const int2 at = tile_of(block, M, N, BM, BN, group); + const int m0 = at.x, n0 = at.y; + + auto stage = [&](int s) { return buf + s * T::STAGE; }; + auto load = [&](int s, int g) { + unsigned char* p = stage(s); + for (int c = tid; c < BM * T::CHUNKS; c += T::THREADS) { + const int r = c / T::CHUNKS, ch = c % T::CHUNKS; + const int row = min(m0 + r, M - 1); + cp16z(p + r * T::ROW + swz(r, ch) * 16, x + static_cast(row) * ldx + g * GS + ch * 8, + m0 + r < M); + } + unsigned char* pw = p + T::X; + constexpr int TILE_BYTES = 64 * GS / 2; // one stored 64-column tile's group block + for (int c = tid; c < T::W / 16; c += T::THREADS) { + const int t = c / (TILE_BYTES / 16), off = c % (TILE_BYTES / 16); + const size_t tile = static_cast(n0 / 64 + t) * KG + g; + if (n0 + t * 64 < npad) // a 256-wide block's last tiles may pass the padded columns + cp16(pw + c * 16, reinterpret_cast(w) + tile * TILE_BYTES + off * 16); + } + unsigned char* ps = pw + T::W; + for (int c = tid; c < 2 * (T::S / 16); c += T::THREADS) { + const int which = c / (T::S / 16), off = c % (T::S / 16); + const __nv_bfloat16* src = (which ? biases : scales) + static_cast(g) * npad + n0 + off * 8; + if (n0 + off * 8 < npad) cp16(ps + which * T::S + off * 16, src); + } + }; + + float acc[T::MT][T::NT][4]; +#pragma unroll + for (int i = 0; i < T::MT; ++i) +#pragma unroll + for (int j = 0; j < T::NT; ++j) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[i][j][e] = 0.0f; +#pragma unroll + for (int s = 0; s < STAGES - 1; ++s) { + if (s < per) load(s, g0 + s); + commit(); + } + for (int it = 0; it < per; ++it) { + wait(); + __syncthreads(); + const int next = it + STAGES - 1; + if (next < per) load(next % STAGES, g0 + next); + commit(); + const unsigned char* p = stage(it % STAGES); + const uint32_t* pw = reinterpret_cast(p + T::X); + const uint16_t* ps = reinterpret_cast(p + T::X + T::W); + uint32_t words[T::NT][GS / 32], sv[T::NT], bv[T::NT]; +#pragma unroll + for (int j = 0; j < T::NT; ++j) { +#pragma unroll + for (int v = 0; v < GS / 32; ++v) words[j][v] = pw[((wn * T::NT + j) * 32 + lane) * (GS / 32) + v]; + const int col = wn * (BN / WN) + j * 8 + (lane >> 2); // this lane's B-fragment column + sv[j] = ps[col] * 0x10001u; // (s, s) and (b, b) as bf16 pairs + bv[j] = ps[BN + col] * 0x10001u; + } +#pragma unroll + for (int kt = 0; kt < GS / 16; ++kt) { + uint32_t a[T::MT][4]; +#pragma unroll + for (int i = 0; i < T::MT; ++i) { + const int r = wm * (BM / WM) + i * 16 + (lane & 7) + ((lane >> 3) & 1) * 8; + const int ch = kt * 2 + (lane >> 4); + ldmatrix4(a[i], p + r * T::ROW + swz(r, ch) * 16); + } +#pragma unroll + for (int j = 0; j < T::NT; ++j) { + const uint32_t b0 = fma2(pair(words[j][kt / 2], (kt & 1) * 8), sv[j], bv[j]); + const uint32_t b1 = fma2(pair(words[j][kt / 2], (kt & 1) * 8 + 4), sv[j], bv[j]); +#pragma unroll + for (int i = 0; i < T::MT; ++i) mma(acc[i][j], a[i], b0, b1); + } + } + } + wait<0>(); + __syncthreads(); +#pragma unroll + for (int i = 0; i < T::MT; ++i) +#pragma unroll + for (int j = 0; j < T::NT; ++j) { + const int col = n0 + wn * (BN / WN) + j * 8 + (lane & 3) * 2; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int row = m0 + wm * (BM / WM) + i * 16 + (lane >> 2) + h * 8; + if (row >= M) continue; + const float v0 = acc[i][j][2 * h], v1 = acc[i][j][2 * h + 1]; + if (F32) { + float* dst = reinterpret_cast(out) + static_cast(row) * N + col; + if (col < N) dst[0] = v0; + if (col + 1 < N) dst[1] = v1; + } else { + __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(out) + static_cast(row) * N + col; + if (col + 1 < N && (N & 1) == 0) + *reinterpret_cast<__nv_bfloat162*>(dst) = __floats2bfloat162_rn(v0, v1); + else { + if (col < N) dst[0] = __float2bfloat16_rn(v0); + if (col + 1 < N) dst[1] = __float2bfloat16_rn(v1); + } + } + } + } +} + +// Keep the shipped kernel body literal: sharing its helper changed Blackwell SASS under nvcc 13.0 and 13.3. template __global__ void __launch_bounds__(WM * WN * 32) prefill_kernel( const __nv_bfloat16* __restrict__ x, const uint32_t* __restrict__ w, const __nv_bfloat16* __restrict__ scales, @@ -147,6 +278,19 @@ __global__ void __launch_bounds__(WM * WN * 32) prefill_kernel( } // namespace tf_qmm_prefill +// One grid runs up to four projections through the shipped body with projection-local block indices. +extern "C" __global__ __launch_bounds__(256) void tf_qmm_prefill_many( + const __nv_bfloat16* __restrict__ x, const __grid_constant__ tf_qmm_prefill::PrefillParts parts, int M, int K, + int ldx, int group) { + int q = 0; +#pragma unroll + for (int i = 1; i < tf_qmm_prefill::PARTS; ++i) + if (i < parts.count && blockIdx.x >= parts.p[i].first) q = i; + const tf_qmm_prefill::PrefillPart P = parts.p[q]; + tf_qmm_prefill::prefill_body<64, 128, 128, 2, 4, 3, false>(x, P.w, P.scales, P.biases, P.out, M, P.n, K, + P.npad, ldx, group, blockIdx.x - P.first); +} + // The instantiation prefill_matmul launches (tile 0: 128x128 on 2x4 warps, 3 stages), bf16 out. template __global__ void tf_qmm_prefill::prefill_kernel<64, 128, 128, 2, 4, 3, false>( const __nv_bfloat16* __restrict__, const uint32_t* __restrict__, const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, void* __restrict__, int, int, int, diff --git a/zig/src/core/contract/measurements/qmm_prefill_132.zig b/zig/src/core/contract/measurements/qmm_prefill_132.zig new file mode 100644 index 00000000000..6ef3080e557 --- /dev/null +++ b/zig/src/core/contract/measurements/qmm_prefill_132.zig @@ -0,0 +1,6 @@ +//! nvcc 13.2 five-SM receipts for Qwen prefill; nvcc 13.3 produced the same usage. +const Override = @import("../registry.zig").Override; +pub const records = [_]Override{ + .{ .name = "qmm_prefill many bit-exact BF16 launch fusion", .usage = .{ .{ .regs = 172, .static = 0, .bound = 256 }, .{ .regs = 172, .static = 0, .bound = 256 }, .{ .regs = 172, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 1024, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, + .{ .name = "qmm_prefill 2x2 bit-exact BF16 GB10 large tile", .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 220, .static = 0, .bound = 128 }, .{ .regs = 220, .static = 0, .bound = 128 } } }, +}; diff --git a/zig/src/core/contract/pending_132.zig b/zig/src/core/contract/pending_132.zig index 70d41d1e7a4..09f0d0023ad 100644 --- a/zig/src/core/contract/pending_132.zig +++ b/zig/src/core/contract/pending_132.zig @@ -1,5 +1,5 @@ //! Explicit pending-launch measurements; absent names and earlier compilers stay pending. -pub const records = @import("measurements/qwen_decode_132.zig").records ++ @import("measurements/deepseek_a_132.zig").records ++ @import("measurements/deepseek_b_132.zig").records ++ @import("measurements/glm_sampling_132.zig").records ++ @import("measurements/qwen_lanes_132.zig").records; +pub const records = @import("measurements/qwen_decode_132.zig").records ++ @import("measurements/deepseek_a_132.zig").records ++ @import("measurements/deepseek_b_132.zig").records ++ @import("measurements/glm_sampling_132.zig").records ++ @import("measurements/qwen_lanes_132.zig").records ++ @import("measurements/qmm_prefill_132.zig").records; const std = @import("std"); const limits = @import("limits.zig"); diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index fbdaeb2629f..7d83d71249d 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -39,6 +39,8 @@ pub const cuda = @import("flashnext_cuda_records.zig").cuda ++ [_]CudaRecord{ .{ .launch = .{ .name = "latent tf_super_topk_few", .symbol = "tf_super_topk_few", .image = "nemotron_latent", .threads = 1024 }, .usage = .{ .{ .regs = 32, .static = 4352, .bound = 1024 }, .{ .regs = 38, .static = 4352, .bound = 1024 }, .{ .regs = 38, .static = 4352, .bound = 1024 }, .{ .regs = 30, .static = 4352, .bound = 1024 }, .{ .regs = 30, .static = 4352, .bound = 1024 } } }, .{ .launch = .{ .name = "qmm_group cluster of 8", .symbol = group_symbol, .image = "qmm_group", .threads = 128, .dynamic = 35328, .cluster = 8, .min_sm = 90 }, .usage = .{ .{ .regs = 54, .static = 0, .bound = 128 }, .{ .regs = 54, .static = 0, .bound = 128 }, .{ .regs = 54, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "qmm_group one CTA a tile", .symbol = group_symbol, .image = "qmm_group", .threads = 128, .dynamic = 35328 }, .usage = .{ .{ .regs = 54, .static = 0, .bound = 128 }, .{ .regs = 54, .static = 0, .bound = 128 }, .{ .regs = 54, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "qmm_prefill many bit-exact BF16 launch fusion", .symbol = "tf_qmm_prefill_many", .image = "qmm_prefill", .threads = 256, .dynamic = 62976, .opt_in = true, .min_sm = 121 }, .usage = .{ .{ .regs = 171, .static = 0, .bound = 256 }, .{ .regs = 171, .static = 0, .bound = 256 }, .{ .regs = 171, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 1024, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "qmm_prefill 2x2 bit-exact BF16 GB10 large tile", .symbol = "_ZN14tf_qmm_prefill14prefill_kernelILi64ELi128ELi128ELi2ELi2ELi2ELb0EEEvPK13__nv_bfloat16PKjS3_S3_Pviiiiii", .image = "qmm_prefill", .threads = 128, .dynamic = 41984 }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 214, .static = 0, .bound = 128 }, .{ .regs = 214, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "lane_gemv", .symbol = gemv_symbol, .image = "lane_gemv", .threads = 128, .dynamic = 35328 }, .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 57, .static = 0, .bound = 128 }, .{ .regs = 57, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "lane_gemv split-K", .symbol = "tf_lane_gemv_split", .image = "lane_gemv", .threads = 128, .dynamic = 17664 }, .usage = .{ .{ .regs = 62, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 44, .static = 128, .bound = 128 }, .{ .regs = 44, .static = 128, .bound = 128 } } }, .{ .launch = .{ .name = "lane_gemv segmented split-K", .symbol = "tf_lane_gemv_seg", .image = "lane_gemv", .threads = 128, .dynamic = 17664 }, .usage = .{ .{ .regs = 62, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 56, .static = 128, .bound = 128 }, .{ .regs = 54, .static = 128, .bound = 128 }, .{ .regs = 54, .static = 128, .bound = 128 } } }, diff --git a/zig/src/cuda/affine4_kernels.zig b/zig/src/cuda/affine4_kernels.zig index 9a00faa0df7..8aca362f951 100644 --- a/zig/src/cuda/affine4_kernels.zig +++ b/zig/src/cuda/affine4_kernels.zig @@ -11,6 +11,7 @@ const Split = linear.Split; const GemvPart = linear.GemvPart; const Segs = linear.Segs; const Parts = linear.Parts; +const PrefillParts = linear.PrefillParts; const symbols = linear.symbols; const splitK = linear.splitK; const group_smem = linear.group_smem; @@ -40,6 +41,7 @@ pub const Affine4Kernels = struct { seg_fn: Function, // the split form over up to four projections of one input prefill_fn: Function, prefill22_fn: Function, // the prompt tile on 2x2 warps and two stages (`half_prompt` picks it) + prefill_many_fn: Function, // GB10: one prompt grid over projections sharing the bf16 input half_prompt: bool = false, // prompts on prefill22_fn: its four warps a block and two stages are quicker on an RTX 5090 words_fn: Function, // affine4_pack.cu: MLX words into the tiles scales_fn: Function, // affine4_pack.cu: (n, kg) scales or biases into (kg, npad) @@ -57,6 +59,7 @@ pub const Affine4Kernels = struct { a.verify128_fn = try group_mod.function(symbols.verify128); a.prefill_fn = try prefill_mod.function(symbols.prefill); a.prefill22_fn = try prefill_mod.function(symbols.prefill22); + a.prefill_many_fn = try prefill_mod.function(symbols.prefill_many); a.half_prompt = false; a.gemv_fn = try gemv_mod.function(symbols.gemv); a.split_fn = try gemv_mod.function(symbols.gemv_split); @@ -72,6 +75,7 @@ pub const Affine4Kernels = struct { try a.seg_fn.allowDynamicShared(split_smem); try a.prefill_fn.allowDynamicShared(prefill_smem); try a.prefill22_fn.allowDynamicShared(linear.prefill22_smem); + try a.prefill_many_fn.allowDynamicShared(prefill_smem); a.gemv_blocks = @max(1, try a.gemv_fn.occupancy(128, group_smem)) * sms; a.pdl = gb10; a.wide_verify = false; @@ -246,6 +250,15 @@ pub const Affine4Kernels = struct { /// qmm.prefill_matmul (tile 0): weights rounded once to bf16, one fp32 chain over K; bf16 out. pub fn prompt(a: *const Affine4Kernels, s: Stream, x: u64, q: Affine4, out: u64, rows: usize) !void { + return a.promptTile(s, x, q, out, rows, a.half_prompt); + } + + /// The same arithmetic through qmm_prefill's 2x2-warp, two-stage tile. + pub fn promptHalf(a: *const Affine4Kernels, s: Stream, x: u64, q: Affine4, out: u64, rows: usize) !void { + return a.promptTile(s, x, q, out, rows, true); + } + + fn promptTile(a: *const Affine4Kernels, s: Stream, x: u64, q: Affine4, out: u64, rows: usize, half: bool) !void { const rows_t = (rows + 127) / 128; const band = (12 << 20) / (128 * q.k * 2); const group = @max(1, @min(rows_t, band)); @@ -253,9 +266,40 @@ pub const Affine4Kernels = struct { for ([_]u64{ x, q.w, q.s, q.b, out }) |v| g.add(v); for ([_]usize{ rows, q.n, q.k, q.npad, q.k, group }) |v| g.add(int(v)); const grid = rows_t * ((q.n + 127) / 128); - const f = if (a.half_prompt) a.prefill22_fn else a.prefill_fn; - const threads: u32 = if (a.half_prompt) 128 else 256; - const smem: u32 = if (a.half_prompt) linear.prefill22_smem else prefill_smem; + const f = if (half) a.prefill22_fn else a.prefill_fn; + const threads: u32 = if (half) 128 else 256; + const smem: u32 = if (half) linear.prefill22_smem else prefill_smem; try launch_.launch(f, .{ .grid = .{ .x = u(grid), .y = 1, .z = 1 }, .block = .{ .x = threads }, .shared = smem }, s, &g); } + + /// One GB10 launch over 2-4 affine-4 prompt projections, each retaining prompt()'s exact tile body. + pub fn promptMany(a: *const Affine4Kernels, s: Stream, x: u64, outs: []const Out, rows: usize) !void { + if (!a.pdl or a.half_prompt) return error.UnsupportedPromptMany; + if (outs.len < 2 or outs.len > segs_max) return error.TooManyParts; + const k = outs[0].q.k; + const rows_t = (rows + 127) / 128; + const band = (12 << 20) / (128 * k * 2); + const group = @max(1, @min(rows_t, band)); + var parts: PrefillParts = std.mem.zeroes(PrefillParts); + var blocks: usize = 0; + for (outs, 0..) |o, i| { + if (o.q.k != k) return error.InputMismatch; + parts.p[i] = .{ + .w = o.q.w, + .scales = o.q.s, + .biases = o.q.b, + .out = o.out, + .n = int(o.q.n), + .npad = int(o.q.npad), + .first = int(blocks), + }; + blocks += rows_t * ((o.q.n + 127) / 128); + } + parts.count = int(outs.len); + var g: launch_.Args = .{}; + g.add(x); + g.add(parts); + for ([_]usize{ rows, k, k, group }) |v| g.add(int(v)); + try launch_.launch(a.prefill_many_fn, .{ .grid = .{ .x = u(blocks) }, .block = .{ .x = 256 }, .shared = prefill_smem }, s, &g); + } }; diff --git a/zig/src/cuda/qlinear.zig b/zig/src/cuda/qlinear.zig index cfed86542ba..948c16263f8 100644 --- a/zig/src/cuda/qlinear.zig +++ b/zig/src/cuda/qlinear.zig @@ -234,6 +234,7 @@ pub const symbols = struct { pub const verify128 = "_ZN12tf_qmm_group12group_kernelILi64ELi128ELi64ELi1ELi4ELi3ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii"; pub const prefill = "_ZN14tf_qmm_prefill14prefill_kernelILi64ELi128ELi128ELi2ELi4ELi3ELb0EEEvPK13__nv_bfloat16PKjS3_S3_Pviiiiii"; pub const prefill22 = "_ZN14tf_qmm_prefill14prefill_kernelILi64ELi128ELi128ELi2ELi2ELi2ELb0EEEvPK13__nv_bfloat16PKjS3_S3_Pviiiiii"; + pub const prefill_many = "tf_qmm_prefill_many"; pub const gemv = "_ZN12tf_lane_gemv11gemv_kernelILi64ELi64ELi8EEEvPK13__nv_bfloat16PKfNS_4PartEiii"; pub const gemv_split = "tf_lane_gemv_split"; pub const gemv_seg = "tf_lane_gemv_seg"; @@ -245,6 +246,10 @@ pub const symbols = struct { pub const Part = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, sk: c_int, tiles: c_int, first: c_int }; pub const Parts = extern struct { p: [4]Part, count: c_int }; +/// qmm_prefill.cu's projection descriptors for one prompt grid over a shared bf16 input. +pub const PrefillPart = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, first: c_int }; +pub const PrefillParts = extern struct { p: [4]PrefillPart, count: c_int }; + /// lane_gemv.cu's Part: one projection whose column tiles the CTAs share out. pub const GemvPart = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, sk: c_int, tiles: c_int }; @@ -254,6 +259,7 @@ pub const Segs = extern struct { s: [4]Seg, count: c_int }; comptime { std.debug.assert(@sizeOf(Part) == 56 and @sizeOf(Parts) == 232 and @sizeOf(GemvPart) == 48); + std.debug.assert(@sizeOf(PrefillPart) == 48 and @sizeOf(PrefillParts) == 200); std.debug.assert(@sizeOf(Seg) == 64 and @sizeOf(Segs) == 264); } diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index c32de870d06..440f32454ad 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -379,6 +379,7 @@ pub const Engine = struct { pub const projSums = @import("cuda_projection.zig").projSums; pub const projAgain = @import("cuda_projection.zig").projAgain; pub const projMany = @import("cuda_projection.zig").projMany; + pub const projManyPrompt = @import("cuda_projection.zig").projManyPrompt; pub const projManySums = @import("cuda_projection.zig").projManySums; pub const projectMany = @import("cuda_projection.zig").projectMany; pub const project = @import("cuda_projection.zig").project; diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 246bf597ada..e0df39ace65 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -54,7 +54,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { switch (l.mixer) { .delta => |m| { const layer: c_int = @intCast(di); - try e.projMany(&.{ m.qkv, m.z, m.a, m.b }, e.x, &.{ e.qkv, e.z, e.a, e.b }, total, prompt); + try e.projManyPrompt(&.{ m.qkv, m.z, m.a, m.b }, e.x, &.{ e.qkv, e.z, e.a, e.b }, total, prompt); if (e.learning) |k| try k.delta(i, e.qkv, e.z, e.b, e.a, total); try e.run(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 @@ -66,7 +66,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { }, .attention => |m| { const aw = g.attnWidth(); - try e.projMany(&.{ m.q, m.k, m.v }, e.x, &.{ e.qraw, e.kraw, e.vraw }, total, prompt); + try e.projManyPrompt(&.{ m.q, m.k, m.v }, e.x, &.{ e.qraw, e.kraw, e.vraw }, total, prompt); if (e.learning) |k| try k.attention(i, e.qraw, e.kraw, e.vraw, total); try e.run(e.fns.head_norm, .{ total * g.q_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.qraw, m.q_norm, e.qn, @as(c_int, @intCast(g.q_heads)), @as(c_int, @intCast(2 * aw)), @as(c_int, 2 * head_dim), g.eps, t_params }); try e.run(e.fns.head_norm, .{ total * g.kv_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.kraw, m.k_norm, e.kn, @as(c_int, @intCast(g.kv_heads)), @as(c_int, @intCast(g.kv_heads * head_dim)), @as(c_int, head_dim), g.eps, t_params }); diff --git a/zig/src/families/qwen3_5/cuda_projection.zig b/zig/src/families/qwen3_5/cuda_projection.zig index fe1e9ed6744..fc53581c71f 100644 --- a/zig/src/families/qwen3_5/cuda_projection.zig +++ b/zig/src/families/qwen3_5/cuda_projection.zig @@ -1,8 +1,8 @@ //! Qwen3.5's projections: the row tiles, the prompt GEMM and the grouped form. -const std = @import("std"); const cuda = @import("cuda"); const engine = @import("cuda_engine.zig"); const int8_prompt = @import("cuda_prompt_int8.zig"); +const projection_many = @import("cuda_projection_many.zig"); const Engine = engine.Engine; const Proj = engine.Proj; @@ -23,15 +23,20 @@ pub fn projAgain(e: *Engine, l: Proj, x: u64, out: u64, rows: usize, prompt: boo /// `projAgain` of each of `ls` into `outs` over one x; on the split form's GPUs one segmented launch a row tile. pub fn projMany(e: *Engine, ls: []const Proj, x: u64, outs: []const u64, rows: usize, prompt: bool) !void { - return projectMany(e, ls, x, e.xs, outs, rows, prompt, e.tables.ptr + Engine.params_at, false); + return projectMany(e, ls, x, e.xs, outs, rows, prompt, e.tables.ptr + Engine.params_at, false, false); +} + +/// The landed forward's shared-input projections; on GB10 their prompt CTAs may share one launch. +pub fn projManyPrompt(e: *Engine, ls: []const Proj, x: u64, outs: []const u64, rows: usize, prompt: bool) !void { + return projectMany(e, ls, x, e.xs, outs, rows, prompt, e.tables.ptr + Engine.params_at, false, true); } /// `projMany` with shared input sums, preserving the caller's prompt or native projection role. pub fn projManySums(e: *Engine, ls: []const Proj, x: u64, xs: u64, outs: []const u64, rows: usize, prompt: bool, params: u64) !void { - return projectMany(e, ls, x, xs, outs, rows, prompt, params, true); + return projectMany(e, ls, x, xs, outs, rows, prompt, params, true, false); } -pub const projectMany = @import("cuda_projection_many.zig").projectMany; +pub const projectMany = projection_many.projectMany; pub fn project(e: *Engine, l: Proj, x: u64, xs: u64, out: u64, rows: usize, prompt: bool, params: u64, sums: bool) !void { if (l == .ql) return @import("cuda_modelopt.zig").project(e, l.ql, x, out, rows, prompt); @@ -57,7 +62,7 @@ pub fn project(e: *Engine, l: Proj, x: u64, xs: u64, out: u64, rows: usize, prom .ql => unreachable, }; if (prompt and rows > 16) return switch (l) { - .a4 => |q| e.affine.prompt(e.stream, x, q, out, rows), + .a4 => |q| if (qwen38LargePromptTile(e, q.n, q.k, rows)) e.affine.promptHalf(e.stream, x, q, out, rows) else e.affine.prompt(e.stream, x, q, out, rows), .an => |q| e.wide.prompt(e.stream, x, q, out, rows), .ql => unreachable, .x3, .bf => unreachable, @@ -82,3 +87,7 @@ pub fn project(e: *Engine, l: Proj, x: u64, xs: u64, out: u64, rows: usize, prom } } } + +fn qwen38LargePromptTile(e: *const Engine, n: usize, k: usize, rows: usize) bool { + return e.affine.pdl and e.g.hidden == 5120 and e.g.intermediate == 17408 and e.g.layers == 64 and e.g.experts == 0 and projection_many.qwen38LargePromptShape(n, k, rows); +} diff --git a/zig/src/families/qwen3_5/cuda_projection_many.zig b/zig/src/families/qwen3_5/cuda_projection_many.zig index b9d4331e475..5844239598e 100644 --- a/zig/src/families/qwen3_5/cuda_projection_many.zig +++ b/zig/src/families/qwen3_5/cuda_projection_many.zig @@ -1,12 +1,24 @@ //! Grouped projections share input sums and preserve each caller's arithmetic role. +const std = @import("std"); const cuda = @import("cuda"); const engine = @import("cuda_engine.zig"); const Engine = engine.Engine; const Proj = engine.Proj; -pub fn projectMany(e: *Engine, ls: []const Proj, x: u64, xs: u64, outs: []const u64, rows: usize, prompt: bool, params: u64, sums: bool) !void { +pub fn projectMany(e: *Engine, ls: []const Proj, x: u64, xs: u64, outs: []const u64, rows: usize, prompt: bool, params: u64, sums: bool, allow_fused_prompt: bool) !void { if (ls.len == 0 or ls.len != outs.len) return error.UnexpectedTensor; const A = cuda.qlinear.Affine4Kernels; + const fused_prompt = allow_fused_prompt and prompt and rows > A.max_rows and qwen38PromptShape(ls, rows) and !e.int8.on and e.affine.pdl and blk: { + const k = ls[0].inputs(); + for (ls) |l| if (l != .a4 or l.inputs() != k) break :blk false; + for (outs, 0..) |out, i| for (outs[i + 1 ..]) |other| if (out == other) break :blk false; + break :blk true; + }; + if (fused_prompt) { + var many: [A.segs_max]A.Out = undefined; + for (ls, outs, many[0..ls.len]) |l, out, *m| m.* = .{ .q = l.a4, .out = out }; + return e.affine.promptMany(e.stream, x, many[0..ls.len], rows); + } const segmented = e.affine.split != null and !(prompt and rows > 16) and ls.len <= A.segs_max and for (ls) |l| { if (l != .a4 or l.inputs() != ls[0].inputs()) break false; } else true; @@ -23,3 +35,41 @@ pub fn projectMany(e: *Engine, ls: []const Proj, x: u64, xs: u64, outs: []const try e.affine.decodeMany(e.stream, x + at * k * 2, xs + at * (k / 64) * 4, many[0..ls.len], @min(A.max_rows, rows - at)); } } + +/// Fuses only Qwen3.8 short QKV and Delta shapes that passed same-stack A-B-A screening on GB10. +fn qwen38PromptShape(ls: []const Proj, rows: usize) bool { + if (rows > 256 or (ls.len != 3 and ls.len != 4)) return false; + for (ls) |l| if (l != .a4 or l.inputs() != 5120) return false; + if (ls.len == 3) + return ls[0].outputs() == 12288 and ls[1].outputs() == 1024 and ls[2].outputs() == 1024; + return ls[0].outputs() == 10240 and ls[1].outputs() == 6144 and ls[2].outputs() == 48 and ls[3].outputs() == 48; +} + +pub fn qwen38LargePromptShape(n: usize, k: usize, rows: usize) bool { + if (rows < 2048 or k != 5120) return false; + return switch (n) { + 48, 1024, 6144, 10240, 12288, 17408 => true, + else => false, + }; +} + +test "Qwen3.8 fused prompt admits only screened BF16 projection shapes" { + const qkv = [_]Proj{ affine(12288), affine(1024), affine(1024) }; + const delta = [_]Proj{ affine(10240), affine(6144), affine(48), affine(48) }; + const mlp = [_]Proj{ affine(17408), affine(17408) }; + try std.testing.expect(qwen38PromptShape(&qkv, 256)); + try std.testing.expect(qwen38PromptShape(&delta, 17)); + try std.testing.expect(!qwen38PromptShape(&qkv, 257)); + try std.testing.expect(!qwen38PromptShape(&mlp, 128)); +} + +test "Qwen3.8 GB10 large prompt tile admits only screened projection shapes" { + try std.testing.expect(qwen38LargePromptShape(12288, 5120, 2048)); + try std.testing.expect(qwen38LargePromptShape(17408, 5120, 4096)); + try std.testing.expect(!qwen38LargePromptShape(12288, 5120, 1024)); + try std.testing.expect(!qwen38LargePromptShape(5120, 17408, 2048)); +} + +fn affine(n: usize) Proj { + return .{ .a4 = .{ .w = 0, .s = 0, .b = 0, .n = n, .k = 5120, .npad = n } }; +} diff --git a/zig/tests/cuda/contract_images_test.zig b/zig/tests/cuda/contract_images_test.zig index 9a604b6b502..8dbd25f1c54 100644 --- a/zig/tests/cuda/contract_images_test.zig +++ b/zig/tests/cuda/contract_images_test.zig @@ -10,6 +10,10 @@ test "contract image: GLM top1 selects its own image" { try std.testing.expectEqualStrings("glm_glue", try resolve("glm_glue")); } +test "contract image: qmm prefill launch fusion selects its own image" { + try std.testing.expectEqualStrings("qmm_prefill", try resolve("qmm_prefill")); +} + test "contract image: only explicit controls select the controls image" { try std.testing.expectEqualStrings("contract_controls", try resolve("contract_controls")); try std.testing.expectEqualStrings("h3", try resolve("h3")); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index a9c9690c789..2a16afa5b69 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -25,7 +25,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "h3")) return &h3_image.bytes; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_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", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "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" }) |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", "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" }) |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 &.{}; std.debug.print("FAIL kernel-contract: unknown image name: {s}\n", .{name}); return error.UnknownContractImage; diff --git a/zig/tests/cuda/contract_qmm_prefill_many.zig b/zig/tests/cuda/contract_qmm_prefill_many.zig new file mode 100644 index 00000000000..8a3ff7c86ee --- /dev/null +++ b/zig/tests/cuda/contract_qmm_prefill_many.zig @@ -0,0 +1,385 @@ +//! GB10 affine-4 prompt projections in one grid, byte-equal to one shipped prompt launch per projection. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const gpu_check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Affine = core.contract.affine.Affine; +const qlinear = cuda.qlinear; + +fn noSums(_: c.Shape) usize { + return 0; +} + +const served = [_]c.Shape{ + .{ .rows = 17, .n = 12288, .k = 5120 }, + .{ .rows = 129, .n = 10240, .k = 5120 }, + .{ .rows = 257, .n = 17408, .k = 5120 }, + .{ .rows = 33, .n = 65, .k = 512 }, +}; + +const rule = "every output byte equals separate qmm_prefill launches on the same BF16 input and affine-4 weights"; + +pub const Registrations = struct { + good: Product, + swapped: Product, + + pub fn init(gpu: gpu_check.Gpu, s: cuda.Stream, affine: *qlinear.Affine4Kernels) Registrations { + return .{ + .good = .{ .rig = .{ .gpu = gpu, .s = s }, .affine = affine }, + .swapped = .{ .rig = .{ .gpu = gpu, .s = s }, .affine = affine }, + }; + } + + pub fn deinit(self: *Registrations) void { + self.good.deinit(); + self.swapped.deinit(); + } + + pub fn append(self: *Registrations, cap: u32, a: std.mem.Allocator, kernels: *std.ArrayList(g.Kernel)) !void { + if (cap != 121) return; + try kernels.append(a, self.good.kernel()); + try kernels.append(a, swappedKernel(&self.swapped)); + } +}; + +/// Focused gate run, kept separate so a live GB10 need not retain every contract fixture at once. +pub fn run(gpu: gpu_check.Gpu) !void { + const cap = try gpu.ctx.capability(); + try gpu_check.expect(cap == 121, "qmm_prefill many contract needs sm_121, got sm_{d}", .{cap}); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + const kk = cuda.kernels; + var mods: [4]cuda.Module = undefined; + var loaded: usize = 0; + defer for (mods[0..loaded]) |*m| m.unload(); + for ([_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.affine4_pack }, 0..) |image, i| { + mods[i] = try cuda.Module.load(gpu.d, image); + loaded += 1; + } + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var affine = try qlinear.Affine4Kernels.resolve(gpu.d, mods[0], mods[1], mods[2], mods[3], sms, true); + defer affine.deinit(); + var registrations = Registrations.init(gpu, s, &affine); + defer registrations.deinit(); + var kernels: std.ArrayList(g.Kernel) = .empty; + defer kernels.deinit(gpu.gpa); + try registrations.append(cap, gpu.gpa, &kernels); + var tally: g.Tally = .{}; + try g.runAll(gpu.gpa, kernels.items, 0x1398, &tally); + std.debug.print("SUMMARY qmm_prefill_many: {d} pass, {d} fail; {d} controls red, {d} missed\n", .{ + tally.passed, tally.failed, tally.caught, tally.missed, + }); + try gpu_check.expect(tally.problems() == 0, "qmm_prefill many contract: {d} failures", .{tally.problems()}); +} + +/// Same-process A-B-A screening of separate launches against the fused launch; not an end-to-end claim. +pub fn bench(gpu: gpu_check.Gpu) !void { + const cap = try gpu.ctx.capability(); + try gpu_check.expect(cap == 121, "qmm_prefill many benchmark needs sm_121, got sm_{d}", .{cap}); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + const kk = cuda.kernels; + var mods: [4]cuda.Module = undefined; + var loaded: usize = 0; + defer for (mods[0..loaded]) |*m| m.unload(); + for ([_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.affine4_pack }, 0..) |image, i| { + mods[i] = try cuda.Module.load(gpu.d, image); + loaded += 1; + } + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var affine = try qlinear.Affine4Kernels.resolve(gpu.d, mods[0], mods[1], mods[2], mods[3], sms, true); + defer affine.deinit(); + var product = Product{ .rig = .{ .gpu = gpu, .s = s }, .affine = &affine }; + defer product.deinit(); + const cases = [_]c.Shape{ + .{ .rows = 17, .n = 12288, .k = 5120 }, .{ .rows = 17, .n = 10240, .k = 5120 }, + .{ .rows = 17, .n = 17408, .k = 5120 }, .{ .rows = 64, .n = 12288, .k = 5120 }, + .{ .rows = 64, .n = 10240, .k = 5120 }, .{ .rows = 128, .n = 12288, .k = 5120 }, + .{ .rows = 128, .n = 10240, .k = 5120 }, .{ .rows = 128, .n = 17408, .k = 5120 }, + .{ .rows = 256, .n = 12288, .k = 5120 }, .{ .rows = 256, .n = 10240, .k = 5120 }, + .{ .rows = 512, .n = 12288, .k = 5120 }, .{ .rows = 512, .n = 10240, .k = 5120 }, + .{ .rows = 512, .n = 17408, .k = 5120 }, .{ .rows = 1024, .n = 12288, .k = 5120 }, + .{ .rows = 1024, .n = 10240, .k = 5120 }, .{ .rows = 2048, .n = 12288, .k = 5120 }, + .{ .rows = 2048, .n = 10240, .k = 5120 }, .{ .rows = 2048, .n = 17408, .k = 5120 }, + .{ .rows = 4096, .n = 12288, .k = 5120 }, .{ .rows = 4096, .n = 10240, .k = 5120 }, + .{ .rows = 4096, .n = 17408, .k = 5120 }, + }; + for (cases, 0..) |shape, i| { + _ = try product.prepare(shape, .random, 0x1398 + i); + try product.baselineRun(); + try product.run(); + try gpu_check.expect((try product.check(.shapes)) == null, "qmm_prefill many benchmark parity failed at {d}x{d}x{d}", .{ shape.rows, shape.n, shape.k }); + const a1 = try product.time(false, 7, gpu.io); + const b = try product.time(true, 7, gpu.io); + const a2 = try product.time(false, 7, gpu.io); + const base: f64 = @floatFromInt(@divTrunc(a1 + a2, 2)); + const candidate: f64 = @floatFromInt(b); + std.debug.print("BENCH qmm_prefill_many rows={d} first_n={d} parts={d}: A1={d:.3} ms B={d:.3} ms A2={d:.3} ms speedup={d:.4}x\n", .{ + shape.rows, shape.n, product.parts, @as(f64, @floatFromInt(a1)) / std.time.ns_per_ms, candidate / std.time.ns_per_ms, + @as(f64, @floatFromInt(a2)) / std.time.ns_per_ms, base / candidate, + }); + } + const tile_cases = [_]c.Shape{ + .{ .rows = 2048, .n = 12288, .k = 5120 }, .{ .rows = 2048, .n = 10240, .k = 5120 }, .{ .rows = 2048, .n = 17408, .k = 5120 }, + .{ .rows = 4096, .n = 12288, .k = 5120 }, .{ .rows = 4096, .n = 10240, .k = 5120 }, .{ .rows = 4096, .n = 17408, .k = 5120 }, + }; + for (tile_cases, 0..) |shape, i| { + _ = try product.prepare(shape, .random, 0x21398 + i); + try product.separateRun(false, false); + try product.separateRun(true, true); + try gpu_check.expect((try product.checkOutputs()) == null, "qmm_prefill 2x2 tile parity failed at {d}x{d}x{d}", .{ shape.rows, shape.n, shape.k }); + const a1 = try product.timeSeparate(false, 7, gpu.io); + const b = try product.timeSeparate(true, 7, gpu.io); + const a2 = try product.timeSeparate(false, 7, gpu.io); + const base: f64 = @floatFromInt(@divTrunc(a1 + a2, 2)); + const candidate: f64 = @floatFromInt(b); + std.debug.print("BENCH qmm_prefill_tile22 rows={d} first_n={d} parts={d}: A1={d:.3} ms B={d:.3} ms A2={d:.3} ms speedup={d:.4}x\n", .{ + shape.rows, shape.n, product.parts, @as(f64, @floatFromInt(a1)) / std.time.ns_per_ms, candidate / std.time.ns_per_ms, + @as(f64, @floatFromInt(a2)) / std.time.ns_per_ms, base / candidate, + }); + } +} + +fn widths(shape: c.Shape) []const usize { + if (shape.k == 512 and shape.n == 65) return &.{ 65, 129 }; + return switch (shape.n) { + 12288 => &.{ 12288, 1024, 1024 }, + 10240 => &.{ 10240, 6144, 48, 48 }, + 17408 => &.{ 17408, 17408 }, + else => &.{}, + }; +} + +pub const Product = struct { + rig: rig_.Rig, + affine: *qlinear.Affine4Kernels, + fixtures: [4]?Affine = @splat(null), + qs: [4]qlinear.Affine4 = undefined, + outs: [4]u64 = undefined, + base: u64 = 0, + parts: usize = 0, + rows: usize = 0, + k: usize = 0, + bytes: usize = 0, + x: u64 = 0, + + pub fn kernel(self: *Product) g.Kernel { + return .{ .spec = .{ + .name = "cuda qmm_prefill many bit-exact BF16 launch fusion", + .accum = .none, + .depth = noSums, + .out = .raw, + .replaces = "one qmm_prefill launch per projection", + .nan = .{ .stated = rule }, + .served = &served, + }, .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Product); + + pub fn deinit(self: *Product) void { + self.drop(); + self.rig.deinit(); + } + + fn drop(self: *Product) void { + for (&self.fixtures) |*f| if (f.*) |owned| owned.deinit(); + self.fixtures = @splat(null); + self.parts = 0; + self.rig.reset(); + } + + pub fn prepare(self: *Product, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.drop(); + const ns = widths(shape); + if (ns.len < 2 or ns.len > self.fixtures.len or shape.rows == 0 or shape.k % 64 != 0) return false; + const a = self.rig.gpu.gpa; + self.rows = shape.rows; + self.k = shape.k; + self.parts = ns.len; + self.bytes = 0; + for (ns, 0..) |n, i| { + const f = try Affine.init(a, .{ .rows = shape.rows, .n = n, .k = shape.k }, 4, 64); + self.fixtures[i] = f; + try f.fill(fill, seed + i * 0x101); + if (i > 0) @memcpy(f.x, self.fixtures[0].?.x); + try self.pack(i, f); + self.outs[i] = try self.rig.output(shape.rows * n * 2); + self.bytes += shape.rows * n * 2; + } + self.x = try self.rig.input(std.mem.sliceAsBytes(self.fixtures[0].?.x)); + self.base = try self.rig.scratch(self.bytes); + return true; + } + + fn pack(self: *Product, i: usize, f: Affine) !void { + const a = self.rig.gpu.gpa; + const shape = f.shape; + const words = try a.alloc(u32, shape.n * shape.k / 8); + defer a.free(words); + f.words(words); + const lay = qlinear.Affine4.layout(shape.n, shape.k); + const zeros = try a.alloc(u8, lay.words); + defer a.free(zeros); + @memset(zeros, 0); + const q: qlinear.Affine4 = .{ + .w = try self.rig.input(zeros), + .s = try self.rig.input(zeros[0..lay.scales]), + .b = try self.rig.input(zeros[0..lay.scales]), + .n = shape.n, + .k = shape.k, + .npad = lay.npad, + }; + const src_w = try self.rig.scratch(words.len * 4); + const src_s = try self.rig.scratch(f.scales.len * 2); + const src_b = try self.rig.scratch(f.biases.len * 2); + for ([_]u64{ src_w, src_s, src_b }, [_][]const u8{ std.mem.sliceAsBytes(words), std.mem.sliceAsBytes(f.scales), std.mem.sliceAsBytes(f.biases) }) |p, h| { + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = p, .len = h.len }; + try b.upload(0, h); + } + try self.affine.pack(self.rig.s, src_w, src_s, src_b, q); + self.qs[i] = q; + } + + pub fn run(self: *Product) !void { + var outs: [4]qlinear.Affine4Kernels.Out = undefined; + for (outs[0..self.parts], 0..) |*o, i| o.* = .{ .q = self.qs[i], .out = self.outs[i] }; + try self.affine.promptMany(self.rig.s, self.x, outs[0..self.parts], self.rows); + try self.rig.s.synchronize(); + } + + pub fn runSwapped(self: *Product) !void { + const rows_t = (self.rows + 127) / 128; + const band = (12 << 20) / (128 * self.k * 2); + const group = @max(1, @min(rows_t, band)); + var parts: qlinear.PrefillParts = std.mem.zeroes(qlinear.PrefillParts); + var sizes: [4]usize = @splat(0); + var blocks: usize = 0; + for (self.qs[0..self.parts], self.outs[0..self.parts], 0..) |q, out, i| { + parts.p[i] = .{ + .w = q.w, + .scales = q.s, + .biases = q.b, + .out = out, + .n = @intCast(q.n), + .npad = @intCast(q.npad), + .first = @intCast(blocks), + }; + sizes[i] = rows_t * ((q.n + 127) / 128); + blocks += sizes[i]; + } + parts.count = @intCast(self.parts); + find_pair: for (0..self.parts) |i| for (i + 1..self.parts) |j| if (sizes[i] == sizes[j]) { + std.mem.swap(u64, &parts.p[i].out, &parts.p[j].out); + break :find_pair; + }; + var args: cuda.Args = .{}; + args.add(self.x); + args.add(parts); + for ([_]usize{ self.rows, self.k, self.k, group }) |v| args.add(@as(c_int, @intCast(v))); + try cuda.launch.launch(self.affine.prefill_many_fn, .{ + .grid = .{ .x = @intCast(blocks) }, + .block = .{ .x = 256 }, + .shared = qlinear.prefill_smem, + }, self.rig.s, &args); + try self.rig.s.synchronize(); + } + + pub fn runHalf(self: *Product) !void { + return self.separateRun(true, true); + } + + pub fn runHalfSwapped(self: *Product) !void { + self.affine.half_prompt = true; + defer self.affine.half_prompt = false; + var mapped = self.outs; + find_pair: for (0..self.parts) |i| for (i + 1..self.parts) |j| if (self.qs[i].n == self.qs[j].n) { + std.mem.swap(u64, &mapped[i], &mapped[j]); + break :find_pair; + }; + for (self.qs[0..self.parts], mapped[0..self.parts]) |q, out| + try self.affine.prompt(self.rig.s, self.x, q, out, self.rows); + try self.rig.s.synchronize(); + } + + pub fn replaced(self: *Product) ![]const u8 { + try self.baselineRun(); + return self.rig.bytes(self.base, self.bytes); + } + + fn baselineRun(self: *Product) !void { + try self.separateRun(false, false); + } + + fn separateRun(self: *Product, half: bool, outputs: bool) !void { + return self.separateRunAt(half, outputs, 0); + } + + fn separateRunAt(self: *Product, half: bool, outputs: bool, shift: u64) !void { + self.affine.half_prompt = half; + defer self.affine.half_prompt = false; + var at: usize = 0; + for (self.qs[0..self.parts], 0..) |q, i| { + try self.affine.prompt(self.rig.s, self.x, q, if (outputs) self.outs[i] + shift else self.base + at, self.rows); + at += self.rows * q.n * 2; + } + try self.rig.s.synchronize(); + } + + fn time(self: *Product, candidate: bool, reps: usize, io: std.Io) !i96 { + const start = gpu_check.now(io); + for (0..reps) |_| if (candidate) try self.run() else try self.baselineRun(); + return @divTrunc(gpu_check.now(io) - start, @as(i96, @intCast(reps))); + } + + fn timeSeparate(self: *Product, half: bool, reps: usize, io: std.Io) !i96 { + const start = gpu_check.now(io); + for (0..reps) |_| try self.separateRun(half, false); + return @divTrunc(gpu_check.now(io) - start, @as(i96, @intCast(reps))); + } + + fn checkOutputs(self: *Product) !?[]const u8 { + const got = try self.rig.gpu.gpa.dupe(u8, try self.rig.outputBytes()); + defer self.rig.gpu.gpa.free(got); + const want = try self.rig.bytes(self.base, self.bytes); + return if (std.mem.eql(u8, got, want)) null else rule; + } + + pub fn check(self: *Product, _: c.Gate) !?[]const u8 { + const got = try self.rig.gpu.gpa.dupe(u8, try self.rig.outputBytes()); + defer self.rig.gpu.gpa.free(got); + const want = try self.replaced(); + return if (std.mem.eql(u8, got, want)) null else rule; + } + + pub fn count(self: *Product) usize { + return self.bytes; + } + + pub fn reference(_: *Product, _: []f64, _: []f64) !void {} +}; + +fn swappedKernel(product: *Product) g.Kernel { + var k = product.kernel(); + k.spec.name = "control: qmm_prefill many swaps two equal-width output bindings"; + // Product.check snapshots bad bytes before the replacement comparison reuses the rig readback buffer. + k.spec.replaces = null; + k.vt = &swapped_vt; + k.control = .shapes; + return k; +} + +const swapped_vt: g.VTable = blk: { + var vt = g.hooks(Product); + vt.run = runSwapped; + break :blk vt; +}; + +fn runSwapped(ctx: *anyopaque) anyerror!void { + const product: *Product = @ptrCast(@alignCast(ctx)); + return product.runSwapped(); +} diff --git a/zig/tests/cuda/contract_qmm_prefill_tile22.zig b/zig/tests/cuda/contract_qmm_prefill_tile22.zig new file mode 100644 index 00000000000..fe3d4e1fa5d --- /dev/null +++ b/zig/tests/cuda/contract_qmm_prefill_tile22.zig @@ -0,0 +1,125 @@ +//! Qwen3.8 GB10 large affine-4 prompts on the shipped 2x2-warp tile, byte-equal to the default tile. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const gpu_check = @import("check.zig"); +const many = @import("contract_qmm_prefill_many.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const qlinear = cuda.qlinear; + +fn noSums(_: c.Shape) usize { + return 0; +} + +const served = [_]c.Shape{ + .{ .rows = 2048, .n = 12288, .k = 5120 }, + .{ .rows = 2048, .n = 10240, .k = 5120 }, + .{ .rows = 2048, .n = 17408, .k = 5120 }, + .{ .rows = 4096, .n = 12288, .k = 5120 }, + .{ .rows = 4096, .n = 10240, .k = 5120 }, + .{ .rows = 4096, .n = 17408, .k = 5120 }, +}; + +const rule = "every output byte equals qmm_prefill's default 2x4-warp tile on the same BF16 input and affine-4 weights"; + +pub const Registrations = struct { + good: many.Product, + swapped: many.Product, + + pub fn init(gpu: gpu_check.Gpu, s: cuda.Stream, affine: *qlinear.Affine4Kernels) Registrations { + return .{ + .good = .{ .rig = .{ .gpu = gpu, .s = s }, .affine = affine }, + .swapped = .{ .rig = .{ .gpu = gpu, .s = s }, .affine = affine }, + }; + } + + pub fn deinit(self: *Registrations) void { + self.good.deinit(); + self.swapped.deinit(); + } + + pub fn append(self: *Registrations, cap: u32, a: std.mem.Allocator, kernels: *std.ArrayList(g.Kernel)) !void { + if (cap != 121) return; + try kernels.append(a, kernel(&self.good)); + try kernels.append(a, swappedKernel(&self.swapped)); + } +}; + +pub fn run(gpu: gpu_check.Gpu) !void { + const cap = try gpu.ctx.capability(); + try gpu_check.expect(cap == 121, "qmm_prefill 2x2 tile contract needs sm_121, got sm_{d}", .{cap}); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + const kk = cuda.kernels; + var mods: [4]cuda.Module = undefined; + var loaded: usize = 0; + defer for (mods[0..loaded]) |*m| m.unload(); + for ([_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.affine4_pack }, 0..) |image, i| { + mods[i] = try cuda.Module.load(gpu.d, image); + loaded += 1; + } + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var affine = try qlinear.Affine4Kernels.resolve(gpu.d, mods[0], mods[1], mods[2], mods[3], sms, true); + defer affine.deinit(); + var registrations = Registrations.init(gpu, s, &affine); + defer registrations.deinit(); + var kernels: std.ArrayList(g.Kernel) = .empty; + defer kernels.deinit(gpu.gpa); + try registrations.append(cap, gpu.gpa, &kernels); + var tally: g.Tally = .{}; + try g.runAll(gpu.gpa, kernels.items, 0x221398, &tally); + std.debug.print("SUMMARY qmm_prefill_tile22: {d} pass, {d} fail; {d} controls red, {d} missed\n", .{ + tally.passed, tally.failed, tally.caught, tally.missed, + }); + try gpu_check.expect(tally.problems() == 0, "qmm_prefill 2x2 tile contract: {d} failures", .{tally.problems()}); +} + +pub fn kernel(product: *many.Product) g.Kernel { + return .{ + .spec = .{ + .name = "cuda qmm_prefill 2x2 bit-exact BF16 GB10 large tile", + .accum = .none, + .depth = noSums, + .out = .raw, + .replaces = "qmm_prefill's default 2x4-warp, three-stage tile", + .nan = .{ .stated = rule }, + .served = &served, + }, + .ctx = product, + .vt = &tile_vt, + }; +} + +const tile_vt: g.VTable = blk: { + var vt = g.hooks(many.Product); + vt.run = runHalf; + break :blk vt; +}; + +fn runHalf(ctx: *anyopaque) anyerror!void { + const product: *many.Product = @ptrCast(@alignCast(ctx)); + return product.runHalf(); +} + +fn swappedKernel(product: *many.Product) g.Kernel { + var k = kernel(product); + k.spec.name = "control: qmm_prefill 2x2 swaps two equal-width output bindings"; + // Product.check snapshots the swapped output before the replacement readback reuses the rig buffer. + k.spec.replaces = null; + k.vt = &swapped_vt; + k.control = .shapes; + return k; +} + +const swapped_vt: g.VTable = blk: { + var vt = g.hooks(many.Product); + vt.run = runSwapped; + break :blk vt; +}; + +fn runSwapped(ctx: *anyopaque) anyerror!void { + const product: *many.Product = @ptrCast(@alignCast(ctx)); + return product.runHalfSwapped(); +} diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index 4db855a9965..65af43f23c5 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -10,6 +10,8 @@ const tail_k = @import("contract_norms_tail.zig"); const dory_k = @import("contract_dory.zig"); const router_k = @import("contract_router.zig"); const mm_k = @import("contract_mm.zig"); +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"); @@ -34,9 +36,7 @@ const vit_k = @import("contract_vit_glue.zig"); const act_round_k = @import("contract_act_round.zig"); const f32w_k = @import("contract_glm_f32w.zig"); 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 gdn_k = @import("contract_gdn.zig"); @@ -47,11 +47,9 @@ const glm_index_k = @import("contract_glm_index.zig"); const glm_attn_k = @import("contract_glm_attn.zig"); const glm = @import("glm_cuda"); const elementwise_k = @import("contract_elementwise.zig"); - const tree_k = @import("contract_tree_attn.zig"); const block_k = @import("contract_block_attn.zig"); const q35_k = @import("contract_q35_attn.zig"); - const window_k = @import("contract_window.zig"); const moe_k = @import("contract_moe.zig"); const qkr_k = @import("contract_qk_round.zig"); @@ -59,7 +57,6 @@ const fact_k = @import("contract_flashnext_fact.zig"); const route_k = @import("contract_route_rows.zig"); const fexp_k = @import("contract_flashnext_fexp.zig"); const glue_k = @import("contract_flashnext_glue.zig"); - const q35_contiguous = @import("contract_q35_contiguous.zig"); const contract = core.contract; const g = contract.gates; @@ -208,6 +205,12 @@ pub fn run(gpu: check.Gpu) !void { } defer for (&verify_controls) |*m| m.deinit(); for (&verify_controls) |*m| if (m.kernel()) |k| try kernels.append(a, k); + var prefill_many = prefill_many_k.Registrations.init(gpu, s, &affine4); + defer prefill_many.deinit(); + try prefill_many.append(cap, a, &kernels); + var prefill_tile22 = prefill_tile22_k.Registrations.init(gpu, s, &affine4); + defer prefill_tile22.deinit(); + try prefill_tile22.append(cap, a, &kernels); var mx = [_]mx_k.Product{ .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane, .clusters = true }, .{ .rig = .{ .gpu = gpu, .s = s }, .lane = &lane_reduce, .clusters = false }, diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 147128a05a7..f703f53288c 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -55,6 +55,8 @@ const embed_tests = @import("embed_tests.zig"); const pocket_tests = @import("pocket_tests.zig"); const recapture_tests = @import("recapture_tests.zig"); const contract_tests = @import("contract_tests.zig"); +const qmm_prefill_many_contract = @import("contract_qmm_prefill_many.zig"); +const qmm_prefill_tile22_contract = @import("contract_qmm_prefill_tile22.zig"); const glue_contract = @import("contract_flashnext_glue.zig"); const lfm2_attention_tests = @import("lfm2_attention_tests.zig"); const lfm2_kernel_tests = @import("lfm2_kernel_tests.zig"); @@ -223,6 +225,9 @@ const usage = \\ exl3-tiles [DIR] EXL3's tile candidate: codebooks and tiles bit-equal, FP64, rows through qlinear and Dense \\ train-pack MODEL EXAMPLES [COUNT] training passes holding several sequences against one a pass: differences, time \\ kernel-contract the registered kernels through the contract's gates, each planted control red (needs -Dnvcc) + \\ qmm-prefill-many-contract the GB10 bit-exact multi-projection prompt launch against separate launches + \\ qmm-prefill-tile22-contract the GB10 large-prompt 2x2 tile against the default tile + \\ qmm-prefill-many-bench same-process A-B-A screening for the GB10 launch fusion \\ qwen-pages qwen35.cu's attention cache through a page table: paged == contiguous, float64, red controls \\ kernel-contract-limits DIR each registered launch against sm_80/86/89/120/121 from the fatbins in DIR \\ glm-exl3 GLM's EXL3 routed experts, decode and prompt, against float64 (synthetic) @@ -438,6 +443,9 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "q27-gemm")) return q27_gemm_tests.run(gpu); if (std.mem.eql(u8, cmd, "gdn-back-27b")) return gdn_back_tests.runShape(gpu, 5120, 64); if (std.mem.eql(u8, cmd, "kernel-contract")) return contract_tests.run(gpu); + if (std.mem.eql(u8, cmd, "qmm-prefill-many-contract")) return qmm_prefill_many_contract.run(gpu); + if (std.mem.eql(u8, cmd, "qmm-prefill-tile22-contract")) return qmm_prefill_tile22_contract.run(gpu); + if (std.mem.eql(u8, cmd, "qmm-prefill-many-bench")) return qmm_prefill_many_contract.bench(gpu); if (std.mem.eql(u8, cmd, "qwen-pages")) return @import("contract_qwen_pages.zig").run(gpu); if (std.mem.eql(u8, cmd, "kernel-contract-limits")) return contract_tests.fatbins(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "tree")) return tree_tests.run(gpu); diff --git a/zig/tests/qwen35_cuda_main.zig b/zig/tests/qwen35_cuda_main.zig index bbbf6795ce8..1133db8ce00 100644 --- a/zig/tests/qwen35_cuda_main.zig +++ b/zig/tests/qwen35_cuda_main.zig @@ -1,4 +1,4 @@ -//! `tf-qwen35-cuda ...`: rows to compare; usage below. +//! `tf-qwen35-cuda ...`: rows to compare; usage below. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -7,13 +7,14 @@ const E = q.engine; const vl = core.qwen_vl; const usage = - \\usage: tf-qwen35-cuda [fp8] + \\usage: tf-qwen35-cuda [fp8] \\ tf-qwen35-cuda probe : a routed model's routing and rows at that layer \\ tf-qwen35-cuda mtp : the MTP drafter's tree regressions after a prompt \\ tf-qwen35-cuda vision [--bound MEAN WORST] ... \\vision prepares each picture with core/qwen_vl under a budget and runs the CUDA tower twice: \\gets NAME.pixels.f32, NAME.rows.f32 (bf16 widened) and meta.json; NAME.ref.f32 there (float32 reference rows) is \\compared row by row (relative L2, worst and mean); --bound needs every reference and exits 1 past either bound. + \\state: raw GDN/conv and active KV bytes; TF_Q35_STATE_STEPS=N settles N decode rows first. \\fp8: the attention caches as e4m3 rows (--kv-cache fp8); TF_Q35_PREFILL, _BESIDE, _DELTA, _RESUME, _SHIFT: below. \\TF_Q35_WINDOW=N fixes window/tree width (tree: at least 2); 0 keeps growing widths. \\ tf-qwen35-cuda kl [control|int8] @@ -69,9 +70,10 @@ pub fn main(init: std.process.Init) !u8 { try fill(e, &cache, ids.items, prefill); // TF_Q35_DELTA=d: the rows after the prefill rotate at position + d, as an image prompt's reply does if (std.c.getenv("TF_Q35_DELTA")) |v| cache.delta = try std.fmt.parseInt(i32, std.mem.span(v), 10); - // TF_Q35_RESUME=1: the stream goes on from a kept copy of its state, restored into another (poisoned) cache + // TF_Q35_RESUME=K: continue from a kept copy at K, restored into another poisoned cache const resume_at = try envCount("TF_Q35_RESUME"); - if (resume_at > 0 and !std.mem.eql(u8, args[2], "prompt") and !std.mem.eql(u8, args[2], "mrope")) try resumeFrom(init.gpa, e, &cache); + const state = std.mem.eql(u8, args[2], "state"); + if (resume_at > 0 and !std.mem.eql(u8, args[2], "prompt") and !state and !std.mem.eql(u8, args[2], "mrope")) try resumeFrom(init.gpa, e, &cache); var other = try E.Cache.init(init.gpa, e, 4096 + beside); defer other.deinit(init.gpa); try fill(e, &other, ids.items, beside); @@ -195,17 +197,31 @@ pub fn main(init: std.process.Init) !u8 { const p0 = cache.len; var at: usize = 0; while (at < n_ids) { - const n = @min(E.max_rows, n_ids - at); + var n = @min(E.max_rows, n_ids - at); + if (resume_at > cache.len and resume_at < cache.len + n) { + n = @intCast(resume_at - cache.len); + } if (table) { // the table's rows are the prompt's from position p0: shift it so row `at` is the cache's next const part: E.Images = .{ .features = im.features, .src = try padded(a, src, p0), .pos = try paddedPos(a, pos, p0, n_ids) }; try e.forward(&.{.{ .cache = &cache, .rows = n, .images = &part }}, ids.items[at..][0..n], .last); } else try e.forward(&.{.{ .cache = &cache, .rows = n }}, ids.items[at..][0..n], .last); at += n; - // TF_Q35_RESUME=K in prompt and mrope: the pass goes on from a kept copy at position K + // TF_Q35_RESUME=K in prompt, state and mrope: the pass goes on from a kept copy at position K if (resume_at > 0 and cache.len == resume_at) try resumeFrom(init.gpa, e, &cache); } - try out.appendSlice(a, std.mem.sliceAsBytes(cache.logits)); + if (state) { + const steps = try envCount("TF_Q35_STATE_STEPS"); + if (steps > 0 and ids.items.len == 0) return error.NoStateTokens; + for (0..steps) |i| { + const token = [_]u32{ids.items[i % ids.items.len]}; + try e.forward(&.{.{ .cache = &cache, .rows = 1 }}, &token, .logits); + try cache.settle(e); + } + const copy = try q.reuse.saveCache(e, &cache, cache.len, &.{}); + defer q.reuse.dropCopy(e, copy); + try out.appendSlice(a, copy.host.bytes[0..@intCast(copy.len)]); + } else try out.appendSlice(a, std.mem.sliceAsBytes(cache.logits)); } try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[4], .data = out.items }); return 0;