diff --git a/CHANGELOG.md b/CHANGELOG.md index 7861f35a3a9..f41e181ec3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA kernels: ERNIE 5.5's DSA key lists (`tf_ernie55_window_merge`, in a new `ernie5_5_index` image): each row's indexer top-k picks, then its 128-position sliding window, with the row's count, as the sparse MLA reads them; under the kernel contract against the host's lists; nothing launches it yet, so served output is unchanged (#5211, part of #4926). + - CUDA: Qwen with `--kv-cache fp8` gives the same tokens with the default `TF_QWEN_PDL` on as with it off; the FP8 RoPE kernel no longer starts before its head norms finish (#PR, fixes #5308). Thanks to @jojomondag for the report. - Tools: a device check that drafted output equals plain output under seeded sampling, on Metal and CUDA, for releases and PR qualification (#5249). diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 4979a4d85c4..47aaa9a479b 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -705,6 +705,15 @@ once in the vendor's order with nothing fused. Each output must be the host's re TP=2 rank's half; gate 4 runs whole logits with whole ranges and power-of-two weights, where every step is exact (`ernie5_5-head`; two controls: each term's multiply and add fused into an fma, and the last term's square dropped). +CUDA also checks ERNIE 5.5's DSA key lists (`ernie5_5/index.cu`, `tf_ernie55_window_merge`): each row's indexer +picks (`topk_rows`' out, `picked` of them held to [0, k] and ending at the first -1), then its sliding window's +min(seq, 128) positions up to seq - 1, then -1, as vLLM-ERNIE's `merge_swa_topk` lays them out for the sparse MLA, +with the count of entries a row. The lists must be the host's (`ernie5_5/window.zig`) to the byte, and every row's +entries, rows told a negative count or one past k included, are rows below seq that ascend to seq - 1 with its picks +below the window, from a decode row at the first position and deep in context, across seq = 128 and seq = k + 128, +to prompt chunks and the 1M context's last rows (`ernie5_5-index`; two controls: every row taking all k picks, and +the window's oldest position dropped). + CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn, diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 6d4286605ef..b8e1db710c9 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -137,6 +137,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("hy4_ihc_fused_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/ihc_fused_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("ernie5_5_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_head.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("hy4_route_rows_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/rows_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); + runner.addImport("ernie5_5_index_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_index.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("gemma4_cuda", @import("gemma4_cuda.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); runner.addImport("spark25", @import("spark25.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); // the served family and its engine, for the dots runner diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 7800044fcad..47d5e94d677 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -169,6 +169,7 @@ pub const kernels = [_]Kernel{ .{ .name = "hy4_route", .src = "hy4_flash/route", .flags = glue }, .{ .name = "hy4_rows", .src = "hy4_flash/rows", .flags = &.{"-O3"} }, .{ .name = "hy4_dfly2_glue", .src = "hy4_flash/dfly2_glue", .flags = glue }, + .{ .name = "ernie5_5_index", .src = "ernie5_5/index", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's DSA key lists .{ .name = "minimax_m3", .flags = glue }, // ours: MiniMax-M3.1-Flash's glue (norms, RoPE prep, routing, DSpark, tower RoPE) .{ .name = "minimax_m3_attn", .flags = glue }, // ours: MiniMax-M3.1-Flash's indexer and block-sparse attention .{ .name = "idol", .flags = glue }, // ours: Idol's denoiser glue and its fp16 head-64 attention diff --git a/zig/kernels/cuda/ernie5_5/index.cu b/zig/kernels/cuda/ernie5_5/index.cu new file mode 100644 index 00000000000..300359b139f --- /dev/null +++ b/zig/kernels/cuda/ernie5_5/index.cu @@ -0,0 +1,55 @@ +// ERNIE 5.5's sparse-attention key lists: each row's indexer picks, then its sliding window, for the sparse MLA. + +namespace ernie55i { + +enum Fault { none, all_picks, short_window }; + +// Row blockIdx.x at pos[0] + row: picks to picked[row] in [0, k] and the first -1, the window to seq - 1, -1, a count. +template +__device__ __forceinline__ void merge(const int* __restrict__ picks, const int* __restrict__ picked, + const int* __restrict__ pos, int* __restrict__ tok, int* __restrict__ cnt, int k, + int window, long long w) { + __shared__ int valid; + const long long row = blockIdx.x, seq = static_cast(pos[0]) + row + 1; + const int p = picked[row]; + const long long held = F == all_picks ? k : p < 0 ? 0 : p > k ? k : p; + const long long sw = (seq < window ? seq : window) - (F == short_window ? 1 : 0), first = seq - sw; + const int* in = picks + row * k; + if (threadIdx.x == 0) valid = static_cast(held); + __syncthreads(); + // a negative pick inside the held count ends the picks (the control keeps every pick it is told) + if (F != all_picks) + for (long long c = threadIdx.x; c < held; c += blockDim.x) + if (in[c] < 0) atomicMin(&valid, static_cast(c)); + __syncthreads(); + const long long n = valid; + int* out = tok + row * w; + for (long long c = threadIdx.x; c < w; c += blockDim.x) + out[c] = c < n ? in[c] : c < n + sw ? static_cast(first + (c - n)) : -1; + if (threadIdx.x == 0) cnt[row] = static_cast(n + sw); +} + +} // namespace ernie55i + +// One row a block of 256 threads; lists w wide (at least k + window). +extern "C" __global__ void __launch_bounds__(256) + tf_ernie55_window_merge(const int* __restrict__ picks, const int* __restrict__ picked, const int* __restrict__ pos, + int* __restrict__ tok, int* __restrict__ cnt, int k, int window, long long w) { + ernie55i::merge(picks, picked, pos, tok, cnt, k, window, w); +} + +// The contract's planted control: every row takes all k picks, its -1s past picked among them. +extern "C" __global__ void __launch_bounds__(256) + tf_ctl_ernie55_window_merge_all_picks(const int* __restrict__ picks, const int* __restrict__ picked, + const int* __restrict__ pos, int* __restrict__ tok, int* __restrict__ cnt, + int k, int window, long long w) { + ernie55i::merge(picks, picked, pos, tok, cnt, k, window, w); +} + +// The contract's planted control: the window's oldest position dropped. +extern "C" __global__ void __launch_bounds__(256) + tf_ctl_ernie55_window_merge_short_window(const int* __restrict__ picks, const int* __restrict__ picked, + const int* __restrict__ pos, int* __restrict__ tok, + int* __restrict__ cnt, int k, int window, long long w) { + ernie55i::merge(picks, picked, pos, tok, cnt, k, window, w); +} diff --git a/zig/src/core/contract/ernie5_5_records.zig b/zig/src/core/contract/ernie5_5_records.zig index ac96730c856..4c66d1e838b 100644 --- a/zig/src/core/contract/ernie5_5_records.zig +++ b/zig/src/core/contract/ernie5_5_records.zig @@ -1,9 +1,10 @@ -//! ERNIE 5.5's CUDA launches (ernie5_5/head.cu): MultiMax on the head's fp32 logits. +//! ERNIE 5.5's CUDA launches: MultiMax on the head's fp32 logits (ernie5_5/head.cu), the DSA key lists (index.cu). const registry = @import("registry.zig"); /// nvcc 13.0's usage (nvcc -cubin per SM at the image's flags), the compiler of the release fatbins. pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "ernie5_5 head tf_ernie55_multimax", .symbol = "tf_ernie55_multimax", .image = "ernie5_5_head", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "ernie5_5 index tf_ernie55_window_merge", .symbol = "tf_ernie55_window_merge", .image = "ernie5_5_index", .threads = 256 }, .usage = .{ .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 40, .static = 4, .bound = 256 }, .{ .regs = 40, .static = 4, .bound = 256 } } }, }; test "ERNIE 5.5 CUDA: every launch is in the live registry and fits every SM" { diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 83f1d82bd81..64e8c3d9b10 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -121,6 +121,7 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const ernie5_5_head: []const u8 = if (available) &Blob("fatbin_ernie5_5_head").bytes else &.{}; +pub const ernie5_5_index: []const u8 = if (available) &Blob("fatbin_ernie5_5_index").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; pub const inkling2_dspark: []const u8 = if (available) &Blob("fatbin_inkling2_dspark").bytes else &.{}; pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; diff --git a/zig/src/families/ernie5_5/cuda_index.zig b/zig/src/families/ernie5_5/cuda_index.zig new file mode 100644 index 00000000000..58ded76cfdc --- /dev/null +++ b/zig/src/families/ernie5_5/cuda_index.zig @@ -0,0 +1,37 @@ +//! ERNIE 5.5's indexer kernels (ernie5_5/index.cu): the sparse MLA's key lists, each row's picks then its window. +const cuda = @import("cuda"); +pub const window = @import("window.zig"); + +pub const threads = 256; + +pub const Index = struct { + mod: cuda.Module, + merge_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Index { + var mod = try cuda.Module.load(d, cuda.kernels.ernie5_5_index); + errdefer mod.unload(); + return .{ .mod = mod, .merge_fn = try mod.function("tf_ernie55_window_merge") }; + } + + pub fn unload(x: *Index) void { + x.mod.unload(); + } + + /// topk_rows' out and picked, pos (row r at pos[0] + r) into tok i32 [rows, w] and cnt i32 [rows], as window.merge. + pub fn merge(x: *const Index, s: cuda.Stream, picks: u64, picked: u64, pos: u64, tok: u64, cnt: u64, sh: window.Shape) !void { + try launch(x.merge_fn, s, picks, picked, pos, tok, cnt, sh); + } +}; + +/// `f`, tf_ernie55_window_merge or an entry of the image with its arguments, one row a block. +pub fn launch(f: cuda.Function, s: cuda.Stream, picks: u64, picked: u64, pos: u64, tok: u64, cnt: u64, sh: window.Shape) !void { + try window.check(sh); + if (sh.rows == 0) return; + var a: cuda.Args = .{}; + inline for (.{ picks, picked, pos, tok, cnt }) |v| a.add(v); + a.add(@as(c_int, @intCast(sh.k))); + a.add(@as(c_int, @intCast(sh.window))); + a.add(@as(i64, @intCast(sh.w))); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.rows) }, .block = .{ .x = threads } }, s, &a); +} diff --git a/zig/src/families/ernie5_5/host_test.zig b/zig/src/families/ernie5_5/host_test.zig index 87eb8801859..a104644b49f 100644 --- a/zig/src/families/ernie5_5/host_test.zig +++ b/zig/src/families/ernie5_5/host_test.zig @@ -1,4 +1,4 @@ -//! Host-only ERNIE 5.5 family package: config, weight map, layer plan, chat encoding, tokenizer, MultiMax. No GPU. +//! Host-only ERNIE 5.5 family: config, weight map, layer plan, chat encoding, tokenizer, MultiMax, key lists. No GPU. test { _ = @import("config.zig"); _ = @import("config_test.zig"); @@ -9,4 +9,5 @@ test { _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); _ = @import("multimax_test.zig"); + _ = @import("window_test.zig"); } diff --git a/zig/src/families/ernie5_5/window.zig b/zig/src/families/ernie5_5/window.zig new file mode 100644 index 00000000000..92554c1b0f5 --- /dev/null +++ b/zig/src/families/ernie5_5/window.zig @@ -0,0 +1,33 @@ +//! ERNIE 5.5's sparse-attention key lists: each row's indexer picks, then its sliding window (vLLM's merge_swa_topk). +const std = @import("std"); + +/// The released config's sliding_window and index_topk. +pub const window = 128; +pub const topk = 2048; + +/// rows rows, row r at position pos0 + r; k picks a row in, lists w wide out (at least k + window). +pub const Shape = struct { rows: usize, k: usize, w: usize, window: usize = window }; + +/// Sizes the kernel holds in i32, and lists wide enough for every pick and the window. +pub fn check(sh: Shape) error{WindowShape}!void { + const most = std.math.maxInt(i32); + if (sh.window == 0 or sh.k > most or sh.window > most or sh.w < sh.k + sh.window or sh.rows > most / sh.w) + return error.WindowShape; +} + +/// Row r: picks to picked[r] (in [0, k]) and the first negative, seq - min(seq, window) .. seq - 1, -1, its count. +pub fn merge(sh: Shape, picks: []const i32, picked: []const i32, pos0: i64, tok: []i32, cnt: []i32) void { + for (0..sh.rows) |r| { + const seq = pos0 + @as(i64, @intCast(r)) + 1; + const held: usize = @intCast(std.math.clamp(picked[r], 0, @as(i32, @intCast(sh.k)))); + const n = for (picks[r * sh.k ..][0..held], 0..) |v, i| { + if (v < 0) break i; // a negative pick inside the count ends the picks + } else held; + const sw: usize = @intCast(@min(seq, @as(i64, @intCast(sh.window)))); + const row = tok[r * sh.w ..][0..sh.w]; + @memcpy(row[0..n], picks[r * sh.k ..][0..n]); + for (row[n..][0..sw], 0..) |*t, i| t.* = @intCast(seq - @as(i64, @intCast(sw)) + @as(i64, @intCast(i))); + @memset(row[n + sw ..], -1); + cnt[r] = @intCast(n + sw); + } +} diff --git a/zig/src/families/ernie5_5/window_test.zig b/zig/src/families/ernie5_5/window_test.zig new file mode 100644 index 00000000000..7d669627b54 --- /dev/null +++ b/zig/src/families/ernie5_5/window_test.zig @@ -0,0 +1,99 @@ +//! window.zig against vLLM-ERNIE's merge_swa_topk, and its refusals. +const std = @import("std"); +const win = @import("window.zig"); + +/// merge_swa_topk as the vendor's Triton kernel writes a column: its n from the position, not from picked. +fn vendor(topk: []const i32, k: usize, window: usize, seq: i64, col: usize) i32 { + const n: i64 = @min(@max(seq - @as(i64, @intCast(window)), 0), @as(i64, @intCast(k))); + const sw: i64 = @min(seq, @as(i64, @intCast(window))); + const c: i64 = @intCast(col); + if (c < n) return topk[col]; + return if (c < n + sw) @intCast(seq - sw + c - n) else -1; +} + +fn run(a: std.mem.Allocator, sh: win.Shape, pos0: i64, picks: []const i32, picked: []const i32) !struct { []i32, []i32 } { + const tok = try a.alloc(i32, sh.rows * sh.w); + const cnt = try a.alloc(i32, sh.rows); + win.merge(sh, picks, picked, pos0, tok, cnt); + return .{ tok, cnt }; +} + +test "with picked as top-k gives it, each list is the vendor's, across the window's and the picks' edges" { + const a = std.testing.allocator; + inline for (.{ .{ 4, 3, 9 }, .{ win.topk, win.window, win.topk + win.window + 64 } }) |g| { + const k: usize = g[0]; + const sh: win.Shape = .{ .rows = 2 * (k + g[1]) + 3, .k = k, .w = g[2], .window = g[1] }; + const picks = try a.alloc(i32, sh.rows * k); + defer a.free(picks); + const picked = try a.alloc(i32, sh.rows); + defer a.free(picked); + for (0..sh.rows) |r| { + const seq: i64 = @intCast(r + 1); + const n: usize = @intCast(@min(@max(seq - @as(i64, @intCast(sh.window)), 0), @as(i64, @intCast(k)))); + picked[r] = @intCast(n); + // n ascending picks spread below seq - window, as topk_rows leaves them, then -1 + const older = seq - @as(i64, @intCast(sh.window)); + for (picks[r * k ..][0..k], 0..) |*p, i| p.* = if (i < n) @intCast(@divFloor(@as(i64, @intCast(i)) * older, @as(i64, @intCast(n)))) else -1; + } + const tok, const cnt = try run(a, sh, 0, picks, picked); + defer a.free(tok); + defer a.free(cnt); + for (0..sh.rows) |r| { + const seq: i64 = @intCast(r + 1); + var valid: i32 = 0; + for (0..sh.w) |c| { + const want = vendor(picks[r * k ..][0..k], k, sh.window, seq, c); + try std.testing.expectEqual(want, tok[r * sh.w + c]); + valid += @intFromBool(want != -1); + } + try std.testing.expectEqual(valid, cnt[r]); + try std.testing.expectEqual(@as(i32, @intCast(seq - 1)), tok[r * sh.w + @as(usize, @intCast(cnt[r])) - 1]); + } + } +} + +test "rows from a later position: the window ends at each row's own position" { + const a = std.testing.allocator; + const sh: win.Shape = .{ .rows = 3, .k = 2, .w = 6, .window = 3 }; + const picks = [_]i32{ 5, 90, 7, 91, 8, 92 }; + const tok, const cnt = try run(a, sh, 99, &picks, &.{ 2, 2, 2 }); + defer a.free(tok); + defer a.free(cnt); + try std.testing.expectEqualSlices(i32, &.{ 5, 90, 97, 98, 99, -1, 7, 91, 98, 99, 100, -1, 8, 92, 99, 100, 101, -1 }, tok); + try std.testing.expectEqualSlices(i32, &.{ 5, 5, 5 }, cnt); +} + +test "picked is held to [0, k]: a negative one lists the window alone, one past k lists k picks" { + const a = std.testing.allocator; + const sh: win.Shape = .{ .rows = 2, .k = 2, .w = 5, .window = 2 }; + const tok, const cnt = try run(a, sh, 9, &.{ 1, 2, 3, 4 }, &.{ -3, 7 }); + defer a.free(tok); + defer a.free(cnt); + try std.testing.expectEqualSlices(i32, &.{ 8, 9, -1, -1, -1, 3, 4, 9, 10, -1 }, tok); + try std.testing.expectEqualSlices(i32, &.{ 2, 4 }, cnt); +} + +test "a count past the picks' nonnegative prefix stops at the first -1: no -1 before a list's count" { + const a = std.testing.allocator; + const sh: win.Shape = .{ .rows = 2, .k = 2, .w = 5, .window = 3 }; + // picks [5, -1] told 7 at seq 10 (the review's case), then a row whose first pick is -1 + const tok, const cnt = try run(a, sh, 9, &.{ 5, -1, -1, 4 }, &.{ 7, 2 }); + defer a.free(tok); + defer a.free(cnt); + try std.testing.expectEqualSlices(i32, &.{ 5, 7, 8, 9, -1, 8, 9, 10, -1, -1 }, tok); + try std.testing.expectEqualSlices(i32, &.{ 4, 3 }, cnt); + for (0..sh.rows) |r| for (tok[r * sh.w ..][0..@intCast(cnt[r])]) |v| try std.testing.expect(v >= 0); +} + +test "check refuses lists narrower than k + window, no window, and sizes past i32" { + try win.check(.{ .rows = 16, .k = win.topk, .w = win.topk + win.window }); + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = 1, .k = 4, .w = 6, .window = 3 })); + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = 1, .k = 4, .w = 6, .window = 0 })); + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = 1 << 20, .k = win.topk, .w = 4096 })); +} + +test "check refuses a row count whose rows * w would wrap, before multiplying" { + // 2^63 + 1 rows of 2 on a 64-bit host (the review's case), 2^31 + 1 on a 32-bit one + const rows = (@as(usize, 1) << (@bitSizeOf(usize) - 1)) | 1; + try std.testing.expectError(error.WindowShape, win.check(.{ .rows = rows, .k = 0, .w = 2, .window = 1 })); +} diff --git a/zig/tests/cuda/contract_ernie5_5_index.zig b/zig/tests/cuda/contract_ernie5_5_index.zig new file mode 100644 index 00000000000..42c94f6c86e --- /dev/null +++ b/zig/tests/cuda/contract_ernie5_5_index.zig @@ -0,0 +1,217 @@ +//! ERNIE 5.5's key lists (ernie5_5/index.cu) under the contract: each row's picks then its window, as window.merge. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ernie = @import("ernie5_5_index_cuda"); +const check_ = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const win = ernie.window; + +/// A planted fault: every row takes all k picks, or the window's oldest position is dropped. +pub const Fault = enum { none, all_picks, short_window }; + +pub const Entry = struct { name: []const u8, symbol: [:0]const u8, fault: Fault = .none }; + +pub const entries = [_]Entry{ + .{ .name = "cuda ernie5_5 index tf_ernie55_window_merge (top-k picks, then the window)", .symbol = "tf_ernie55_window_merge" }, + .{ .name = "control: ernie5_5 window merge taking all k picks", .symbol = "tf_ctl_ernie55_window_merge_all_picks", .fault = .all_picks }, + .{ .name = "control: ernie5_5 window merge dropping the window's oldest position", .symbol = "tf_ctl_ernie55_window_merge_short_window", .fault = .short_window }, +}; + +/// rows, row 0's seq (n) and k: across the window with fewer picks than k (the controls' faults show), then the rest. +const served = &[_]c.Shape{ .{ .rows = 16, .n = 120, .k = win.topk }, .{ .rows = 1, .n = 1, .k = win.topk }, .{ .rows = 16, .n = win.topk + win.window - 8, .k = win.topk }, .{ .rows = 1, .n = 100_000, .k = win.topk }, .{ .rows = 512, .n = 1, .k = win.topk }, .{ .rows = 256, .n = 4000, .k = win.topk }, .{ .rows = 4, .n = 1 << 20, .k = win.topk } }; + +fn noSums(_: c.Shape) usize { + return 0; +} + +const rule = "window.merge: picks to picked in [0, k] and the first -1, then the window to seq - 1, -1 after; no NaN"; + +pub fn spec(e: Entry) c.Spec { + const tiles = [3]c.Tile{ .{}, .{ .size = win.window }, .{} }; + return .{ .name = e.name, .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = rule }, .tiles = tiles, .served = if (e.fault == .none) served else served[0..1] }; +} + +pub fn control(e: Entry) ?g.Gate { + return if (e.fault == .none) null else .shapes; +} + +pub const Lists = struct { + rig: rig_.Rig, + entry: Entry, + f: cuda.Function, + shape: c.Shape = undefined, + picks: []i32 = &.{}, + told: []i32 = &.{}, // what the kernel reads as picked: the due counts, a negative and two oversized ones planted + due: []i32 = &.{}, // each row's true count of picks + dev: [3]u64 = @splat(0), // picks, picked, pos + tok: u64 = 0, + cnt: u64 = 0, + msg: [200]u8 = undefined, + + const vt = g.hooks(Lists); + + pub fn kernel(self: *Lists) g.Kernel { + return .{ .spec = spec(self.entry), .ctx = self, .vt = &vt, .control = control(self.entry) }; + } + + fn free(self: *Lists) void { + const a = self.rig.gpu.gpa; + a.free(self.picks); + a.free(self.told); + a.free(self.due); + self.picks = &.{}; + self.told = &.{}; + self.due = &.{}; + } + + pub fn deinit(self: *Lists) void { + self.free(); + self.rig.deinit(); + } + + fn sh(self: *const Lists) win.Shape { + return .{ .rows = self.shape.rows, .k = self.shape.k, .w = self.shape.k + win.window }; + } + + /// Picks as topk_rows leaves them (n below seq - window, then -1); row 4 told -3, rows 3 and 5 told k + 7. + pub fn prepare(self: *Lists, shape: c.Shape, _: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0) return false; + self.rig.reset(); + self.free(); + self.shape = shape; + const a = self.rig.gpu.gpa; + self.picks = try a.alloc(i32, shape.rows * shape.k); + self.told = try a.alloc(i32, shape.rows); + self.due = try a.alloc(i32, shape.rows); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (0..shape.rows) |r| { + const older: usize = (shape.n + r) -| win.window; + const n = @min(older, shape.k); + for (self.picks[r * shape.k ..][0..shape.k], 0..) |*p, i| { + if (i >= n) { + p.* = -1; + continue; + } + const lo = i * older / n; + p.* = @intCast(lo + rng.uintLessThan(usize, (i + 1) * older / n - lo)); + } + self.due[r] = @intCast(n); + } + @memcpy(self.told, self.due); + if (shape.rows >= 5) { + self.told[4] = -3; + if (self.due[3] == shape.k) self.told[3] = @intCast(shape.k + 7); + } + if (shape.rows >= 6 and self.due[5] < shape.k) self.told[5] = @intCast(shape.k + 7); // past its valid picks + const pos0 = [1]i32{@intCast(shape.n - 1)}; + self.dev = .{ try self.rig.input(std.mem.sliceAsBytes(self.picks)), try self.rig.input(std.mem.sliceAsBytes(self.told)), try self.rig.input(std.mem.sliceAsBytes(&pos0)) }; + self.tok = try self.rig.output(shape.rows * (shape.k + win.window) * 4); + self.cnt = try self.rig.output(shape.rows * 4); + return true; + } + + pub fn run(self: *Lists) !void { + try ernie.launch(self.f, self.rig.s, self.dev[0], self.dev[1], self.dev[2], self.tok, self.cnt, self.sh()); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Lists) usize { + return self.shape.rows * (self.shape.k + win.window + 1) * 4; + } + + pub fn reference(_: *Lists, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + fn fail(self: *Lists, comptime fmt: []const u8, args: anytype) !?[]const u8 { + return try std.fmt.bufPrint(&self.msg, fmt, args); + } + + /// window.merge's bytes; every row: its valid picks then the window, each below seq, ascending, last seq - 1. + pub fn check(self: *Lists, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const s = self.sh(); + const got = try self.rig.outputBytes(); + const tok = try a.alloc(i32, s.rows * s.w); + defer a.free(tok); + const cnt = try a.alloc(i32, s.rows); + defer a.free(cnt); + win.merge(s, self.picks, self.told, @intCast(self.shape.n - 1), tok, cnt); + const outs = s.rows * s.w * 4; + if (std.mem.indexOfDiff(u8, got[0..outs], std.mem.sliceAsBytes(tok))) |at| return self.fail("list entry {d} is {d}, window.merge gives {d}", .{ at / 4, std.mem.bytesAsSlice(i32, got[0..outs])[at / 4], tok[at / 4] }); + if (std.mem.indexOfDiff(u8, got[outs..], std.mem.sliceAsBytes(cnt))) |at| return self.fail("row {d}'s count differs from window.merge's", .{at / 4}); + for (0..s.rows) |r| { + const seq: i64 = @intCast(self.shape.n + r); + const row = tok[r * s.w ..][0..s.w]; + const m: usize = @intCast(cnt[r]); + // its count held to [0, k], then to its valid picks (the first `due`; -1 after them) + const told: usize = @intCast(std.math.clamp(self.told[r], 0, @as(i32, @intCast(s.k)))); + const n = @min(told, @as(usize, @intCast(self.due[r]))); + const due = n + @as(usize, @intCast(@min(seq, win.window))); + if (m != due) return self.fail("row {d}: {d} entries where its picks and window are {d}", .{ r, m, due }); + for (row[0..m], 0..) |v, i| if (v < 0 or v >= seq) return self.fail("row {d} entry {d}: {d}, not a row below seq {d}", .{ r, i, v, seq }); + for (row[1..m], 1..) |v, i| if (v <= row[i - 1]) return self.fail("row {d} entry {d}: {d} after {d}, not ascending", .{ r, i, v, row[i - 1] }); + if (n > 0 and row[n - 1] >= seq - win.window) return self.fail("row {d}: a pick inside the window", .{r}); + if (row[m - 1] != seq - 1) return self.fail("row {d}: the last entry is {d}, not seq - 1 = {d}", .{ r, row[m - 1], seq - 1 }); + for (row[m..]) |v| if (v != -1) return self.fail("row {d}: {d} past its count, not -1", .{ r, v }); + } + return null; + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + index: ernie.Index, + items: [entries.len]Lists = undefined, + + /// The set, its kernels appended to `list` (each control after the kernel it breaks). + pub fn init(gpu: check_.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var index = try ernie.Index.load(gpu.d); + errdefer index.unload(); + set.* = .{ .gpa = gpu.gpa, .index = index }; + for (&set.items, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .f = try set.index.mod.function(e.symbol) }; + for (&set.items) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.items) |*x| x.deinit(); + set.index.unload(); + set.gpa.destroy(set); + } +}; + +/// The window merge's gates 1-4 and its controls alone. +pub fn run(gpu: check_.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x65726e6a, &t); + std.debug.print("SUMMARY ernie5_5 index: {d} kernels, {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed }); + try check_.expect(t.problems() == 0, "ernie5_5-index contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} + +test "every control is named one, and only the controls plant a fault" { + for (entries) |e| try std.testing.expectEqual(e.fault != .none, std.mem.startsWith(u8, e.name, "control: ")); +} + +test "the served shapes fit the kernel, and the first leaves rows fewer picks than k on both sides of the window" { + for (served) |x| try win.check(.{ .rows = x.rows, .k = x.k, .w = x.k + win.window }); + const first = served[0]; + try std.testing.expect(first.n <= win.window and first.n + first.rows > win.window + 1 and first.n + first.rows < win.window + first.k); +} diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 8acec62e1ec..481e6e6a687 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -14,6 +14,7 @@ pub const Sets = struct { bf16_experts: *@import("contract_experts_bf16.zig").Set, mxfp4_experts: *@import("contract_experts_mxfp4.zig").Set, ernie5_5_head: *@import("contract_ernie5_5_head.zig").Set, + ernie5_5_index: *@import("contract_ernie5_5_index.zig").Set, pocket: *@import("contract_pocket.zig").Set, minimax: *@import("contract_minimax.zig").Set, inkling2: *@import("contract_inkling2.zig").Set, @@ -49,6 +50,8 @@ pub const Sets = struct { errdefer mxfp4_experts.deinit(); const ernie5_5_head = try @import("contract_ernie5_5_head.zig").Set.init(gpu, s, a, list); errdefer ernie5_5_head.deinit(); + const ernie5_5_index = try @import("contract_ernie5_5_index.zig").Set.init(gpu, s, a, list); + errdefer ernie5_5_index.deinit(); const pocket = try @import("contract_pocket.zig").Set.init(gpu, s, a, list); errdefer pocket.deinit(); const minimax = try @import("contract_minimax.zig").Set.init(gpu, s, a, list); @@ -127,6 +130,7 @@ pub const Sets = struct { .bf16_experts = bf16_experts, .mxfp4_experts = mxfp4_experts, .ernie5_5_head = ernie5_5_head, + .ernie5_5_index = ernie5_5_index, .pocket = pocket, .minimax = minimax, .inkling2 = inkling2, @@ -187,6 +191,7 @@ pub const Sets = struct { sets.minimax.deinit(); sets.pocket.deinit(); sets.ernie5_5_head.deinit(); + sets.ernie5_5_index.deinit(); sets.bf16_experts.deinit(); sets.mxfp4_experts.deinit(); } diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 5555094ea4f..901b8582624 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -46,6 +46,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "moss_image_decoder", "moss_image_encoder", "sparse_attention" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "zonos3", "zonos3_codec", "zonos3_encoder", "zonos3_teacher" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "ernie5_5_head")) return kk.ernie5_5_head; + if (std.mem.eql(u8, name, "ernie5_5_index")) return kk.ernie5_5_index; inline for (.{ "hy4_hc", "hy4_ihc_fused" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "tfq3")) return kk.tfq3; if (std.mem.eql(u8, name, "tfq3_moe")) return kk.tfq3_moe; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index f7070dda3e5..64bc7af2a05 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -275,6 +275,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "mxfp4-experts")) return if (rest.len == 0) @import("mxfp4_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_mxfp4.zig").run(gpu) else error.UnknownCommand; if (std.mem.eql(u8, cmd, "bf16-experts")) return if (rest.len == 0) @import("bf16_experts_tests.zig").experts(gpu) else if (std.mem.eql(u8, rest[0], "contract")) @import("contract_experts_bf16.zig").run(gpu) else error.UnknownCommand; if (std.mem.eql(u8, cmd, "ernie5_5-head")) return @import("contract_ernie5_5_head.zig").run(gpu); + if (std.mem.eql(u8, cmd, "ernie5_5-index")) return @import("contract_ernie5_5_index.zig").run(gpu); if (std.mem.eql(u8, cmd, "projection-f32")) return projection_f32_tests.run(gpu); if (std.mem.eql(u8, cmd, "mxfp8")) return mxfp8_tests.run(gpu); if (std.mem.eql(u8, cmd, "quant-ref")) return quant_ref_tests.run(gpu); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 24488773c18..784c8c06688 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -104,6 +104,7 @@ pub const usage = \\ bf16-experts [contract] grouped bf16 experts against float64 (repack, up, downs, rows, forms); contract: gates 1-4, controls red \\ mxfp4-experts [contract] grouped MXFP4 experts' downs: bf16 experts' bytes on the decoded weights; contract: gates 1-4, controls red \\ ernie5_5-head ERNIE 5.5's MultiMax on the head's fp32 logits: contract gates 1-4, controls red + \\ ernie5_5-index ERNIE 5.5's DSA key lists, picks then window: contract gates 1-4, controls red \\ projection-f32 FP32 projection outputs against FP64, rounding and row/reduction invariance \\ mxfp8 MXFP8 strided projections against FP64 and row-count invariance \\ quant-ref FP8 and NVFP4 projections and experts against float64 references (synthetic) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 31986beb487..2e3c95e1666 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -95,7 +95,7 @@ zig/src/cuda/experts.zig 53d05dc33e2c793ef5e867e4e699d74595005c7aca6f1c441aececb 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 8e8359a136cca05d24cdfcec343c366f3bdabcc794cd6b872f742f2de6c8cdc5 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered +zig/src/cuda/kernels.zig f6630f5264e3b3908cff4b7be84234d413b1a45c1d91dcccadd2483dd3b914bd 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; #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5211: the ernie5_5_index image registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw