From 9fabd76e1d67b7b35ca4db120000a5690f965f0b Mon Sep 17 00:00:00 2001 From: bjornmonnens <787697+bjornmonnens@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:13:36 +0100 Subject: [PATCH 1/8] glm cuda: the latent row width and cache count are parameters of pages, state and snapshot plans (#3063) Full GLM-5.3 keeps 79 latent caches (78 DSA layers and the MTP layer) of 576-value rows (kv_lora 512 and qk_rope 64), a pooled key a row and no KDA layers. config.zig reads qk_rope_head_dim into Config.rope (still refused unless 0 for GLM-5.3-Flash) and latentRow() is kv_lora + rope. cuda_state's Shape carries the cache count, the row width, the index key dims and the pool size (Config.kpool) that pages, a State's arena and onPages lay out from, and the snapshot plan takes its latent and pooled spans from the same shape; its parts hold up to 79 caches instead of max_layers' 47. The KV host gather's row bytes follow latentRow(). GLM-5.3-Flash's 12 caches of 512 values and pools of 4 give the same 13,056 bytes a row and the same plans. --- zig/src/families/glm/config.zig | 25 ++++++- zig/src/families/glm/cuda_native.zig | 2 +- zig/src/families/glm/cuda_pages.zig | 2 +- zig/src/families/glm/cuda_snapshot_layout.zig | 17 +++-- .../glm/cuda_snapshot_layout_test.zig | 59 +++++++++++++++ zig/src/families/glm/cuda_state.zig | 71 +++++++++++++------ 6 files changed, 144 insertions(+), 32 deletions(-) diff --git a/zig/src/families/glm/config.zig b/zig/src/families/glm/config.zig index 646b04d2714..294061dc98d 100644 --- a/zig/src/families/glm/config.zig +++ b/zig/src/families/glm/config.zig @@ -36,6 +36,7 @@ pub const Config = struct { v_dim: u32 = 256, q_lora: u32 = 1536, kv_lora: u32 = 512, + rope: u32 = 0, // qk_rope_head_dim: the roped key dims a latent row carries past kv_lora (none on GLM-5.3-Flash) i_heads: u32 = 32, i_dim: u32 = 128, i_topk: u32 = 2048, @@ -83,6 +84,11 @@ pub const Config = struct { return c.mla_heads * c.nope + c.i_heads * c.i_dim; } + /// A latent cache row's values: the kv_lora latent, then its roped key dims. + pub fn latentRow(c: *const Config) u32 { + return c.kv_lora + c.rope; + } + /// Keys a sparse row attends: index_topk from whole blocks plus the tail of its partial block. pub fn keyWidth(c: *const Config) u32 { return c.i_topk + c.kpool - 1; @@ -217,15 +223,14 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8) !Config { c.eos_n = @intCast(v.array.items.len); for (v.array.items, 0..) |e, i| c.eos[i] = @intCast(e.integer); }; - const rope = t.get("qk_rope_head_dim"); + if (t.get("qk_rope_head_dim")) |v| c.rope = if (v == .integer and v.integer >= 0) @intCast(v.integer) else return error.NotGlm53Flash; const plain = (if (t.get("n_group")) |v| v.integer else 1) == 1 and (if (t.get("topk_group")) |v| v.integer else 1) == 1; const widths = c.hidden == want.hidden and c.dense_inter == want.dense_inter and c.topk == want.topk and c.moe_inter == want.moe_inter and c.shared_inter == want.shared_inter and c.mla_heads == want.mla_heads and c.nope == want.nope and c.v_dim == want.v_dim and c.q_lora == want.q_lora and c.kv_lora == want.kv_lora and c.i_heads == want.i_heads and c.i_dim == want.i_dim and c.i_topk == want.i_topk and c.kpool == want.kpool and c.hc == want.hc and c.sinkhorn == want.sinkhorn and c.kda_heads == want.kda_heads and - c.kda_dim == want.kda_dim and c.conv == want.conv and plain and - (rope == null or (rope.? == .integer and rope.?.integer == 0)); + c.kda_dim == want.kda_dim and c.conv == want.conv and plain and c.rope == want.rope; var eos_in = true; for (c.eos[0..c.eos_n]) |id| eos_in = eos_in and id < c.vocab; const counts = c.layers >= 1 and c.layers <= want.layers and c.dense_layers <= c.layers and @@ -334,6 +339,20 @@ test "the real counts parse to the defaults; smaller counts parse, other widths try std.testing.expectError(error.NotGlm53Flash, parse(gpa, few)); } +test "qk_rope_head_dim: absent or 0 parses to a 512-wide latent row; GLM-5.3-Flash refuses roped latent dims" { + const gpa = std.testing.allocator; + const real = try textConfig(gpa, 45, 3, &.{ 3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43 }, 288, 154880, 4096); + defer gpa.free(real); + try std.testing.expectEqual(@as(u32, 512), (try parse(gpa, real)).latentRow()); + const zero = try std.mem.replaceOwned(u8, gpa, real, "\"kv_lora_rank\": 512", "\"kv_lora_rank\": 512, \"qk_rope_head_dim\": 0"); + defer gpa.free(zero); + try std.testing.expectEqual(@as(u32, 512), (try parse(gpa, zero)).latentRow()); + const roped = try std.mem.replaceOwned(u8, gpa, real, "\"kv_lora_rank\": 512", "\"kv_lora_rank\": 512, \"qk_rope_head_dim\": 64"); + defer gpa.free(roped); + try std.testing.expectError(error.NotGlm53Flash, parse(gpa, roped)); + try std.testing.expectEqual(@as(u32, 576), (Config{ .rope = 64 }).latentRow()); +} + test "quantization_config: EXL3 at the top level or inside text_config parses as EXL3, the top level first" { const gpa = std.testing.allocator; const real = try textConfig(gpa, 45, 3, &.{ 3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43 }, 288, 154880, 4096); diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index 783bddcac79..d3ee01332fa 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -336,7 +336,7 @@ fn finishRank(a: OpenArgs) !Loaded { errdefer own.link.deinit(); try @import("cuda_prompt_logprobs.zig").prepare(own.e); own.e.snap_setup = .{ .ptr = own, .run = readySnapshots }; - try @import("cuda_kv_host.zig").prepare(ctx.d, @import("cuda_state.zig").pageBytes(&own.e.w), own.e.capacity, own.e.w.config.kv_lora * 2); + try @import("cuda_kv_host.zig").prepare(ctx.d, @import("cuda_state.zig").pageBytes(&own.e.w), own.e.capacity, own.e.w.config.latentRow() * 2); if (p.world > 1) try a.load_cache.finishAfter(.{ io, own.e.checkpoint_digest }, cuda.tp_watch.ready) else a.load_cache.finish(); // Rank 0 admits by the smallest room of the ranks; its sizes are the largest (the first ranks take the remainder). const rooms = try gpa.alloc(u64, p.world); diff --git a/zig/src/families/glm/cuda_pages.zig b/zig/src/families/glm/cuda_pages.zig index ee798111c22..a3d1a4a96c9 100644 --- a/zig/src/families/glm/cuda_pages.zig +++ b/zig/src/families/glm/cuda_pages.zig @@ -87,7 +87,7 @@ pub const Pages = struct { p.host_ptr = try p.host.?.device(); } p.pk_arena = try cuda.DeviceBuffer.alloc(e.d, pages * state.pkPageBytes(&e.w)); - try kv_host.prepare(e.d, page, e.capacity, e.w.config.kv_lora * 2); // made before the room was read + try kv_host.prepare(e.d, page, e.capacity, e.w.config.latentRow() * 2); // made before the room was read std.log.info("kv host: {d} pages ({d} MiB) in pinned host memory, pooled keys {d} MiB on the device", .{ pages, pages * page >> 20, pages * state.pkPageBytes(&e.w) >> 20 }); } errdefer if (p.host) |*h| h.free(); diff --git a/zig/src/families/glm/cuda_snapshot_layout.zig b/zig/src/families/glm/cuda_snapshot_layout.zig index c7f08765e97..f31cec74bf8 100644 --- a/zig/src/families/glm/cuda_snapshot_layout.zig +++ b/zig/src/families/glm/cuda_snapshot_layout.zig @@ -2,9 +2,9 @@ const std = @import("std"); const State = @import("cuda_state.zig").State; const page_rows = @import("cuda_state.zig").page_rows; +const Shape = @import("cuda_state.zig").Shape; const Config = @import("config.zig").Config; const cache = @import("cuda_dsa_block.zig"); -const sparse = @import("cuda_sparse.zig"); const walk = @import("core").state_walk.Device; @@ -23,8 +23,10 @@ pub fn halfOf(cur: []const u1, layers: usize, on: bool) ?u1 { /// `len` bytes from `live`, or on a paged sequence's pages `span` bytes a page `page` bytes apart, from byte `from`. pub const Part = walk.Part; +/// Latent caches a plan carries at most: full GLM-5.3's 78 DSA layers and its MTP layer (GLM-5.3-Flash: 12). +pub const max_caches = 79; pub const Plan = struct { - parts: [5 * (@import("config.zig").max_layers + 1) + 2]Part = undefined, + parts: [5 * max_caches + 2]Part = undefined, count: usize = 0, len: usize = 0, ids: []const u32 = &.{}, // a paged sequence's pages in row order @@ -55,7 +57,7 @@ pub const Plan = struct { } fn make(st: *const State, c: *const Config, at: usize, head: ?usize, shared: usize, sizing: bool, half: ?u1) !Plan { - if (at > st.capacity or st.caches.len > @import("config.zig").max_layers) return error.SnapshotShape; + if (at > st.capacity or st.caches.len >= max_caches) return error.SnapshotShape; if (st.rings.len != 2 * (st.caches.len + 1)) return error.SnapshotShape; if (shared > 0 and (st.table == 0 or shared * page_rows > at)) return error.SnapshotShape; // pages below `at` only var p: Plan = .{ .ids = st.pages, .sizing = sizing, .shared = shared, .half = half }; @@ -84,14 +86,15 @@ pub const Plan = struct { } fn rows(p: *Plan, st: *const State, c: *const Config, x: cache.Caches, j: usize, at: usize) !void { - const latent = try std.math.mul(usize, at, @as(usize, c.kv_lora) * @as(usize, if (x.ls == 0) 2 else 1)); + const s = Shape.of(c, st.caches.len + 1); + const latent = try std.math.mul(usize, at, s.row * @as(usize, if (x.ls == 0) 2 else 1)); const ring = try std.math.mul(usize, @min(at, st.ring_rows), st.ring_row); - const pooled = try std.math.mul(usize, @min(at / sparse.pool + 2, x.pk_rows), @as(usize, c.i_dim) * 2); - try p.addCache(st, x, x.lc, latent, page_rows * @as(usize, c.kv_lora) * 2, x.ps); + const pooled = try std.math.mul(usize, @min(at / s.pool + 2, x.pk_rows), s.i_dim * 2); + try p.addCache(st, x, x.lc, latent, s.latentBytes(), x.ps); if (x.ls != 0) try p.add(st, x.ls, try std.math.mul(usize, at, @sizeOf(f32))); try p.add(st, st.rings[2 * j], ring); try p.add(st, st.rings[2 * j + 1], ring); - try p.addCache(st, x, x.pk, pooled, page_rows / sparse.pool * @as(usize, c.i_dim) * 2, if (x.pks != 0) x.pks else x.ps); + try p.addCache(st, x, x.pk, pooled, s.pkBytes(), if (x.pks != 0) x.pks else x.ps); } /// A cache's rows: in the arena, or on the sequence's pages, `span` bytes a page (past the store's `shared`). diff --git a/zig/src/families/glm/cuda_snapshot_layout_test.zig b/zig/src/families/glm/cuda_snapshot_layout_test.zig index 5afa8367ca5..88fbffe924d 100644 --- a/zig/src/families/glm/cuda_snapshot_layout_test.zig +++ b/zig/src/families/glm/cuda_snapshot_layout_test.zig @@ -95,3 +95,62 @@ test "live half: halfOf keeps both halves when the flag is off, when a layer is try t.expectEqual(@as(?u1, null), layout.halfOf(&same, 2, true)); try t.expectEqual(@as(?u1, 0), layout.halfOf(&zero, 1, true)); } + +test "cache shape: GLM-5.3-Flash's pages keep their bytes, full GLM-5.3's 79 caches of 576-wide rows and pool 1 lay out" { + const flash = state.Shape.of(&@import("config.zig").Config{}, 12); + try t.expectEqual(@as(usize, 512), flash.row); + try t.expectEqual(@as(usize, 557056), flash.cacheBytes()); + try t.expectEqual(@as(u64, 13056 * state.page_rows), flash.pageBytes()); + try t.expectEqual(@as(u64, 12 * 32768), flash.pkPageBytes()); + const full = state.Shape.of(&@import("config.zig").Config{ .rope = 64, .kpool = 1 }, 79); + try t.expectEqual(@as(usize, 576), full.row); + try t.expectEqual(@as(usize, 512 * 576 * 2), full.latentBytes()); + try t.expectEqual(@as(usize, 512 * 128 * 2), full.pkBytes()); + try t.expectEqual(@as(u64, 79 * (576 * 2 + 128 * 2) * state.page_rows), full.pageBytes()); +} + +/// Full GLM-5.3's caches on a state: 78 DSA layers and no KDA, 576-wide latent rows, a pooled key a row. +fn fullFixture(d: *cuda.Driver, w: *weights.Weights, layers: []weights.Layer) !state.State { + for (layers) |*l| l.mixer = .{ .mla = undefined }; + w.config = .{ .rope = 64, .kpool = 1 }; + w.share = try shard.Share.of(&w.config, 0, 1); + w.layers = layers; + return state.State.init(t.allocator, d, w, 4096); +} + +test "cache shape: a full GLM-5.3 state's plan carries every cache's 576-wide rows and pooled keys, no KDA half" { + var d = Fake.driver(); + var layers: [78]weights.Layer = undefined; + var w: weights.Weights = undefined; + var st = try fullFixture(&d, &w, &layers); + defer st.deinit(); + try t.expectEqual(@as(usize, 0), st.kda_layers); + try t.expectEqual(@as(usize, 78), st.caches.len); + try t.expectEqual(@as(usize, 4096 + 2), st.caches[0].pk_rows); + const at = 2048; + const plan = try layout.Plan.init(&st, &w.config, at, at, 0); + try t.expectEqual(@as(?u1, null), plan.half); + try t.expectEqual(@as(usize, 1 + 79 * 4 + 1), plan.count); // the head, each cache's latent, rings and pooled keys, the tail + for (0..79) |j| { + try t.expectEqual(@as(usize, at * 576 * 2), plan.parts[1 + 4 * j].len); + try t.expectEqual(@as(usize, at * 128 * 2), plan.parts[2 + 4 * j].len); + try t.expectEqual(@as(usize, (at + 2) * 128 * 2), plan.parts[4 + 4 * j].len); + } +} + +test "cache shape: on pages each cache's part is a 576-wide row's latent then its pooled keys" { + var d = Fake.driver(); + var layers: [78]weights.Layer = undefined; + var w: weights.Weights = undefined; + var st = try fullFixture(&d, &w, &layers); + defer st.deinit(); + const s = state.shapeOf(&w); + try t.expectEqual(@as(usize, 79), s.caches); + const kv: u64 = 1 << 40; + st.place(&w, .{ .kv = kv, .pages = 4, .page_bytes = state.pageBytes(&w) }); + for (st.caches, 0..) |x, j| { + try t.expectEqual(kv + j * (512 * 576 * 2 + 512 * 128 * 2), x.lc); + try t.expectEqual(x.lc + 512 * 576 * 2, x.pk); + } + try t.expectEqual(kv + 78 * s.cacheBytes(), st.mtp_caches.lc); +} diff --git a/zig/src/families/glm/cuda_state.zig b/zig/src/families/glm/cuda_state.zig index 633ea2e06a9..805afc05663 100644 --- a/zig/src/families/glm/cuda_state.zig +++ b/zig/src/families/glm/cuda_state.zig @@ -65,29 +65,59 @@ pub fn mlaLayers(w: *const weights.Weights) usize { return nd; } -/// One cache's part of a page: its latent rows, then their pools' keys. -fn pageCacheBytes(c: anytype) usize { - return page_rows * c.kv_lora * 2 + page_rows / sparse.pool * c.i_dim * 2; -} +/// The latent caches' shape: their count (DSA layers and the MTP layer's), a row's values, index key dims, pool rows. +pub const Shape = struct { + caches: usize, + row: usize, // kv_lora + qk_rope: 512 on GLM-5.3-Flash + i_dim: usize, + pool: usize, // rows a pooled key sums: 4 on GLM-5.3-Flash + + pub fn of(c: anytype, caches: usize) Shape { + return .{ .caches = caches, .row = c.latentRow(), .i_dim = c.i_dim, .pool = c.kpool }; + } + + /// One cache's latent rows on a page, and their pooled keys. + pub fn latentBytes(s: Shape) usize { + return page_rows * s.row * 2; + } + + pub fn pkBytes(s: Shape) usize { + return page_rows / s.pool * s.i_dim * 2; + } + + /// One cache's part of a page: its latent rows, then their pools' keys. + pub fn cacheBytes(s: Shape) usize { + return s.latentBytes() + s.pkBytes(); + } + + /// A page's bytes: every cache's part (13,056 a row on GLM-5.3-Flash). + pub fn pageBytes(s: Shape) u64 { + return s.caches * s.cacheBytes(); + } + + /// TF_GLM_KV_HOST: every cache's pooled keys on a device page of their own. + pub fn pkPageBytes(s: Shape) u64 { + return s.caches * s.pkBytes(); + } +}; -/// TF_GLM_KV_HOST: one cache's pooled keys on a device page of their own, and that page's bytes. -fn pkCacheBytes(c: anytype) usize { - return page_rows / sparse.pool * c.i_dim * 2; +pub fn shapeOf(w: *const weights.Weights) Shape { + return Shape.of(&w.config, mlaLayers(w) + 1); } pub fn pkPageBytes(w: *const weights.Weights) u64 { - return (mlaLayers(w) + 1) * pkCacheBytes(&w.config); + return shapeOf(w).pkPageBytes(); } -/// A page's bytes: every DSA layer's part, then the MTP layer's (13,056 a row on GLM-5.3-Flash). +/// A page's bytes: every DSA layer's part, then the MTP layer's. pub fn pageBytes(w: *const weights.Weights) u64 { - return (mlaLayers(w) + 1) * pageCacheBytes(&w.config); + return shapeOf(w).pageBytes(); } /// Cache `j`'s rows on pages: its part of page 0 at `p.kv`, the others through the table. -fn onPages(x: *dsa_block.Caches, c: anytype, p: Paged, table: u64, j: usize) void { - x.lc = p.kv + j * pageCacheBytes(c); - x.pk = if (p.pk != 0) p.pk + j * pkCacheBytes(c) else x.lc + page_rows * c.kv_lora * 2; +fn onPages(x: *dsa_block.Caches, s: Shape, p: Paged, table: u64, j: usize) void { + x.lc = p.kv + j * s.cacheBytes(); + x.pk = if (p.pk != 0) p.pk + j * s.pkBytes() else x.lc + s.latentBytes(); x.pks = p.pk_page; x.pt = table; x.ps = p.page_bytes; @@ -101,14 +131,14 @@ fn stateSizes(gpa: std.mem.Allocator, w: *const weights.Weights, capacity: usize const nk = w.layers.len - nd; const n = s.kda.len() * c.kda_dim; const kw = @import("cuda_kda_block.zig").rowWidth(s.kda.len()); // TF_GLM_KDA_PAD - const pk_rows = capacity / sparse.pool + 2; + const pk_rows = capacity / c.kpool + 2; const ring_rows = @min(capacity, index_ring); const rows: usize = @intFromBool(table == null); // on pages a cache's rows are the pool's var sizes: std.ArrayList(usize) = .empty; errdefer sizes.deinit(gpa); try sizes.appendSlice(gpa, &.{ 4, nk * 3 * 3 * n * 2, 2 * nk * s.kda.len() * kda.dk * kda.dv * 4, nk * window_rows * kw * 2 }); try sizes.appendSlice(gpa, &.{ nk * window_rows * n * 4, nk * window_rows * n * 2, nk * window_rows * n * 4, nk * window_rows * s.kda.len() * 4 }); - const lc_bytes = try latent.cacheBytes(capacity, c.kv_lora, kv8); + const lc_bytes = try latent.cacheBytes(capacity, c.latentRow(), kv8); for (0..nd + 1) |_| try sizes.appendSlice(gpa, &.{ rows * lc_bytes, ring_rows * c.i_dim * 2, ring_rows * c.i_dim * 2, rows * pk_rows * c.i_dim * 2 }); try sizes.appendSlice(gpa, &.{ 4, c.hidden * 2 }); // MTP position and sequence-owned first-draft row if (table) |t| try sizes.append(gpa, t * 4); @@ -431,7 +461,7 @@ pub const State = struct { const nd = mlaLayers(w); const n = s.kda.len() * c.kda_dim; const kw = @import("cuda_kda_block.zig").rowWidth(s.kda.len()); // TF_GLM_KDA_PAD - const pk_rows = capacity / sparse.pool + 2; + const pk_rows = capacity / c.kpool + 2; const sizes = try stateSizes(gpa, w, capacity, kv8, if (paged) |q| q.pages else null); defer gpa.free(sizes); const p = try gpa.alloc(u64, sizes.len); @@ -443,11 +473,11 @@ pub const State = struct { @memset(cur, 0); const caches = try gpa.alloc(dsa_block.Caches, nd); errdefer gpa.free(caches); - for (caches, 0..) |*x, j| x.* = .{ .lc = p[8 + 4 * j], .ls = if (kv8) p[8 + 4 * j] + capacity * c.kv_lora else 0, .ik = p[9 + 4 * j], .ig = p[10 + 4 * j], .pk = p[11 + 4 * j], .pk_rows = pk_rows }; + for (caches, 0..) |*x, j| x.* = .{ .lc = p[8 + 4 * j], .ls = if (kv8) p[8 + 4 * j] + capacity * c.latentRow() else 0, .ik = p[9 + 4 * j], .ig = p[10 + 4 * j], .pk = p[11 + 4 * j], .pk_rows = pk_rows }; const rings = try gpa.alloc(u64, 2 * (nd + 1)); for (0..nd + 1) |j| rings[2 * j ..][0..2].* = .{ p[9 + 4 * j], p[10 + 4 * j] }; const ring_rows = @min(capacity, index_ring); - var st: State = .{ .ring_rows = ring_rows, .ring_row = c.i_dim * 2, .rings = rings, .arena = a, .gpa = gpa, .capacity = capacity, .pos_dev = p[0], .conv = p[1], .rec = p[2], .proj = p[3], .save_k = p[4], .save_v = p[5], .save_g = p[6], .save_b = p[7], .cur = cur, .heads = s.kda.len(), .mtp_caches = .{ .lc = p[8 + 4 * nd], .ls = if (kv8) p[8 + 4 * nd] + capacity * c.kv_lora else 0, .ik = p[9 + 4 * nd], .ig = p[10 + 4 * nd], .pk = p[11 + 4 * nd], .pk_rows = pk_rows }, .mtp_pos_dev = p[12 + 4 * nd], .prompt_hidden = p[13 + 4 * nd], .kda_layers = nk, .caches = caches, .conv_c = 3 * n, .rec_layer = s.kda.len() * kda.dk * kda.dv * 4, .proj_layer = window_rows * kw, .proj_row = kw }; + var st: State = .{ .ring_rows = ring_rows, .ring_row = c.i_dim * 2, .rings = rings, .arena = a, .gpa = gpa, .capacity = capacity, .pos_dev = p[0], .conv = p[1], .rec = p[2], .proj = p[3], .save_k = p[4], .save_v = p[5], .save_g = p[6], .save_b = p[7], .cur = cur, .heads = s.kda.len(), .mtp_caches = .{ .lc = p[8 + 4 * nd], .ls = if (kv8) p[8 + 4 * nd] + capacity * c.latentRow() else 0, .ik = p[9 + 4 * nd], .ig = p[10 + 4 * nd], .pk = p[11 + 4 * nd], .pk_rows = pk_rows }, .mtp_pos_dev = p[12 + 4 * nd], .prompt_hidden = p[13 + 4 * nd], .kda_layers = nk, .caches = caches, .conv_c = 3 * n, .rec_layer = s.kda.len() * kda.dk * kda.dv * 4, .proj_layer = window_rows * kw, .proj_row = kw }; if (paged) |q| { st.table = p[14 + 4 * nd]; st.capacity = 0; // no rows until a stream's pages are mapped @@ -458,8 +488,9 @@ pub const State = struct { /// A paged sequence's caches on the pages of `p` (the engine's own, made before its pool, placed when it is made). pub fn place(st: *State, w: *const weights.Weights, p: Paged) void { - for (st.caches, 0..) |*x, j| onPages(x, &w.config, p, st.table, j); - onPages(&st.mtp_caches, &w.config, p, st.table, st.caches.len); + const s = shapeOf(w); + for (st.caches, 0..) |*x, j| onPages(x, s, p, st.table, j); + onPages(&st.mtp_caches, s, p, st.table, st.caches.len); } pub fn deinit(st: *State) void { From 4166f7d8e042072c4b5104cbc174ed0b3999fafb Mon Sep 17 00:00:00 2001 From: bjornmonnens <787697+bjornmonnens@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:13:37 +0100 Subject: [PATCH 2/8] glm cuda: the DSA indexer's pool size, key store and index rope are parameters (#3063) Full GLM-5.3 scores every index key (no pooling, top 2,048 over the whole history) and ropes the first 64 dims of its index keys and queries in interleaved pairs. cuda_sparse.Geometry carries the pool size, the pools a row keeps, the roped dims and their fp32 frequencies; dsa_block.Index holds one, set from Config.kpool and index_topk (GLM-5.3-Flash: 4, 512, none). The kernels take the pool size where they divided by 4: tf_glm_scores, tf_glm_index_scores (a page's pools become 512 / pool), tf_glm_select_rows and its wide form, tf_glm_index_pools, tf_glm_dsel_scan and _merge, and tf_glm_dsa_tokens (pool K tokens and a tail of pool - 1). tf_glm_pool_keys keeps its gated softmax for pools of 4; pools of 1 store each LayerNormed key as written and read neither gates nor ape, so scoring pool 1 is scoring every key directly. tf_glm_index_write ropes its LayerNormed key below `rope` before the bf16 store, and both score kernels rope the query fragments they load (glm_index_rope.cuh; the angle's sincosf out of line). A State's index key rows come from Shape.keys (index_ring, or maxInt for a whole sequence) and its rebase keeps whole pools of State.pool. Every existing call passes GLM-5.3-Flash's values, so its launches compute the same bytes. The emulator (test-glm-index-emulate) adds pool-1 scores, paged at 512 keys a page, with queries roped on 64 dims against a model that ropes them itself, and pool-1 top-2,048 picks through tf_glm_index_pools and the decode select. The GPU contract and check launchers pass the new arguments at GLM-5.3-Flash's values, and nvcc 13.0's records follow the six changed launches (tf_glm_pool_keys, tf_glm_scores, tf_glm_index_scores, tf_glm_select_rows, tf_glm_dsel_merge, tf_glm_dsa_tokens). The contract also runs full GLM-5.3's values on these kernels (contract_glm_full.zig): tf_glm_scores at pools of 1 with 64 roped query dims against float64, allowing the roped queries' bf16 rounding; tf_glm_index_scores bit-equal to it; tf_glm_dsa_tokens at pools of 1; and tf_glm_index_write's LayerNormed keys roped on 64 dims against float64. Four planted controls go red: queries or keys left unroped, keys read as pools of 4, and token lists one position late. A score's -inf (a pool the row cannot see) is checked exactly. --- docs/kernel-contract.md | 4 + tools/glm_index_emulate/emulate.cpp | 79 ++++-- zig/glm_ring_host.zig | 1 + zig/kernels/cuda/glm_glue_attn.cuh | 13 +- zig/kernels/cuda/glm_glue_index.cuh | 40 ++- zig/kernels/cuda/glm_index_decode.cuh | 12 +- zig/kernels/cuda/glm_index_pools.cuh | 4 +- zig/kernels/cuda/glm_index_rope.cuh | 55 ++++ zig/kernels/cuda/glm_index_scores.cuh | 16 +- zig/kernels/cuda/glm_ops.cu | 22 +- zig/src/core/contract/glm_cuda_records.zig | 10 +- zig/src/families/glm/cuda_dsa_block.zig | 20 +- zig/src/families/glm/cuda_index.zig | 20 +- zig/src/families/glm/cuda_kv8_test.zig | 2 + .../glm/cuda_snapshot_layout_test.zig | 11 + zig/src/families/glm/cuda_sparse.zig | 146 +++++++--- zig/src/families/glm/cuda_state.zig | 18 +- zig/src/families/glm/cuda_weights.zig | 2 +- zig/tests/cuda/contract_glm_dsel.zig | 2 +- zig/tests/cuda/contract_glm_full.zig | 252 ++++++++++++++++++ zig/tests/cuda/contract_glm_index.zig | 137 ++++++++-- zig/tests/cuda/contract_glm_pages.zig | 2 +- zig/tests/cuda/contract_glm_pools.zig | 4 +- zig/tests/cuda/contract_glm_select.zig | 2 +- zig/tests/cuda/glm_index_check.zig | 30 +-- zig/tests/cuda/glm_ref_index.zig | 10 +- 26 files changed, 720 insertions(+), 194 deletions(-) create mode 100644 zig/kernels/cuda/glm_index_rope.cuh create mode 100644 zig/tests/cuda/contract_glm_full.zig diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index f314b922077..7bb58007c6c 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -447,6 +447,10 @@ sparse). Its prompt indexer (`tf_glm_index_scores`, `tf_glm_index_pools`) is bit and its decode select at a 1,024-thread block a row (`tf_glm_select_rows_wide`) and in spans over many blocks (`tf_glm_dsel_scan`, then `tf_glm_dsel_merge` a block a row) to `tf_glm_select_rows`; both stated rules rank any NaN above +inf, as the GPU's `s + 0` makes every NaN one positive NaN. +Full GLM-5.3's indexer values run on the same kernels (`contract_glm_full.zig`): `tf_glm_scores` at pools of 1 with +64 roped query dims against float64 (allowing the roped queries' bf16 rounding), `tf_glm_index_scores` bit-equal to +it, `tf_glm_dsa_tokens` at pools of 1, and `tf_glm_index_write`'s LayerNormed keys roped on 64 dims, with four +controls: queries or keys left unroped, keys read as pools of 4, and token lists one position late. CUDA also checks `TF_GLM_KV_HOST`'s gather (`tf_glm_kvh_*` in `glm_ops.cu`, launched by `cuda_kv_host.zig`): the marks (a slot for each distinct pick; past its slots, the call flagged and no row left marked), the picked rows into their slots from host pages or the layer's row cache, the token lists' slots, the marks cleared, the dense rows through diff --git a/tools/glm_index_emulate/emulate.cpp b/tools/glm_index_emulate/emulate.cpp index 36ab0fa58e0..47451b12bf9 100644 --- a/tools/glm_index_emulate/emulate.cpp +++ b/tools/glm_index_emulate/emulate.cpp @@ -72,7 +72,7 @@ static int fails = 0; static uint32_t bits(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } static float bf(__nv_bfloat16 v) { return __bfloat162float(v); } -struct Case { int64_t pos, rows, np; int loop, heads; bool paged; }; +struct Case { int64_t pos, rows, np; int loop, heads; bool paged; int pool = 4, rope = 0; }; // tf_glm_scores' result for one (row, pool), the model of the mma: a chain of double sums per k16 step, then its rules static float model_score(const std::vector<__nv_bfloat16>& q, const std::vector<__nv_bfloat16>& w, int64_t w_stride, @@ -103,34 +103,48 @@ static float model_score(const std::vector<__nv_bfloat16>& q, const std::vector< static void scores_case(std::mt19937_64& g, const Case& c) { const int D = 128, W = 40; // head weights in a row of W columns - const int64_t visible = (c.pos + c.rows) / 4; + const int64_t visible = (c.pos + c.rows) / c.pool, pp = 512 / c.pool; // pp: a page's pools const int64_t nb = (std::min(c.np, std::max(512, visible)) + 63) / 64; std::normal_distribution nd(0.0f, 1.0f); std::vector<__nv_bfloat16> q(c.rows * c.heads * D), w(c.rows * W); for (auto& x : q) x = __float2bfloat16_rn(nd(g)); for (auto& x : w) x = __float2bfloat16_rn(nd(g)); - const int64_t pool_rows = (c.pos + c.rows) / 4 + 1; + const int64_t pool_rows = (c.pos + c.rows) / c.pool + 1; std::vector<__nv_bfloat16> keys(std::max(c.np, pool_rows + 200) * D); for (auto& x : keys) x = __float2bfloat16_rn(nd(g) * 2); - // pages of 128 pools, shuffled, when paged: the table maps a logical page to its place - const int64_t npages = (keys.size() / D + 127) / 128, page_elems = 128 * D; + // pages of pp pools, shuffled, when paged: the table maps a logical page to its place + const int64_t npages = (keys.size() / D + pp - 1) / pp, page_elems = pp * D; std::vector pt(npages), order(npages); for (int i = 0; i < npages; i++) order[i] = i; std::shuffle(order.begin(), order.end(), g); std::vector<__nv_bfloat16> store(npages * page_elems); for (int64_t p = 0; p < (int64_t)(keys.size() / D); p++) { - pt[p / 128] = order[p / 128]; - std::memcpy(&store[(int64_t)order[p / 128] * page_elems + (p % 128) * D], &keys[p * D], D * 2); + pt[p / pp] = order[p / pp]; + std::memcpy(&store[(int64_t)order[p / pp] * page_elems + (p % pp) * D], &keys[p * D], D * 2); } const __nv_bfloat16* pk = c.paged ? store.data() : keys.data(); const float scale = 0.0883883461f, wscale = 0.176776692f; const int pos = (int)c.pos; + // rope: the model turns q's pairs below c.rope itself (row r at pos + r), the kernel its fragments + std::vector inv(64); + for (int i = 0; i < 64; i++) inv[i] = (float)std::pow(8.0e6, -2.0 * i / 64); + std::vector<__nv_bfloat16> qm = q; + for (int64_t r = 0; r < c.rows; r++) + for (int h = 0; h < c.heads; h++) + for (int i = 0; i < c.rope / 2; i++) { + __nv_bfloat16* x = &qm[(r * c.heads + h) * D + 2 * i]; + const float x0 = bf(x[0]), x1 = bf(x[1]); + float sn, cs; + sincosf((float)(c.pos + r) * inv[i], &sn, &cs); + x[0] = __float2bfloat16_rn(std::fma(x0, cs, -(x1 * sn))); + x[1] = __float2bfloat16_rn(std::fma(x1, cs, x0 * sn)); + } std::vector out(c.rows * c.np); std::vector raw(out.size(), 0x7FC0DEAD); std::memcpy(out.data(), raw.data(), out.size() * 4); run_grid((c.rows + 7) / 8, (nb + c.loop - 1) / c.loop, 256, [&] { tf_glm_index_scores(q.data(), w.data(), W, pk, out.data(), &pos, c.rows, c.np, nb, scale, wscale, c.heads, c.loop, - c.paged ? pt.data() : nullptr, c.paged ? page_elems * 2 : 0); + c.paged ? pt.data() : nullptr, c.paged ? page_elems * 2 : 0, c.pool, c.rope, inv.data()); }); int64_t bad = 0, unread = 0; for (int64_t r = 0; r < c.rows; r++) @@ -140,12 +154,12 @@ static void scores_case(std::mt19937_64& g, const Case& c) { unread += have != 0x7FC0DEAD; // never written continue; } - const int64_t npool = (c.pos + r + 1) / 4; - const float want = p < npool ? model_score(q, w, W, &keys[p * D], r, c.heads, scale, wscale) : -INFINITY; + const int64_t npool = (c.pos + r + 1) / c.pool; + const float want = p < npool ? model_score(qm, w, W, &keys[p * D], r, c.heads, scale, wscale) : -INFINITY; bad += have != bits(want); } - printf("scores pos %lld rows %lld np %lld loop %d heads %d %s: %lld differ, %lld untouched columns written\n", - (long long)c.pos, (long long)c.rows, (long long)c.np, c.loop, c.heads, c.paged ? "paged" : "plain", + printf("scores pos %lld rows %lld np %lld loop %d heads %d pool %d rope %d %s: %lld differ, %lld untouched columns written\n", + (long long)c.pos, (long long)c.rows, (long long)c.np, c.loop, c.heads, c.pool, c.rope, c.paged ? "paged" : "plain", (long long)bad, (long long)unread); fails += bad != 0 || unread != 0; } @@ -188,34 +202,43 @@ int main() { std::mt19937_64 g(0x101); for (const Case& c : {Case{0, 1, 1024, 2, 32, false}, Case{1000, 19, 1024, 4, 32, false}, Case{3000, 24, 1024, 16, 32, true}, Case{3900, 17, 1000, 3, 32, false}, Case{5000, 9, 2048, 5, 20, true}, - Case{6000, 24, 2048, 8, 32, false}, Case{12000, 8, 4096, 3, 32, true}}) + Case{6000, 24, 2048, 8, 32, false}, Case{12000, 8, 4096, 3, 32, true}, + // full GLM-5.3's: every key scored (pools of 1, 512 a page), queries roped on 64 dims + Case{3000, 9, 4096, 4, 32, true, 1, 64}, Case{2100, 17, 2560, 3, 32, false, 1, 64}, + Case{5000, 8, 8192, 16, 32, true, 1, 0}}) scores_case(g, c); - const int K = 512, rows = 2; + const int rows = 2; int paths[3] = {0, 0, 0}; - for (int np : {1024, 4097, 12289, 32769, 70001}) + // GLM-5.3-Flash's 512 of pools of 4 at every bucket, then full GLM-5.3's 2,048 of single keys + struct Pick { int np, pool, K; }; + std::vector picks; + for (int np : {1024, 4097, 12289, 32769, 70001}) picks.push_back({np, 4, 512}); + for (int np : {4097, 12289}) picks.push_back({np, 1, 2048}); + for (const Pick& pk : picks) for (int mode = 0; mode < 3; mode++) for (Kind kind : {normal, ties, equal, zeros, skewed, decoy}) { + const int np = pk.np, pool = pk.pool, K = pk.K; // the first row's position: few visible pools (limit K), about half, or nearly all - const int pos = mode == 0 ? 300 : mode == 1 ? 2 * np : 4 * np - rows - 5; + const int pos = mode == 0 ? 300 : mode == 1 ? pool * np / 2 : pool * np - rows - 5; std::vector s((size_t)rows * np + 4); float* base = s.data() + (np % 4 ? 1 : 0); // an unaligned row now and then: the scalar loads std::vector limit(rows); for (int r = 0; r < rows; r++) { - limit[r] = (int)std::min(np, std::max((pos + r + 1) / 4, K)); + limit[r] = (int)std::min(np, std::max((pos + r + 1) / pool, K)); fill(g, base + (size_t)r * np, np, limit[r], kind); } std::vector out((size_t)rows * K, -7); std::vector path(rows, -1); run_grid(rows, 1, glm_index::T, [&] { - tf_glm_index_pools(base, out.data(), np, &pos, K, tile_cap(np), tile_target(np), path.data()); + tf_glm_index_pools(base, out.data(), np, &pos, K, tile_cap(np), tile_target(np), path.data(), pool); }); for (int r = 0; r < rows; r++) { paths[path[r]]++; const auto want = reference(base + (size_t)r * np, limit[r], K); if (!std::equal(want.begin(), want.end(), out.begin() + (size_t)r * K)) { fails++; - printf("pools np %d mode %d kind %d row %d (path %d) differs\n", np, mode, (int)kind, r, path[r]); + printf("pools np %d pool %d mode %d kind %d row %d (path %d) differs\n", np, pool, mode, (int)kind, r, path[r]); } } } @@ -225,26 +248,30 @@ int main() { // glm_index_decode.cuh: a decode window's rows marked on many CTAs, then merged, against the same plain top-K int dpaths[4] = {0, 0, 0, 0}; const int drows = 3; - for (int np : {4097, 12289, 70001}) + std::vector dpicks; + for (int np : {4097, 12289, 70001}) dpicks.push_back({np, 4, 512}); + dpicks.push_back({12289, 1, 2048}); + for (const Pick& pk : dpicks) for (int mode = 0; mode < 3; mode++) for (Kind kind : {normal, ties, equal, zeros, skewed, decoy}) { - const int pos = mode == 0 ? 300 : mode == 1 ? 2 * np : 4 * np - drows - 5; + const int np = pk.np, pool = pk.pool, K = pk.K; + const int pos = mode == 0 ? 300 : mode == 1 ? pool * np / 2 : pool * np - drows - 5; std::vector s((size_t)drows * np + 4); float* base = s.data() + (np % 4 ? 1 : 0); std::vector limit(drows); for (int r = 0; r < drows; r++) { - limit[r] = (int)std::min(np, std::max((pos + r + 1) / 4, K)); + limit[r] = (int)std::min(np, std::max((pos + r + 1) / pool, K)); fill(g, base + (size_t)r * np, np, limit[r], kind); } const int64_t words = (np + 31) / 32; std::vector bitw((size_t)drows * 2 * words, 0xA5A5A5A5u); // words a scan does not write stay unread - const int last = (int)std::min(np, std::max((pos + drows) / 4, K)); + const int last = (int)std::min(np, std::max((pos + drows) / pool, K)); const unsigned ctas = last <= glm_dsel::CAP ? 0 : (unsigned)((last + glm_dsel::SPAN - 1) / glm_dsel::SPAN); if (ctas > 0) - run_grid(ctas, drows, glm_dsel::T1, [&] { tf_glm_dsel_scan(base, np, &pos, K, 2048, bitw.data(), words); }); + run_grid(ctas, drows, glm_dsel::T1, [&] { tf_glm_dsel_scan(base, np, &pos, K, 2048, bitw.data(), words, pool); }); std::vector out((size_t)drows * K, -7); std::vector path(drows, -1); - run_grid(drows, 1, glm_dsel::T2, [&] { tf_glm_dsel_merge(base, out.data(), np, &pos, K, bitw.data(), words, path.data()); }); + run_grid(drows, 1, glm_dsel::T2, [&] { tf_glm_dsel_merge(base, out.data(), np, &pos, K, bitw.data(), words, path.data(), pool); }); for (int r = 0; r < drows; r++) { if (path[r] < 0 || path[r] > 3) { fails++; @@ -255,7 +282,7 @@ int main() { const auto want = reference(base + (size_t)r * np, limit[r], K); if (!std::equal(want.begin(), want.end(), out.begin() + (size_t)r * K)) { fails++; - printf("dsel np %d mode %d kind %d row %d (path %d) differs\n", np, mode, (int)kind, r, path[r]); + printf("dsel np %d pool %d mode %d kind %d row %d (path %d) differs\n", np, pool, mode, (int)kind, r, path[r]); } } } diff --git a/zig/glm_ring_host.zig b/zig/glm_ring_host.zig index 5cd8da62b56..83d8bd4f6d6 100644 --- a/zig/glm_ring_host.zig +++ b/zig/glm_ring_host.zig @@ -42,6 +42,7 @@ fn check(boundary: usize, resumed: bool, rewind: usize) !void { st.capacity = boundary + 8192; st.ring_rows = keys.len; st.ring_row = 1; + st.pool = 4; st.rings = &rings; st.caches = &.{}; st.cur = &.{}; diff --git a/zig/kernels/cuda/glm_glue_attn.cuh b/zig/kernels/cuda/glm_glue_attn.cuh index 11fe779be0a..48433be8a41 100644 --- a/zig/kernels/cuda/glm_glue_attn.cuh +++ b/zig/kernels/cuda/glm_glue_attn.cuh @@ -6,6 +6,7 @@ #include "glm_glue_router.cuh" #include #include "common/mla.cuh" +#include "glm_index_rope.cuh" // The 16-head form (decode windows) and 32-head form (prompt chunks), each in glm_attn::wide_smem() bytes of smem. extern "C" __global__ void __launch_bounds__(256) @@ -71,17 +72,17 @@ extern "C" __global__ void __launch_bounds__(128) for (int j = 0; j < 4; ++j) out[(r * heads + h) * LW + k0 + j] = __float2bfloat16_rn(glm_triton::div_full(o[j], l)); } -// sparse._scores, block (row, L pool blocks) of 4 warps, 16 pools a warp: sum_h w relu(dots scale), -inf past visible. +// sparse._scores, a block (row, L pool blocks), 4 warps: sum_h w relu(dots scale); pools of `pool`, roped below `rope`. extern "C" __global__ void __launch_bounds__(128) tf_glm_scores(const __nv_bfloat16* qi, const __nv_bfloat16* wts, int64_t w_stride, const __nv_bfloat16* pk, float* out, const int* pos, int64_t np, int64_t nb, float scale, float wscale, int64_t heads, - int loop, const int* pt, int64_t ps) { + int loop, const int* pt, int64_t ps, int pool, int rope, const float* inv) { glm_pdl::enter(); constexpr int D = 128, HP = 32, BP = 64; __shared__ __align__(16) __nv_bfloat16 sm[4 * 2 * 16 * D]; // q's 32 rows, then each warp's two 16-pool buffers auto at = [](int row, int u) { return row * D + ((u ^ (row & 7)) << 3); }; const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, g = lane >> 2, q = lane & 3; - const int64_t r = blockIdx.x, npool = ((int64_t)pos[0] + r + 1) / 4; + const int64_t r = blockIdx.x, npool = ((int64_t)pos[0] + r + 1) / pool, pp = 512 / pool; for (int idx = threadIdx.x; idx < HP * (D / 8); idx += 128) { const int hh = idx / (D / 8), u = idx % (D / 8); const bool ok = hh < heads; @@ -93,9 +94,10 @@ extern "C" __global__ void __launch_bounds__(128) const int64_t hh = g + 8 * i; wv[i] = hh < heads ? glm_triton::fmul(__bfloat162float(wts[r * w_stride + hh]), wscale) : 0.0f; } - // A block's pools for this warp: rows p0 .. p0 + 15 of pk (16 | p0: one page), 16 chunks of 16 bytes, 8 a lane. + // A block's pools for this warp: rows p0 .. p0 + 15 of pk (16 | p0: one page of pp), 16 chunks of 16 bytes, 8 a lane. auto stage = [&](int buf, int64_t p0) { - const __nv_bfloat16* src = pk + glm_pages::at<128>(pt, ps / 2, p0 < npool ? p0 : 0, D); + const int64_t pa = p0 < npool ? p0 : 0; + const __nv_bfloat16* src = pk + (pt ? (int64_t)pt[pa / pp] * (ps / 2) + (pa % pp) * D : pa * D); #pragma unroll for (int t = 0; t < 8; ++t) { const int idx = lane + t * 32, row = idx / (D / 8), u = idx % (D / 8); @@ -114,6 +116,7 @@ extern "C" __global__ void __launch_bounds__(128) for (int kq = 0; kq < D / 16; ++kq) #pragma unroll for (int i = 0; i < 2; ++i) glm_attn::ldm4(aq[kq][i], sm + at(i * 16 + (lane & 15), kq * 2 + (lane >> 4))); + if (rope > 0) glm_rope::frags(aq, q, (int64_t)pos[0] + r, rope, inv); __syncthreads(); // q's fragments are in registers: the key buffers take its place if (live(0)) stage(0, first * BP + warp * 16); glm_attn::commit(); diff --git a/zig/kernels/cuda/glm_glue_index.cuh b/zig/kernels/cuda/glm_glue_index.cuh index 5f5cdb75beb..45515e39376 100644 --- a/zig/kernels/cuda/glm_glue_index.cuh +++ b/zig/kernels/cuda/glm_glue_index.cuh @@ -4,13 +4,15 @@ #include "glm_pdl.cuh" #include "glm_triton.cuh" +#include "glm_index_rope.cuh" using namespace glm_triton; -// sparse._index_write, a warp a row (D 128): LayerNorm of k_raw (div.full, sqrt.approx) into ik, gate row into ig. +// sparse._index_write, a warp a row (D 128): LayerNorm of k_raw, dims below `rope` roped, into ik; gate row into ig. extern "C" __global__ void __launch_bounds__(32) tf_glm_index_write(const __nv_bfloat16* kr, int64_t k_stride, const float* gr, const __nv_bfloat16* lnw, - const __nv_bfloat16* lnb, __nv_bfloat16* ik, __nv_bfloat16* ig, const int* pos, float eps) { + const __nv_bfloat16* lnb, __nv_bfloat16* ik, __nv_bfloat16* ig, const int* pos, float eps, + int rope, const float* inv) { glm_pdl::enter(); constexpr int D = 128; const int64_t r = blockIdx.x, at = (int64_t)pos[0] + r; @@ -30,22 +32,31 @@ extern "C" __global__ void __launch_bounds__(32) v = __fmaf_rn(xc[3], xc[3], v); for (int o = 16; o > 0; o >>= 1) v = v + __shfl_xor_sync(0xffffffffu, v, o); const float sd = sqrt_approx(fadd(eps, div_full(v, (float)D))); + float y[4]; + for (int j = 0; j < 4; ++j) y[j] = __fmaf_rn(div_full(xc[j], sd), bf(lnw[d0 + j]), bf(lnb[d0 + j])); + if (d0 < rope) // rope % 4 == 0: both of this lane's pairs + for (int j = 0; j < 4; j += 2) glm_rope::pair(y[j], y[j + 1], at, inv, (d0 + j) / 2); for (int j = 0; j < 4; ++j) { const int d = d0 + j; - ik[at * D + d] = __float2bfloat16_rn(__fmaf_rn(div_full(xc[j], sd), bf(lnw[d]), bf(lnb[d]))); + ik[at * D + d] = __float2bfloat16_rn(y[j]); ig[at * D + d] = __float2bfloat16_rn(gr[r * D + d]); } } -// sparse._pool_keys, a warp a completed pool: softmax of its 4 gate rows (+ ape) times bf16 keys, summed in order. +// sparse._pool_keys, a warp a pool: softmax of its 4 gate rows (+ ape) times keys, in order; `pool` 1: keys as written. extern "C" __global__ void __launch_bounds__(32) tf_glm_pool_keys(const __nv_bfloat16* ik, const __nv_bfloat16* ig, const __nv_bfloat16* ape, __nv_bfloat16* pk, - const int* pos, int64_t rows, const int* pt, int64_t ps) { + const int* pos, int64_t rows, const int* pt, int64_t ps, int pool) { glm_pdl::enter(); constexpr int D = 128; - const int64_t P = pos[0], p = P / 4 + blockIdx.x; - if (4 * p + 3 > P + rows - 1) return; - __nv_bfloat16* out = pk + glm_pages::at<128>(pt, ps / 2, p, D); // a page holds 512 rows' 128 pools + const int64_t P = pos[0], p = P / pool + blockIdx.x; + if (pool * p + pool - 1 > P + rows - 1) return; + const int64_t pp = 512 / pool; // a page holds 512 rows' pools + __nv_bfloat16* out = pk + (pt ? (int64_t)pt[p / pp] * (ps / 2) + (p % pp) * D : p * D); + if (pool == 1) { + for (int j = 0; j < 4; ++j) out[threadIdx.x * 4 + j] = ik[p * D + threadIdx.x * 4 + j]; + return; + } for (int j = 0; j < 4; ++j) { const int d = threadIdx.x * 4 + j; float l[4], e[4]; @@ -95,7 +106,8 @@ __device__ __forceinline__ int block_scan(int v, int (*wsum)[W], int slot, int* // sparse._select_rows (VISIBLE), a row per T-thread block: K best visible pools by 8-bit radix select, ties to lower. template -__device__ __forceinline__ void select_row(const float* scores, int64_t* out, int64_t np, const int* pos, int k) { +__device__ __forceinline__ void select_row(const float* scores, int64_t* out, int64_t np, const int* pos, int k, + int pool) { __shared__ int hist[256]; __shared__ uint32_t sh_prefix; __shared__ int sh_need, wsum[2][T / 32]; @@ -103,7 +115,7 @@ __device__ __forceinline__ void select_row(const float* scores, int64_t* out, in const float* row = scores + r * np; const int t = threadIdx.x, lane = t & 31, warp = t >> 5; const unsigned below = (1u << lane) - 1; - const int64_t vis = ((int64_t)pos[0] + r + 1) / 4; + const int64_t vis = ((int64_t)pos[0] + r + 1) / pool; const int64_t limit = np < (vis > k ? vis : k) ? np : (vis > k ? vis : k); const bool vec = (reinterpret_cast(row) & 15) == 0; // The order keys of pools c + 8 t .. + 7 (0 past limit; callers test the index). @@ -197,14 +209,14 @@ __device__ __forceinline__ void select_row(const float* scores, int64_t* out, in // sparse._select_rows (VISIBLE), a row per 4-warp block: K best visible pools by 8-bit radix select, ties to lower. extern "C" __global__ void __launch_bounds__(128) - tf_glm_select_rows(const float* scores, int64_t* out, int64_t np, const int* pos, int k) { + tf_glm_select_rows(const float* scores, int64_t* out, int64_t np, const int* pos, int k, int pool) { glm_pdl::enter(); - glm_index::select_row<128>(scores, out, np, pos, k); + glm_index::select_row<128>(scores, out, np, pos, k, pool); } // tf_glm_select_rows a row per 1,024-thread block, for a few rows over many pools (a decode step's): its bytes. extern "C" __global__ void __launch_bounds__(1024) - tf_glm_select_rows_wide(const float* scores, int64_t* out, int64_t np, const int* pos, int k) { + tf_glm_select_rows_wide(const float* scores, int64_t* out, int64_t np, const int* pos, int k, int pool) { glm_pdl::enter(); - glm_index::select_row<1024>(scores, out, np, pos, k); + glm_index::select_row<1024>(scores, out, np, pos, k, pool); } diff --git a/zig/kernels/cuda/glm_index_decode.cuh b/zig/kernels/cuda/glm_index_decode.cuh index 3275a682e92..3c42304c63f 100644 --- a/zig/kernels/cuda/glm_index_decode.cuh +++ b/zig/kernels/cuda/glm_index_decode.cuh @@ -22,8 +22,8 @@ __device__ __forceinline__ uint32_t order_key(float s) { } // Row r's selection range [0, NP): its visible pools, at least K, at most np (tf_glm_select_rows' limit). -__device__ __forceinline__ int row_limit(int64_t np, const int* pos, int64_t r, int K) { - const int64_t vis = ((int64_t)pos[0] + r + 1) / 4; +__device__ __forceinline__ int row_limit(int64_t np, const int* pos, int64_t r, int K, int pool) { + const int64_t vis = ((int64_t)pos[0] + r + 1) / pool; return (int)min(np, max(vis, (int64_t)K)); } @@ -194,14 +194,14 @@ struct Merge { // tf_glm_dsel_scan, grid (cdiv(the last row's NP, SPAN), R): a span's pools above (gt) and at (eq) the row's floor. extern "C" __global__ void __launch_bounds__(glm_dsel::T1) tf_glm_dsel_scan(const float* S, int64_t np, const int* pos, int K, int target, - uint32_t* __restrict__ bits, int64_t words) { + uint32_t* __restrict__ bits, int64_t words, int pool) { glm_pdl::enter(); using namespace glm_dsel; __shared__ int hist[256]; __shared__ uint32_t sh_prefix; __shared__ int sh_need; const int64_t r = blockIdx.y; - const int NP = row_limit(np, pos, r, K); + const int NP = row_limit(np, pos, r, K, pool); const int64_t p0 = (int64_t)blockIdx.x * SPAN; if (NP <= CAP || p0 >= NP) return; // rows of NP <= CAP mark nothing: the merge takes them whole const float* row = S + r * np; @@ -259,12 +259,12 @@ extern "C" __global__ void __launch_bounds__(glm_dsel::T1) // tf_glm_dsel_merge, a CTA a row: scores [R][np] into out [R][K] int64 ascending; PATH null or [R] int32, each path. extern "C" __global__ void __launch_bounds__(glm_dsel::T2) tf_glm_dsel_merge(const float* S, int64_t* __restrict__ OUT, int64_t np, const int* pos, - int K, const uint32_t* bits, int64_t words, int* __restrict__ PATH) { + int K, const uint32_t* bits, int64_t words, int* __restrict__ PATH, int pool) { glm_pdl::enter(); using namespace glm_dsel; __shared__ Merge sm; const int64_t r = blockIdx.x; - const int NP = row_limit(np, pos, r, K); + const int NP = row_limit(np, pos, r, K, pool); const float* row = S + r * np; int64_t* out = OUT + r * K; const int t = threadIdx.x; diff --git a/zig/kernels/cuda/glm_index_pools.cuh b/zig/kernels/cuda/glm_index_pools.cuh index 2a8969878ea..2ac5315ba95 100644 --- a/zig/kernels/cuda/glm_index_pools.cuh +++ b/zig/kernels/cuda/glm_index_pools.cuh @@ -174,12 +174,12 @@ __device__ uint32_t sample_floor(Smem& sm, const float* row, int NP, int TARGET, // tf_glm_select_rows' pools for scores [R][np]; CAP (<= 4096), TARGET speed only; PATH null or [R] int32; grid (R). extern "C" __global__ void __launch_bounds__(glm_index::T) tf_glm_index_pools(const float* S, int64_t* __restrict__ OUT, int64_t np, const int* pos, - int K, int CAP, int TARGET, int* __restrict__ PATH) { + int K, int CAP, int TARGET, int* __restrict__ PATH, int pool) { glm_pdl::enter(); using namespace glm_index; __shared__ Smem sm; CAP = min(CAP, CAP_MAX); - const int64_t r = blockIdx.x, vis = ((int64_t)pos[0] + r + 1) / 4; + const int64_t r = blockIdx.x, vis = ((int64_t)pos[0] + r + 1) / pool; const float* row = S + r * np; int64_t* out = OUT + r * K; const int NP = (int)min(np, max(vis, (int64_t)K)); diff --git a/zig/kernels/cuda/glm_index_rope.cuh b/zig/kernels/cuda/glm_index_rope.cuh new file mode 100644 index 00000000000..7fd5c82882d --- /dev/null +++ b/zig/kernels/cuda/glm_index_rope.cuh @@ -0,0 +1,55 @@ +// The DSA indexer's rope (indexer_rope_interleave): dims (2i, 2i + 1) below `rope` turned by pos inv[i], in place. +#pragma once + +#include +#include +#include +#include + +namespace glm_rope { + +// Sine and cosine of pair i's angle pos inv[i], out of line: one copy of sincosf's large-angle path, not one a site. +static __device__ __attribute__((noinline)) void turn(int64_t pos, const float* inv, int i, float* s, float* c) { + sincosf(__fmul_rn((float)pos, inv[i]), s, c); +} + +// A pair turned by (s, c): (x0 c - x1 s, x1 c + x0 s). +__device__ __forceinline__ void apply(float& x0, float& x1, float s, float c) { + const float y0 = __fmaf_rn(x0, c, -__fmul_rn(x1, s)), y1 = __fmaf_rn(x1, c, __fmul_rn(x0, s)); + x0 = y0; + x1 = y1; +} + +// Pair i of a key or query at position pos. +__device__ __forceinline__ void pair(float& x0, float& x1, int64_t pos, const float* inv, int i) { + float s, c; + turn(pos, inv, i, &s, &c); + apply(x0, x1, s, c); +} + +// A query row's m16n8k16 A fragments (KQ k16 steps, two 16-head tiles), dims below `rope` roped at pos, back to bf16. +template +__device__ __forceinline__ void frags(uint32_t (&aq)[KQ][2][4], int q, int64_t pos, int rope, const float* inv) { +#pragma unroll + for (int kq = 0; kq < KQ; ++kq) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int d = kq * 16 + h * 8 + 2 * q; + if (d >= rope) continue; + float s, c; + turn(pos, inv, d / 2, &s, &c); +#pragma unroll + for (int k = 0; k < 4; ++k) { + uint32_t& w = aq[kq][k >> 1][2 * h + (k & 1)]; + __nv_bfloat16 b[2]; + memcpy(b, &w, 4); + float x0 = __bfloat162float(b[0]), x1 = __bfloat162float(b[1]); + apply(x0, x1, s, c); + b[0] = __float2bfloat16_rn(x0); + b[1] = __float2bfloat16_rn(x1); + memcpy(&w, b, 4); + } + } +} + +} // namespace glm_rope diff --git a/zig/kernels/cuda/glm_index_scores.cuh b/zig/kernels/cuda/glm_index_scores.cuh index 50bea137e89..ef7a139ccc8 100644 --- a/zig/kernels/cuda/glm_index_scores.cuh +++ b/zig/kernels/cuda/glm_index_scores.cuh @@ -7,6 +7,7 @@ #include #include #include "common/cp_async.cuh" +#include "glm_index_rope.cuh" #ifndef GLM_INDEX_HOST #include "common/qmm_frag.cuh" #endif @@ -31,9 +32,9 @@ __device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint } #endif -// Element offset of pool p's key: in order (pt null), or row p % 128 of page pt[p / 128] (glm_pages::at<128>). -__device__ __forceinline__ int64_t key_at(const int* pt, int64_t page_elems, int64_t p) { - return pt ? (int64_t)pt[p / 128] * page_elems + (p % 128) * D : p * D; +// Element offset of pool p's key: in order (pt null), or row p % pp of page pt[p / pp] (pp: a page's 512 rows' pools). +__device__ __forceinline__ int64_t key_at(const int* pt, int64_t page_elems, int64_t p, int64_t pp) { + return pt ? (int64_t)pt[p / pp] * page_elems + (p % pp) * D : p * D; } // Logical 16-byte chunk u of key row `row` (0..63) in the tile: the 16-row groups' layout of tf_glm_scores. @@ -45,15 +46,15 @@ __device__ __forceinline__ int tile_at(int row, int u) { return row * D + ((u ^ extern "C" __global__ void __launch_bounds__(glm_index::RB * 32) tf_glm_index_scores(const __nv_bfloat16* qi, const __nv_bfloat16* wts, int64_t w_stride, const __nv_bfloat16* pk, float* out, const int* pos, int64_t rows, int64_t np, int64_t nb, float scale, float wscale, - int64_t heads, int loop, const int* pt, int64_t ps) { + int64_t heads, int loop, const int* pt, int64_t ps, int pool, int rope, const float* inv) { glm_pdl::enter(); using namespace glm_index; __shared__ __align__(16) __nv_bfloat16 tile[2][BP * D]; // two key tiles const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, g = lane >> 2, q = lane & 3; const int64_t r = (int64_t)blockIdx.x * RB + warp, P = pos[0]; const bool live = r < rows; - const int64_t npool = live ? (P + r + 1) / 4 : 0; - const int64_t last = min(rows, (int64_t)(blockIdx.x + 1) * RB) - 1, nmax = (P + last + 1) / 4; // the CTA's largest + const int64_t npool = live ? (P + r + 1) / pool : 0, pp = 512 / pool; + const int64_t last = min(rows, (int64_t)(blockIdx.x + 1) * RB) - 1, nmax = (P + last + 1) / pool; // the CTA's largest // this row's query fragments for the 8 k16 steps and 2 head tiles (ldmatrix's A layout), and a lane's 4 head weights uint32_t aq[KQ][2][4]; #pragma unroll @@ -69,6 +70,7 @@ extern "C" __global__ void __launch_bounds__(glm_index::RB * 32) aq[kq][i][2] = o0 ? *reinterpret_cast(b0 + 8) : 0u; aq[kq][i][3] = o1 ? *reinterpret_cast(b1 + 8) : 0u; } + if (rope > 0) glm_rope::frags(aq, q, P + r, rope, inv); float wv[4]; for (int i = 0; i < 4; ++i) { const int64_t hh = g + 8 * i; @@ -80,7 +82,7 @@ extern "C" __global__ void __launch_bounds__(glm_index::RB * 32) const int row = idx / (D / 8), u = idx % (D / 8); const int64_t p = pb * BP + row; const bool ok = p < nmax; - cp16(&tile[buf][tile_at(row, u)], pk + key_at(pt, ps / 2, ok ? p : 0) + u * 8, ok); + cp16(&tile[buf][tile_at(row, u)], pk + key_at(pt, ps / 2, ok ? p : 0, pp) + u * 8, ok); } }; const int64_t first = (int64_t)blockIdx.y * loop; diff --git a/zig/kernels/cuda/glm_ops.cu b/zig/kernels/cuda/glm_ops.cu index 2da3d8b7ba6..bf4d92ef975 100644 --- a/zig/kernels/cuda/glm_ops.cu +++ b/zig/kernels/cuda/glm_ops.cu @@ -6,27 +6,27 @@ constexpr long long PAGE = 512; // rows a KV page holds -// sparse.select_tokens' assembly, a block a row: K pools' 4 tokens, then the tail; on pages each token's row in them. +// sparse.select_tokens' assembly, a block a row: K pools' `pool` tokens, then the tail; on pages each token's row. extern "C" __global__ void tf_glm_dsa_tokens(const long long* pools, const int* pos, int K, int* __restrict__ tokens, int* __restrict__ counts, - const int* pt, long long page_rows) { + const int* pt, long long page_rows, int pool) { glm_pdl::enter(); const int r = blockIdx.x; const long long q = static_cast(*pos) + r; - const long long npool = (q + 1) / 4; - const int width = 4 * K + 3; + const long long npool = (q + 1) / pool; + const int width = pool * K + pool - 1; int* row = tokens + static_cast(r) * width; auto at = [&](long long t) { return static_cast(pt ? pt[t / PAGE] * page_rows + t % PAGE : t); }; - for (int i = threadIdx.x; i < 4 * K; i += blockDim.x) - row[i] = at(pools[static_cast(r) * K + i / 4] * 4 + i % 4); - if (threadIdx.x < 3) { - const long long t = npool * 4 + threadIdx.x; - row[4 * K + threadIdx.x] = t <= q ? at(t) : -1; + for (int i = threadIdx.x; i < pool * K; i += blockDim.x) + row[i] = at(pools[static_cast(r) * K + i / pool] * pool + i % pool); + if (threadIdx.x < pool - 1) { + const long long t = npool * pool + threadIdx.x; + row[pool * K + threadIdx.x] = t <= q ? at(t) : -1; } if (threadIdx.x == 0) { int tail = 0; - for (int t = 0; t < 3; ++t) tail += npool * 4 + t <= q; - counts[r] = npool > K ? 4 * K + tail : 0; + for (int t = 0; t < pool - 1; ++t) tail += npool * pool + t <= q; + counts[r] = npool > K ? pool * K + tail : 0; } } diff --git a/zig/src/core/contract/glm_cuda_records.zig b/zig/src/core/contract/glm_cuda_records.zig index 1b29f5a27b6..bc0b9433aa5 100644 --- a/zig/src/core/contract/glm_cuda_records.zig +++ b/zig/src/core/contract/glm_cuda_records.zig @@ -40,17 +40,17 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "glm_glue tf_glm_rmsnorm_4096_f32w", .symbol = "tf_glm_rmsnorm_4096_f32w", .image = "glm_glue", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 44, .static = 32, .bound = 256 }, .{ .regs = 44, .static = 32, .bound = 256 }, .{ .regs = 44, .static = 32, .bound = 256 }, .{ .regs = 40, .static = 32, .bound = 256 }, .{ .regs = 40, .static = 32, .bound = 256 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_hc_finish_f32w", .symbol = "tf_glm_hc_finish_f32w", .image = "glm_glue", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 80, .static = 48, .bound = 256 }, .{ .regs = 78, .static = 48, .bound = 256 }, .{ .regs = 78, .static = 48, .bound = 256 }, .{ .regs = 80, .static = 48, .bound = 256 }, .{ .regs = 80, .static = 48, .bound = 256 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_lat_write", .symbol = "tf_glm_lat_write", .image = "glm_glue", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 } } }, - .{ .launch = .{ .name = "glm_glue tf_glm_pool_keys", .symbol = "tf_glm_pool_keys", .image = "glm_glue", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 25, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 24, .static = 0, .bound = 32 }, .{ .regs = 24, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "glm_glue tf_glm_scores", .symbol = "tf_glm_scores", .image = "glm_glue", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 126, .static = 32768, .bound = 128 }, .{ .regs = 131, .static = 32768, .bound = 128 }, .{ .regs = 131, .static = 32768, .bound = 128 }, .{ .regs = 155, .static = 32768, .bound = 128 }, .{ .regs = 155, .static = 32768, .bound = 128 } } }, - .{ .launch = .{ .name = "glm_index tf_glm_index_scores", .symbol = "tf_glm_index_scores", .image = "glm_index", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 128, .static = 32768, .bound = 256 }, .{ .regs = 128, .static = 32768, .bound = 256 }, .{ .regs = 128, .static = 32768, .bound = 256 }, .{ .regs = 124, .static = 32768, .bound = 256 }, .{ .regs = 124, .static = 32768, .bound = 256 } } }, + .{ .launch = .{ .name = "glm_glue tf_glm_pool_keys", .symbol = "tf_glm_pool_keys", .image = "glm_glue", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 25, .static = 0, .bound = 32 }, .{ .regs = 27, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "glm_glue tf_glm_scores", .symbol = "tf_glm_scores", .image = "glm_glue", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 122, .static = 32768, .bound = 128 }, .{ .regs = 131, .static = 32768, .bound = 128 }, .{ .regs = 131, .static = 32768, .bound = 128 }, .{ .regs = 154, .static = 32768, .bound = 128 }, .{ .regs = 154, .static = 32768, .bound = 128 } } }, + .{ .launch = .{ .name = "glm_index tf_glm_index_scores", .symbol = "tf_glm_index_scores", .image = "glm_index", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 125, .static = 32768, .bound = 256 }, .{ .regs = 125, .static = 32768, .bound = 256 }, .{ .regs = 125, .static = 32768, .bound = 256 }, .{ .regs = 125, .static = 32768, .bound = 256 }, .{ .regs = 125, .static = 32768, .bound = 256 } } }, .{ .launch = .{ .name = "glm_index tf_glm_index_pools", .symbol = "tf_glm_index_pools", .image = "glm_index", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 62, .static = 33864, .bound = 256 }, .{ .regs = 64, .static = 33864, .bound = 256 }, .{ .regs = 64, .static = 33864, .bound = 256 }, .{ .regs = 59, .static = 33864, .bound = 256 }, .{ .regs = 59, .static = 33864, .bound = 256 } } }, - .{ .launch = .{ .name = "glm_glue tf_glm_select_rows", .symbol = "tf_glm_select_rows", .image = "glm_glue", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 45, .static = 1072, .bound = 128 }, .{ .regs = 54, .static = 1072, .bound = 128 }, .{ .regs = 54, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 } } }, + .{ .launch = .{ .name = "glm_glue tf_glm_select_rows", .symbol = "tf_glm_select_rows", .image = "glm_glue", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 40, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 }, .{ .regs = 48, .static = 1072, .bound = 128 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_select_rows_wide", .symbol = "tf_glm_select_rows_wide", .image = "glm_glue", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 }, .{ .regs = 54, .static = 1296, .bound = 1024 }, .{ .regs = 61, .static = 1296, .bound = 1024 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_dsel_scan", .symbol = "tf_glm_dsel_scan", .image = "glm_glue", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 60, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 48, .static = 1040, .bound = 256 }, .{ .regs = 60, .static = 1040, .bound = 256 }, .{ .regs = 60, .static = 1040, .bound = 256 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_dsel_merge", .symbol = "tf_glm_dsel_merge", .image = "glm_glue", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 56, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 }, .{ .regs = 64, .static = 34064, .bound = 1024 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_chunks_16", .symbol = "tf_glm_chunks_16", .image = "glm_glue", .threads = 256, .dynamic = 83328, .opt_in = true, .min_sm = 80 }, .usage = .{ .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 123, .static = 0, .bound = 256 }, .{ .regs = 123, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "glm_glue tf_glm_chunks_32", .symbol = "tf_glm_chunks_32", .image = "glm_glue", .threads = 256, .dynamic = 101120, .opt_in = true, .min_sm = 80 }, .usage = .{ .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 150, .static = 0, .bound = 256 }, .{ .regs = 130, .static = 0, .bound = 256 }, .{ .regs = 130, .static = 0, .bound = 256 } } }, - .{ .launch = .{ .name = "glm_ops tf_glm_dsa_tokens", .symbol = "tf_glm_dsa_tokens", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "glm_ops tf_glm_dsa_tokens", .symbol = "tf_glm_dsa_tokens", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 29, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "glm_ops tf_glm_kvh_mark", .symbol = "tf_glm_kvh_mark", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "glm_ops tf_glm_kvh_copy", .symbol = "tf_glm_kvh_copy", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 42, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "glm_ops tf_glm_kvh_remap", .symbol = "tf_glm_kvh_remap", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, diff --git a/zig/src/families/glm/cuda_dsa_block.zig b/zig/src/families/glm/cuda_dsa_block.zig index 61d9c15aa63..4d52d0c0878 100644 --- a/zig/src/families/glm/cuda_dsa_block.zig +++ b/zig/src/families/glm/cuda_dsa_block.zig @@ -14,7 +14,7 @@ const kv_host = @import("cuda_kv_host.zig"); pub const prompt_att_rows = 512; /// The indexer's weights, replicated: [wk | weights_proj] [d + heads][dims], wq_b (as stored), gate, LayerNorm, bias. -pub const Index = struct { kw: projection.Proj, gate: u64, ln_w: u64, ln_b: u64, ape: u64, qb: projection.Proj, heads: usize, d: usize }; +pub const Index = struct { kw: projection.Proj, gate: u64, ln_w: u64, ln_b: u64, ape: u64, qb: projection.Proj, heads: usize, d: usize, geom: sparse.Geometry }; /// One DSA layer on a rank of `heads` heads: proj, norms, q_b, kv_b per head as wk/wv, o, indexer; shapes from config. pub const Layer = struct { @@ -67,7 +67,7 @@ pub const Scratch = struct { partials: latent.Partials, dummy: u64, // an i32 select: sparse.Scratch, - tokens: u64, // i32 [rows][sparse.width] + tokens: u64, // i32 [rows][index width] counts: u64, // i32 [rows] mm_part: u64, // fp32 split-K partials at: u64, // an i32: a prompt block's first position (pos + its first row) @@ -149,14 +149,14 @@ pub fn attend(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, stamp.end(); } if (sparseRows(l, host_pos, rows)) { - try sparse.selectTokensProfile(set, k.ops, stream, v.qi, v.ikr + ix.d * 2, kw_rows, c.pk, tk, pos, host_pos, rows, ix.heads, ix.d, c.pk_rows - 2, v.select, v.tokens, v.counts, k.split, k.prof); + try sparse.selectTokensProfile(set, k.ops, stream, v.qi, v.ikr + ix.d * 2, kw_rows, c.pk, tk, pos, host_pos, rows, ix.heads, ix.d, ix.geom, c.pk_rows - 2, v.select, v.tokens, v.counts, k.split, k.prof); const stamp = prof.span(k.prof, stream, .mla); defer stamp.end(); if (c.pks != 0) if (kv_host.active) |*g| { // host rows: gather the picks into device slots, attend there - const slots = try g.gather(k.ops, stream, ix.gate, c.lc, c.pt, t.page_rows, pos, v.tokens, v.counts, rows, sparse.width); - return latent.sparseAttentionFormat(set, stream, v.qa, slots, 0, .{}, v.tokens, v.counts, sparse.width, v.partials, v.ol, rows, l.heads, l.lw, scale); + const slots = try g.gather(k.ops, stream, ix.gate, c.lc, c.pt, t.page_rows, pos, v.tokens, v.counts, rows, ix.geom.width()); + return latent.sparseAttentionFormat(set, stream, v.qa, slots, 0, .{}, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, rows, l.heads, l.lw, scale); }; - try latent.sparseAttentionFormat(set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, sparse.width, v.partials, v.ol, rows, l.heads, l.lw, scale); + try latent.sparseAttentionFormat(set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, rows, l.heads, l.lw, scale); } } @@ -171,7 +171,7 @@ pub fn blockLastRow(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scr try latent.latentWriteFormat(k.set, stream, s.lat, l.lw, c.lc, c.ls, t, pos, rows, l.lw); // all rows, at pos, before any of them attends stamp.end(); stamp = prof.span(k.prof, stream, .index_update); - try sparse.indexUpdate(k.set, stream, s.ikr, kw_rows, s.igr, ix.ln_w, ix.ln_b, ix.ape, c.ik, c.ig, c.pk, tk, pos, rows); + try sparse.indexUpdate(k.set, stream, s.ikr, kw_rows, s.igr, ix.ln_w, ix.ln_b, ix.ape, c.ik, c.ig, c.pk, tk, pos, rows, ix.geom); stamp.end(); try attendLastRow(k, stream, l, c, s, rows, pos, host_pos, nch, t, tk); const pstamp = prof.span(k.prof, stream, .projections); @@ -206,10 +206,10 @@ fn attendLastRow(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratc } if (sparseRows(l, host_pos, rows)) { // one row at host_pos + r0: the same pool bucket, score columns and token list its block computed for it - try sparse.selectTokensProfile(k.set, k.ops, stream, v.qi, s.ikr + r0 * (ix.d + ix.heads) * 2 + ix.d * 2, ix.d + ix.heads, c.pk, tk, at, host_pos + r0, 1, ix.heads, ix.d, c.pk_rows - 2, v.select, v.tokens, v.counts, null, k.prof); + try sparse.selectTokensProfile(k.set, k.ops, stream, v.qi, s.ikr + r0 * (ix.d + ix.heads) * 2 + ix.d * 2, ix.d + ix.heads, c.pk, tk, at, host_pos + r0, 1, ix.heads, ix.d, ix.geom, c.pk_rows - 2, v.select, v.tokens, v.counts, null, k.prof); var stamp = prof.span(k.prof, stream, .mla); defer stamp.end(); - try latent.sparseAttentionFormat(k.set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, sparse.width, v.partials, v.ol, 1, l.heads, l.lw, scale); + try latent.sparseAttentionFormat(k.set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, 1, l.heads, l.lw, scale); } } @@ -249,7 +249,7 @@ fn writeKeys(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, r try latent.latentWriteFormat(set, stream, s.lat, l.lw, c.lc, c.ls, t, pos, rows, l.lw); stamp.end(); stamp = prof.span(k.prof, stream, .index_update); - try sparse.indexUpdate(set, stream, s.ikr, kw_rows, s.igr, ix.ln_w, ix.ln_b, ix.ape, c.ik, c.ig, c.pk, tk, pos, rows); + try sparse.indexUpdate(set, stream, s.ikr, kw_rows, s.igr, ix.ln_w, ix.ln_b, ix.ape, c.ik, c.ig, c.pk, tk, pos, rows, ix.geom); stamp.end(); } diff --git a/zig/src/families/glm/cuda_index.zig b/zig/src/families/glm/cuda_index.zig index 78b727bf681..e720eb315e1 100644 --- a/zig/src/families/glm/cuda_index.zig +++ b/zig/src/families/glm/cuda_index.zig @@ -91,23 +91,23 @@ pub const Kernels = struct { } /// tf_glm_scores' launch for `rows` rows at `at` into out [rows][np]; the first `nb` 64-pool blocks are written. - pub fn scores(k: *const Kernels, s: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, out: u64, at: u64, rows: usize, np: usize, nb: usize, scale: f32, wscale: f32, heads: usize, pt: u64, ps: u64) !void { - return k.scoresTiles(s, qi, wts, w_stride, pk, out, at, rows, np, nb, scale, wscale, heads, pt, ps, score_tiles); + pub fn scores(k: *const Kernels, s: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, out: u64, at: u64, rows: usize, np: usize, nb: usize, scale: f32, wscale: f32, heads: usize, pt: u64, ps: u64, g: sparse.Geometry) !void { + return k.scoresTiles(s, qi, wts, w_stride, pk, out, at, rows, np, nb, scale, wscale, heads, pt, ps, score_tiles, g); } /// As scores, `loop` 64-pool tiles a CTA (speed only: every tiling writes the same scores). - pub fn scoresTiles(k: *const Kernels, s: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, out: u64, at: u64, rows: usize, np: usize, nb: usize, scale: f32, wscale: f32, heads: usize, pt: u64, ps: u64, loop: usize) !void { - const g: [2]u32 = .{ @intCast(cdiv(rows, score_rows)), @intCast(@max(1, cdiv(nb, loop))) }; + pub fn scoresTiles(k: *const Kernels, s: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, out: u64, at: u64, rows: usize, np: usize, nb: usize, scale: f32, wscale: f32, heads: usize, pt: u64, ps: u64, loop: usize, g: sparse.Geometry) !void { + const grid: [2]u32 = .{ @intCast(cdiv(rows, score_rows)), @intCast(@max(1, cdiv(nb, loop))) }; var a: cuda.Args = .{}; - inline for (.{ qi, wts, @as(i64, @intCast(w_stride)), pk, out, at, @as(i64, @intCast(rows)), @as(i64, @intCast(np)), @as(i64, @intCast(nb)), scale, wscale, @as(i64, @intCast(heads)), @as(c_int, @intCast(loop)), pt, @as(i64, @intCast(ps)) }) |v| a.add(v); - try cuda_pdl.launch(k.scores_fn, .{ .grid = .{ .x = g[0], .y = g[1] }, .block = .{ .x = threads } }, s, &a); + inline for (.{ qi, wts, @as(i64, @intCast(w_stride)), pk, out, at, @as(i64, @intCast(rows)), @as(i64, @intCast(np)), @as(i64, @intCast(nb)), scale, wscale, @as(i64, @intCast(heads)), @as(c_int, @intCast(loop)), pt, @as(i64, @intCast(ps)), @as(c_int, @intCast(g.pool)), @as(c_int, @intCast(g.rope)), g.inv }) |v| a.add(v); + try cuda_pdl.launch(k.scores_fn, .{ .grid = .{ .x = grid[0], .y = grid[1] }, .block = .{ .x = threads } }, s, &a); } - /// tf_glm_select_rows' launch: each row's 512 best pools of scores [rows][np] ascending into out [rows][512] int64. - pub fn pools(k: *const Kernels, s: cuda.Stream, scores_ptr: u64, out: u64, at: u64, rows: usize, np: usize, path: u64) !void { + /// tf_glm_select_rows' launch: each row's g.topk best pools of scores [rows][np] into out [rows][g.topk] int64. + pub fn pools(k: *const Kernels, s: cuda.Stream, scores_ptr: u64, out: u64, at: u64, rows: usize, np: usize, path: u64, g: sparse.Geometry) !void { const t = tile(np); var a: cuda.Args = .{}; - inline for (.{ scores_ptr, out, @as(i64, @intCast(np)), at, @as(c_int, topk), @as(c_int, @intCast(t.cap)), @as(c_int, @intCast(t.target)), path }) |v| a.add(v); + inline for (.{ scores_ptr, out, @as(i64, @intCast(np)), at, @as(c_int, @intCast(g.topk)), @as(c_int, @intCast(t.cap)), @as(c_int, @intCast(t.target)), path, @as(c_int, @intCast(g.pool)) }) |v| a.add(v); try cuda_pdl.launch(k.pools_fn, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = pool_threads } }, s, &a); } }; @@ -222,7 +222,7 @@ test "GLM index: prompt chunks take the kernels; a decode row, an unaligned key .{ .rows = 512, .pk = 0x1000, .cap = 256, .want = &.{ 20, 21, 41 } }, // fewer than 512 pools }) |c| { Recorded.n = 0; - try sparse.selectTokens(set, ops, stream, 0x5000, 0x6000, 160, c.pk, table, 0x7000, 65536, c.rows, 32, 128, c.cap, s, 0x8000, 0x9000); + try sparse.selectTokens(set, ops, stream, 0x5000, 0x6000, 160, c.pk, table, 0x7000, 65536, c.rows, 32, 128, .{}, c.cap, s, 0x8000, 0x9000); try std.testing.expectEqualSlices(usize, c.want, Recorded.ids[0..Recorded.n]); } } diff --git a/zig/src/families/glm/cuda_kv8_test.zig b/zig/src/families/glm/cuda_kv8_test.zig index 12f9f4df47b..8c17a3261de 100644 --- a/zig/src/families/glm/cuda_kv8_test.zig +++ b/zig/src/families/glm/cuda_kv8_test.zig @@ -197,6 +197,7 @@ test "GLM FP8 KV: actual DSA dense and sparse passes retain the sequence-owned s l.qk = 256; l.index.heads = 32; l.index.d = 128; + l.index.geom = .{}; var scratch = std.mem.zeroes(dsa.Scratch); scratch.tokens = 500; scratch.counts = 600; @@ -248,6 +249,7 @@ test "GLM KV host: a prompt MTP chunk's pooled keys take their own page stride, l.dims = 4096; l.index.heads = 32; l.index.d = 128; + l.index.geom = .{}; l.dense_limit = 1; const pages: u64 = 145; for ([_]u64{ pks, 0 }) |own| { // TF_GLM_KV_HOST's MTP cache (the second), then pooled keys inside the pages diff --git a/zig/src/families/glm/cuda_snapshot_layout_test.zig b/zig/src/families/glm/cuda_snapshot_layout_test.zig index 88fbffe924d..becdf2a2a96 100644 --- a/zig/src/families/glm/cuda_snapshot_layout_test.zig +++ b/zig/src/families/glm/cuda_snapshot_layout_test.zig @@ -154,3 +154,14 @@ test "cache shape: on pages each cache's part is a 576-wide row's latent then it } try t.expectEqual(kv + 78 * s.cacheBytes(), st.mtp_caches.lc); } + +test "cache shape: index keys stay in GLM-5.3-Flash's ring of index_ring rows, a rebase keeping whole pools" { + var d = Fake.driver(); + var layers: [2]weights.Layer = undefined; + var w: weights.Weights = undefined; + var st = try fixture(&d, &w, &layers); + defer st.deinit(); + try t.expectEqual(@as(usize, state.index_ring), state.shapeOf(&w).keys); + try t.expectEqual(@as(usize, state.index_ring), st.ring_rows); + try t.expectEqual(@as(usize, 4), st.pool); +} diff --git a/zig/src/families/glm/cuda_sparse.zig b/zig/src/families/glm/cuda_sparse.zig index 12764f5be62..f4bef0244ef 100644 --- a/zig/src/families/glm/cuda_sparse.zig +++ b/zig/src/families/glm/cuda_sparse.zig @@ -17,6 +17,25 @@ pub const select_rows = 512; /// A row's token list: the 512 pools' tokens, then the incomplete pool's up to 3. pub const width = topk_pools * pool + pool - 1; +/// The indexer's shape: rows a pooled key sums (1: keys as written), pools a row keeps, roped dims (`inv` [rope / 2]). +pub const Geometry = struct { + pool: usize = pool, + topk: usize = topk_pools, + rope: usize = 0, + inv: u64 = 0, + + /// A row's token list: its pools' tokens, then the incomplete pool's up to pool - 1. + pub fn width(g: Geometry) usize { + return g.topk * g.pool + g.pool - 1; + } + + /// The kernels' cases: pools of 4 (gated) or 1, rope on whole lanes' pairs (a multiple of 4) with its frequencies. + pub fn check(g: Geometry) !void { + if ((g.pool != pool and g.pool != 1) or g.topk == 0 or g.rope % 4 != 0 or g.rope > 128 or (g.rope > 0) != (g.inv != 0)) + return error.IndexShape; + } +}; + fn cdiv(a: usize, b: usize) usize { return (a + b - 1) / b; } @@ -43,13 +62,13 @@ pub fn bitsBytes(rows: usize, np: usize) usize { } /// tf_glm_dsel_scan's grid for `rows` rows from host_pos: the last row's pools (it sees the most) in spans. -pub fn dselScanCtas(host_pos: usize, rows: usize, np: usize) usize { - const last = @min(np, @max((host_pos + rows) / pool, topk_pools)); +pub fn dselScanCtas(host_pos: usize, rows: usize, np: usize, g: Geometry) usize { + const last = @min(np, @max((host_pos + rows) / g.pool, g.topk)); // 0 when every row fits a merge CTA's candidates: the merge takes the rows whole and the scan marks nothing return if (last <= dsel_cap) 0 else cdiv(last, dsel_span); } -/// A decode window's picks (the wide select's rows) on many CTAs: scores [rows][np] at `at` into pools [rows][512]. +/// A decode window's picks (the wide select's rows) on many CTAs: scores [rows][np] at `at` into pools [rows][g.topk]. pub fn decodeSelect( set: glue.Set, stream: cuda.Stream, @@ -62,38 +81,40 @@ pub fn decodeSelect( bits: u64, /// 0, or [rows] int32 for each row's path (glm_index_decode.cuh; the checks count them). path: u64, + g: Geometry, ) !void { const words = cdiv(np, 32); - const g = dselScanCtas(host_pos, rows, np); - if (g > 0) { + const ctas = dselScanCtas(host_pos, rows, np, g); + if (ctas > 0) { var sa: cuda.Args = .{}; - inline for (.{ scores, @as(i64, @intCast(np)), at, @as(c_int, topk_pools), @as(c_int, dsel_target), bits, @as(i64, @intCast(words)) }) |v| sa.add(v); - try cuda_pdl.launch(set.glue.dsel_scan, .{ .grid = .{ .x = @intCast(g), .y = @intCast(rows) }, .block = .{ .x = dsel_scan_threads } }, stream, &sa); + inline for (.{ scores, @as(i64, @intCast(np)), at, @as(c_int, @intCast(g.topk)), @as(c_int, dsel_target), bits, @as(i64, @intCast(words)), @as(c_int, @intCast(g.pool)) }) |v| sa.add(v); + try cuda_pdl.launch(set.glue.dsel_scan, .{ .grid = .{ .x = @intCast(ctas), .y = @intCast(rows) }, .block = .{ .x = dsel_scan_threads } }, stream, &sa); } var ma: cuda.Args = .{}; - inline for (.{ scores, pools, @as(i64, @intCast(np)), at, @as(c_int, topk_pools), bits, @as(i64, @intCast(words)), path }) |v| ma.add(v); + inline for (.{ scores, pools, @as(i64, @intCast(np)), at, @as(c_int, @intCast(g.topk)), bits, @as(i64, @intCast(words)), path, @as(c_int, @intCast(g.pool)) }) |v| ma.add(v); try cuda_pdl.launch(set.glue.dsel_merge, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = dsel_merge_threads } }, stream, &ma); } -/// sparse.index_update: the window's LayerNormed index keys and gates into ik and ig at pos, completed pools into pk. -pub fn indexUpdate(set: glue.Set, stream: cuda.Stream, k_raw: u64, k_stride: usize, gate: u64, ln_w: u64, ln_b: u64, ape: u64, ik: u64, ig: u64, pk: u64, t: latent.Table, pos: u64, rows: usize) !void { +/// sparse.index_update: the window's LayerNormed (and roped) index keys and gates into ik, ig; completed pools into pk. +pub fn indexUpdate(set: glue.Set, stream: cuda.Stream, k_raw: u64, k_stride: usize, gate: u64, ln_w: u64, ln_b: u64, ape: u64, ik: u64, ig: u64, pk: u64, t: latent.Table, pos: u64, rows: usize, g: Geometry) !void { + try g.check(); var a: cuda.Args = .{}; - inline for (.{ k_raw, @as(i64, @intCast(k_stride)), gate, ln_w, ln_b, ik, ig, pos, @as(f32, 1e-6) }) |v| a.add(v); + inline for (.{ k_raw, @as(i64, @intCast(k_stride)), gate, ln_w, ln_b, ik, ig, pos, @as(f32, 1e-6), @as(c_int, @intCast(g.rope)), g.inv }) |v| a.add(v); try cuda_pdl.launch(set.glue.index_write, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 32 } }, stream, &a); var b: cuda.Args = .{}; - inline for (.{ ik, ig, ape, pk, pos, @as(i64, @intCast(rows)), t.pt, @as(i64, @intCast(t.ps)) }) |v| b.add(v); - try cuda_pdl.launch(set.glue.pool_keys, .{ .grid = .{ .x = @intCast(rows / 4 + 2) }, .block = .{ .x = 32 } }, stream, &b); + inline for (.{ ik, ig, ape, pk, pos, @as(i64, @intCast(rows)), t.pt, @as(i64, @intCast(t.ps)), @as(c_int, @intCast(g.pool)) }) |v| b.add(v); + try cuda_pdl.launch(set.glue.pool_keys, .{ .grid = .{ .x = @intCast(rows / g.pool + 2) }, .block = .{ .x = 32 } }, stream, &b); } /// sparse.pool_bucket: visible pools for rows pos .. pos + rows - 1, a power of two (at least 1024), at most `np_max`. -pub fn poolBucket(pos: usize, rows: usize, np_max: usize) usize { - const visible = (pos + rows) / pool + 1; +pub fn poolBucket(pos: usize, rows: usize, np_max: usize, g: Geometry) usize { + const visible = (pos + rows) / g.pool + 1; return @min(np_max, @max(1024, std.math.ceilPowerOfTwoAssert(usize, visible))); } -/// sparse.score_columns: the pool columns selection reads for those rows (the last row's complete pools, at least 512). -pub fn scoreColumns(pos: usize, rows: usize, np_max: usize) usize { - return @min(np_max, @max(topk_pools, (pos + rows) / pool)); +/// sparse.score_columns: the pool columns selection reads (the last row's complete pools, at least topk). +pub fn scoreColumns(pos: usize, rows: usize, np_max: usize, g: Geometry) usize { + return @min(np_max, @max(g.topk, (pos + rows) / g.pool)); } /// select_tokens' 1/sqrt(heads) head-weight scale (32 heads: 1 / 5.656854249492381, as the Python family writes it). @@ -121,15 +142,16 @@ pub fn splitAt(start: usize, from: usize, world: usize) bool { return from > 0 and world > 1 and start >= from; } -/// sparse.select_tokens: rows' tokens (i32 [rows][width], ascending, -1 padded; on pages their rows); count 0 if dense. -pub fn selectTokens(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, t: latent.Table, pos: u64, host_pos: usize, rows: usize, heads: usize, d: usize, np_max_cap: usize, s: Scratch, tokens: u64, counts: u64) !void { - return selectTokensProfile(set, ops, stream, qi, wts, w_stride, pk, t, pos, host_pos, rows, heads, d, np_max_cap, s, tokens, counts, null, null); +/// sparse.select_tokens: rows' tokens (i32 [rows][g.width()], ascending, -1 padded; on pages their rows); 0 if dense. +pub fn selectTokens(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, t: latent.Table, pos: u64, host_pos: usize, rows: usize, heads: usize, d: usize, g: Geometry, np_max_cap: usize, s: Scratch, tokens: u64, counts: u64) !void { + return selectTokensProfile(set, ops, stream, qi, wts, w_stride, pk, t, pos, host_pos, rows, heads, d, g, np_max_cap, s, tokens, counts, null, null); } /// With `split`, this rank picks for its block of rows only (as one pass would, block by block) and gathers the rest. -pub fn selectTokensProfile(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, t: latent.Table, pos: u64, host_pos: usize, rows: usize, heads: usize, d: usize, np_max_cap: usize, s: Scratch, tokens: u64, counts: u64, split: ?Split, profile: ?*@import("cuda_prof.zig").Prof) !void { +pub fn selectTokensProfile(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, qi: u64, wts: u64, w_stride: usize, pk: u64, t: latent.Table, pos: u64, host_pos: usize, rows: usize, heads: usize, d: usize, g: Geometry, np_max_cap: usize, s: Scratch, tokens: u64, counts: u64, split: ?Split, profile: ?*@import("cuda_prof.zig").Prof) !void { const prof = @import("cuda_prof.zig"); - const np_max = poolBucket(host_pos, rows, np_max_cap); + try g.check(); + const np_max = poolBucket(host_pos, rows, np_max_cap, g); const b = @min(rows, select_rows); const loop: usize = if (rows >= score_loop_from) score_loop else 1; const add = try ops.function("tf_glm_add_i32"); @@ -148,68 +170,70 @@ pub fn selectTokensProfile(set: glue.Set, ops: cuda.Module, stream: cuda.Stream, try cuda_pdl.launch(add, .{ .grid = .{}, .block = .{ .x = 32 } }, stream, &args); at = s.at; } - const nb = cdiv(scoreColumns(host_pos + a, n, np_max), 64); + const nb = cdiv(scoreColumns(host_pos + a, n, np_max, g), 64); const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(d), -0.5)); var sa: cuda.Args = .{}; - inline for (.{ qi + a * heads * d * 2, wts + a * w_stride * 2, @as(i64, @intCast(w_stride)), pk, s.scores, at, @as(i64, @intCast(np_max)), @as(i64, @intCast(nb)), scale, headScale(heads), @as(i64, @intCast(heads)), @as(c_int, @intCast(loop)), t.pt, @as(i64, @intCast(t.ps)) }) |v| sa.add(v); + inline for (.{ qi + a * heads * d * 2, wts + a * w_stride * 2, @as(i64, @intCast(w_stride)), pk, s.scores, at, @as(i64, @intCast(np_max)), @as(i64, @intCast(nb)), scale, headScale(heads), @as(i64, @intCast(heads)), @as(c_int, @intCast(loop)), t.pt, @as(i64, @intCast(t.ps)), @as(c_int, @intCast(g.pool)), @as(c_int, @intCast(g.rope)), g.inv }) |v| sa.add(v); if (d != 128 or heads > 32) return error.IndexShape; const quick = if (set.index) |k| if (k.takes(rows, np_max, pk, t.ps)) k else null else null; // a decode window's rows: the same scores from glm_index_scores (8 rows a CTA, key tiles staged once) const dec = if (set.dscore) |k| if (k.takesDecode(rows, np_max, nb, pk, t.ps)) k else null else null; var stamp = prof.span(profile, stream, .index_score); - if (quick) |k| try k.scores(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps) else if (dec) |k| try k.scoresTiles(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps, index_mod.decodeLoop(n, nb)) else try cuda_pdl.launch(set.glue.scores, .{ .grid = .{ .x = @intCast(n), .y = @intCast(cdiv(nb, loop)) }, .block = .{ .x = 128 } }, stream, &sa); + if (quick) |k| try k.scores(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps, g) else if (dec) |k| try k.scoresTiles(stream, qi + a * heads * d * 2, wts + a * w_stride * 2, w_stride, pk, s.scores, at, n, np_max, nb, scale, headScale(heads), heads, t.pt, t.ps, index_mod.decodeLoop(n, nb), g) else try cuda_pdl.launch(set.glue.scores, .{ .grid = .{ .x = @intCast(n), .y = @intCast(cdiv(nb, loop)) }, .block = .{ .x = 128 } }, stream, &sa); stamp.end(); stamp = prof.span(profile, stream, .index_select); if (quick) |k| if (k.select) { - try k.pools(stream, s.scores, s.pools + a * topk_pools * 8, at, n, np_max, 0); + try k.pools(stream, s.scores, s.pools + a * g.topk * 8, at, n, np_max, 0, g); stamp.end(); continue; }; const wide = wideSelect(n, np_max); if (wide and set.dsel and n <= s.bits_rows) { - try decodeSelect(set, stream, s.scores, s.pools + a * topk_pools * 8, np_max, at, host_pos + a, n, s.ls, 0); + try decodeSelect(set, stream, s.scores, s.pools + a * g.topk * 8, np_max, at, host_pos + a, n, s.ls, 0, g); stamp.end(); continue; } var sel: cuda.Args = .{}; - inline for (.{ s.scores, s.pools + a * topk_pools * 8, @as(i64, @intCast(np_max)), at, @as(c_int, topk_pools) }) |v| sel.add(v); + inline for (.{ s.scores, s.pools + a * g.topk * 8, @as(i64, @intCast(np_max)), at, @as(c_int, @intCast(g.topk)), @as(c_int, @intCast(g.pool)) }) |v| sel.add(v); try cuda_pdl.launch(if (wide) set.glue.select_rows_wide else set.glue.select_rows, .{ .grid = .{ .x = @intCast(n) }, .block = .{ .x = if (wide) 1024 else 128 } }, stream, &sel); stamp.end(); } const stamp = prof.span(profile, stream, .index_select); defer stamp.end(); if (split) |x| { // in place: each rank's equal block (the prefill buffers' pools hold world rows more), rank order - const bytes = per * topk_pools * 8; + const bytes = per * g.topk * 8; try x.lib.check(x.lib.api.ncclAllGather(s.pools + x.rank * bytes, s.pools, bytes, .u8, x.comm, stream.handle), "ncclAllGather"); } const assemble = try ops.function("tf_glm_dsa_tokens"); var args: cuda.Args = .{}; args.add(s.pools); args.add(pos); - args.add(@as(c_int, topk_pools)); + args.add(@as(c_int, @intCast(g.topk))); args.add(tokens); args.add(counts); args.add(t.pt); args.add(@as(i64, @intCast(t.page_rows))); + args.add(@as(c_int, @intCast(g.pool))); try cuda_pdl.launch(assemble, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, stream, &args); } test "sparse.py's sizing rules" { - try std.testing.expectEqual(@as(usize, 1024), poolBucket(100, 1, 1 << 20)); - try std.testing.expectEqual(@as(usize, 2048), poolBucket(5000, 1, 1 << 20)); // 1251 visible pools - try std.testing.expectEqual(@as(usize, 512), scoreColumns(100, 1, 1024)); - try std.testing.expectEqual(@as(usize, 1250), scoreColumns(5000, 1, 2048)); + try std.testing.expectEqual(@as(usize, 1024), poolBucket(100, 1, 1 << 20, .{})); + try std.testing.expectEqual(@as(usize, 2048), poolBucket(5000, 1, 1 << 20, .{})); // 1251 visible pools + try std.testing.expectEqual(@as(usize, 512), scoreColumns(100, 1, 1024, .{})); + try std.testing.expectEqual(@as(usize, 1250), scoreColumns(5000, 1, 2048, .{})); try std.testing.expectEqual(@as(usize, 2051), width); + try std.testing.expectEqual(width, (Geometry{}).width()); try std.testing.expectEqual(@as(f32, @floatCast(1.0 / 5.656854249492381)), headScale(32)); } test "GLM index: a decode select's scan covers the last row's pools in spans, and none when the merge takes rows whole" { // 864K: the last row sees 216,064 pools of a 216,080 bucket - try std.testing.expectEqual(@as(usize, 53), dselScanCtas(864256 - 16, 16, 216080)); - try std.testing.expectEqual(@as(usize, 8), dselScanCtas(131072 - 1, 1, 65536)); // 32,768 visible of 65,536 - try std.testing.expectEqual(@as(usize, 0), dselScanCtas(4 * 4096 - 1, 1, 8192)); // 4,096 pools: one merge CTA - try std.testing.expectEqual(@as(usize, 2), dselScanCtas(4 * 4096 + 3, 1, 8192)); - try std.testing.expectEqual(@as(usize, 0), dselScanCtas(100, 1, 4096)); // a few visible: K pools + try std.testing.expectEqual(@as(usize, 53), dselScanCtas(864256 - 16, 16, 216080, .{})); + try std.testing.expectEqual(@as(usize, 8), dselScanCtas(131072 - 1, 1, 65536, .{})); // 32,768 visible of 65,536 + try std.testing.expectEqual(@as(usize, 0), dselScanCtas(4 * 4096 - 1, 1, 8192, .{})); // 4,096 pools: one merge CTA + try std.testing.expectEqual(@as(usize, 2), dselScanCtas(4 * 4096 + 3, 1, 8192, .{})); + try std.testing.expectEqual(@as(usize, 0), dselScanCtas(100, 1, 4096, .{})); // a few visible: K pools try std.testing.expect(dsel_span % (32 * (dsel_scan_threads / 32)) == 0); // whole words for every warp try std.testing.expectEqual(@as(usize, 16 * 2 * 6753 * 4), bitsBytes(16, 216080)); } @@ -220,3 +244,45 @@ test "rank 0 splits a prompt chunk's indexer rows from TF_GLM_INDEX_SPLIT's posi try std.testing.expect(!splitAt(63488, 65536, 3)); try std.testing.expect(!splitAt(65536, 65536, 1)); // one rank holds every row } + +test "GLM index geometry: full GLM-5.3's pools of 1 score every key, keep 2,048 and list them with no tail" { + const full: Geometry = .{ .pool = 1, .topk = 2048, .rope = 64, .inv = 0x1000 }; + try full.check(); + try std.testing.expectEqual(@as(usize, 2048), full.width()); + try std.testing.expectEqual(@as(usize, 8192), poolBucket(5000, 1, 1 << 20, full)); // 5,002 visible keys + try std.testing.expectEqual(@as(usize, 2048), scoreColumns(100, 1, 1 << 20, full)); + try std.testing.expectEqual(@as(usize, 5001), scoreColumns(5000, 1, 8192, full)); + try std.testing.expectEqual(@as(usize, 2), dselScanCtas(4097, 1, 8192, full)); // 4,098 keys past one merge CTA + try std.testing.expectEqual(@as(usize, 0), dselScanCtas(4095, 1, 8192, full)); + try (Geometry{}).check(); + for ([_]Geometry{ .{ .pool = 2 }, .{ .rope = 64 }, .{ .rope = 62, .inv = 0x1000 }, .{ .inv = 0x1000 }, .{ .topk = 0 } }) |g| + try std.testing.expectError(error.IndexShape, g.check()); +} + +test "GLM index geometry: indexUpdate passes GLM-5.3-Flash's rope 0 and pools of 4, full GLM-5.3's rope 64 and pools of 1" { + const R = struct { + var n: usize = 0; + var grids: [2]c_uint = undefined; + var last: [2]c_int = undefined; // index_write's rope, pool_keys' pool + fn launch(_: cuda.abi.Function, gx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + grids[n] = gx; + last[n] = @as(*const c_int, @ptrCast(@alignCast(args.?[if (n == 0) 9 else 8].?))).*; + n += 1; + return 0; + } + }; + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = R.launch; + var ks: glue.Kernels = undefined; + ks.index_write = .{ .d = &d, .handle = @ptrFromInt(1) }; + ks.pool_keys = .{ .d = &d, .handle = @ptrFromInt(2) }; + const stream: cuda.Stream = .{ .d = &d, .handle = null }; + for ([_]Geometry{ .{}, .{ .pool = 1, .topk = 2048, .rope = 64, .inv = 0x1000 } }) |g| { + R.n = 0; + try indexUpdate(.{ .glue = &ks }, stream, 0x100, 160, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x800, .{}, 0x900, 64, g); + try std.testing.expectEqual(@as(usize, 2), R.n); + try std.testing.expectEqual([2]c_uint{ 64, @intCast(64 / g.pool + 2) }, R.grids); + try std.testing.expectEqual([2]c_int{ @intCast(g.rope), @intCast(g.pool) }, R.last); + } + try std.testing.expectError(error.IndexShape, indexUpdate(.{ .glue = &ks }, stream, 0, 160, 0, 0, 0, 0, 0, 0, 0, .{}, 0, 64, .{ .pool = 2 })); +} diff --git a/zig/src/families/glm/cuda_state.zig b/zig/src/families/glm/cuda_state.zig index 805afc05663..3be6dfde8f7 100644 --- a/zig/src/families/glm/cuda_state.zig +++ b/zig/src/families/glm/cuda_state.zig @@ -71,9 +71,10 @@ pub const Shape = struct { row: usize, // kv_lora + qk_rope: 512 on GLM-5.3-Flash i_dim: usize, pool: usize, // rows a pooled key sums: 4 on GLM-5.3-Flash + keys: usize, // index key and gate rows a cache holds: a ring of index_ring, or maxInt for a whole sequence's pub fn of(c: anytype, caches: usize) Shape { - return .{ .caches = caches, .row = c.latentRow(), .i_dim = c.i_dim, .pool = c.kpool }; + return .{ .caches = caches, .row = c.latentRow(), .i_dim = c.i_dim, .pool = c.kpool, .keys = index_ring }; } /// One cache's latent rows on a page, and their pooled keys. @@ -132,7 +133,7 @@ fn stateSizes(gpa: std.mem.Allocator, w: *const weights.Weights, capacity: usize const n = s.kda.len() * c.kda_dim; const kw = @import("cuda_kda_block.zig").rowWidth(s.kda.len()); // TF_GLM_KDA_PAD const pk_rows = capacity / c.kpool + 2; - const ring_rows = @min(capacity, index_ring); + const ring_rows = @min(capacity, shapeOf(w).keys); const rows: usize = @intFromBool(table == null); // on pages a cache's rows are the pool's var sizes: std.ArrayList(usize) = .empty; errdefer sizes.deinit(gpa); @@ -272,7 +273,7 @@ pub const Buffers = struct { const part_rows = if (prefill) @min(rows, dsa_block.prompt_att_rows) else seg; const nch = latent.chunksFor(@min(capacity, dense_reach) + seg); const partial_rows = @max(nch * part_rows, latent.chunksFor(sparse.width) * seg); // dense calls, or one sparse - const np_max = capacity / sparse.pool; + const np_max = capacity / c.kpool; const sel = selectLs(rows, prefill, seg, np_max); var mm: usize = 4; // windows under rows_from rows keep their K slices apart (a prompt's tail chunk on the prefill buffers too) @@ -300,7 +301,7 @@ pub const Buffers = struct { @min(seg, sparse.select_rows) * np_max * 4, sel.bytes, // ls: the list rows, and on a decode's buffers its select's bit words rows * sparse.select_list * 4, - (if (prefill) rows + s.world else rows) * sparse.topk_pools * 8, // pools; a split's equal blocks end at most world - 1 rows past them + (if (prefill) rows + s.world else rows) * (c.i_topk / c.kpool) * 8, // pools; a split's equal blocks end at most world - 1 rows past them 4, rows * sparse.width * 4, rows * 4, @@ -423,7 +424,8 @@ pub const State = struct { rec_layer: usize, proj_layer: usize, proj_row: usize, - ring_rows: usize, // index rows each ring holds: min(capacity, index_ring) + ring_rows: usize, // index rows each ring holds: min(capacity, Shape.keys) + pool: usize, // rows a pooled key sums: a rebase keeps whole pools ring_row: usize, // bytes of one index row rings: []u64, // each DSA layer's ik ring then ig ring, the MTP layer's last: [layers + 1][2] base: usize = 0, // the first position the main rings hold (their pointers are ring - base rows) @@ -476,8 +478,8 @@ pub const State = struct { for (caches, 0..) |*x, j| x.* = .{ .lc = p[8 + 4 * j], .ls = if (kv8) p[8 + 4 * j] + capacity * c.latentRow() else 0, .ik = p[9 + 4 * j], .ig = p[10 + 4 * j], .pk = p[11 + 4 * j], .pk_rows = pk_rows }; const rings = try gpa.alloc(u64, 2 * (nd + 1)); for (0..nd + 1) |j| rings[2 * j ..][0..2].* = .{ p[9 + 4 * j], p[10 + 4 * j] }; - const ring_rows = @min(capacity, index_ring); - var st: State = .{ .ring_rows = ring_rows, .ring_row = c.i_dim * 2, .rings = rings, .arena = a, .gpa = gpa, .capacity = capacity, .pos_dev = p[0], .conv = p[1], .rec = p[2], .proj = p[3], .save_k = p[4], .save_v = p[5], .save_g = p[6], .save_b = p[7], .cur = cur, .heads = s.kda.len(), .mtp_caches = .{ .lc = p[8 + 4 * nd], .ls = if (kv8) p[8 + 4 * nd] + capacity * c.latentRow() else 0, .ik = p[9 + 4 * nd], .ig = p[10 + 4 * nd], .pk = p[11 + 4 * nd], .pk_rows = pk_rows }, .mtp_pos_dev = p[12 + 4 * nd], .prompt_hidden = p[13 + 4 * nd], .kda_layers = nk, .caches = caches, .conv_c = 3 * n, .rec_layer = s.kda.len() * kda.dk * kda.dv * 4, .proj_layer = window_rows * kw, .proj_row = kw }; + const ring_rows = @min(capacity, shapeOf(w).keys); + var st: State = .{ .pool = c.kpool, .ring_rows = ring_rows, .ring_row = c.i_dim * 2, .rings = rings, .arena = a, .gpa = gpa, .capacity = capacity, .pos_dev = p[0], .conv = p[1], .rec = p[2], .proj = p[3], .save_k = p[4], .save_v = p[5], .save_g = p[6], .save_b = p[7], .cur = cur, .heads = s.kda.len(), .mtp_caches = .{ .lc = p[8 + 4 * nd], .ls = if (kv8) p[8 + 4 * nd] + capacity * c.latentRow() else 0, .ik = p[9 + 4 * nd], .ig = p[10 + 4 * nd], .pk = p[11 + 4 * nd], .pk_rows = pk_rows }, .mtp_pos_dev = p[12 + 4 * nd], .prompt_hidden = p[13 + 4 * nd], .kda_layers = nk, .caches = caches, .conv_c = 3 * n, .rec_layer = s.kda.len() * kda.dk * kda.dv * 4, .proj_layer = window_rows * kw, .proj_row = kw }; if (paged) |q| { st.table = p[14 + 4 * nd]; st.capacity = 0; // no rows until a stream's pages are mapped @@ -553,7 +555,7 @@ pub const State = struct { const at = if (mtp) st.mtp_len else st.pos; const old = if (mtp) st.mtp_base else st.base; const floor = if (mtp) at -| window_rows else at; - const nb = floor / sparse.pool * sparse.pool; + const nb = floor / st.pool * st.pool; const keep = (at - nb) * st.ring_row; const d = st.arena.buf.d; const first: usize = if (mtp) st.caches.len else 0; diff --git a/zig/src/families/glm/cuda_weights.zig b/zig/src/families/glm/cuda_weights.zig index 438c71d93ad..48ddff20cb9 100644 --- a/zig/src/families/glm/cuda_weights.zig +++ b/zig/src/families/glm/cuda_weights.zig @@ -278,7 +278,7 @@ const Loader = struct { .wk = wk, .wv = wv, .o = o, - .index = .{ .kw = kw, .gate = gate, .ln_w = ln_w, .ln_b = ln_b, .ape = ape, .qb = qb, .heads = c.i_heads, .d = c.i_dim }, + .index = .{ .kw = kw, .gate = gate, .ln_w = ln_w, .ln_b = ln_b, .ape = ape, .qb = qb, .heads = c.i_heads, .d = c.i_dim, .geom = .{ .pool = c.kpool, .topk = c.i_topk / c.kpool } }, .heads = h.len(), .qk = qk, .dv = c.v_dim, diff --git a/zig/tests/cuda/contract_glm_dsel.zig b/zig/tests/cuda/contract_glm_dsel.zig index a93cd2abba4..f73b76753cf 100644 --- a/zig/tests/cuda/contract_glm_dsel.zig +++ b/zig/tests/cuda/contract_glm_dsel.zig @@ -48,7 +48,7 @@ pub const Dsel = struct { const b = &self.base; const set: glm.glue.Set = .{ .glue = &self.fns, .dsel = true }; const n = if (self.short and b.shape.n > 2 * sparse.dsel_span) b.shape.n - sparse.dsel_span else b.shape.n; - try sparse.decodeSelect(set, b.rig.s, b.in, b.out, n, b.pos, b.at, b.shape.rows, self.bits, 0); + try sparse.decodeSelect(set, b.rig.s, b.in, b.out, n, b.pos, b.at, b.shape.rows, self.bits, 0, .{}); try b.rig.s.synchronize(); } diff --git a/zig/tests/cuda/contract_glm_full.zig b/zig/tests/cuda/contract_glm_full.zig new file mode 100644 index 00000000000..75b3177d6a5 --- /dev/null +++ b/zig/tests/cuda/contract_glm_full.zig @@ -0,0 +1,252 @@ +//! Full GLM-5.3's indexer on the GLM-5.3-Flash kernels under the contract: pools of 1 and 64 roped dims, with controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const glm = @import("glm_cuda"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const index = @import("contract_glm_index.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const rows_ = core.contract.rows; +const sparse = glm.sparse; + +const dk = 128; +const rope = 64; // full GLM-5.3's roped index dims +const theta = 8.0e6; // its rope_theta +const eps: f32 = 1e-6; +const k_stride = dk + 32; // the keys sit in a wider row, as the block passes them + +/// A lane's chain of 4 products or adds, then 5 butterflies. +fn depth(_: c.Shape) usize { + return 10; +} + +fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = depth, .out = .bf16, .served = &.{ .{ .rows = 8, .n = dk, .k = dk }, .{ .rows = 64, .n = dk, .k = dk } } }; +} + +/// sparse._index_write: each row's key LayerNormed, its first 64 dims roped at its position, at row pos + r of ik. +pub const IndexWrite = struct { + rig: rig_.Rig, + f: cuda.Function, + name: []const u8, + fault: index.Fault = .none, + arena: ?std.heap.ArenaAllocator = null, + rows: usize = 0, + at: usize = 0, + x: []const u16 = &.{}, + w: []const u16 = &.{}, + b: []const u16 = &.{}, + freqs: [32]f32 = @splat(0), + extra: []f64 = &.{}, + dev: [7]u64 = undefined, // kr, gr, lnw, lnb, ik, ig, pos + inv: u64 = 0, + + pub fn deinit(self: *IndexWrite) void { + if (self.arena) |*a| a.deinit(); + self.rig.deinit(); + } + + const vt = g.hooks(IndexWrite); + + pub fn kernel(self: *IndexWrite) g.Kernel { + return .{ .spec = spec(self.name), .ctx = self, .vt = &vt, .control = if (self.fault != .none) .shapes else null }; + } + + /// Rows offset by 0, 16 or 128 over noise in [-1, 1); stress: 128 plus integer pairs, an exact rope (inv 0). + pub fn prepare(self: *IndexWrite, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.k != dk or shape.n != dk or shape.rows == 0) return false; + self.rig.reset(); + if (self.arena) |*a| a.deinit(); + self.arena = std.heap.ArenaAllocator.init(self.rig.gpu.gpa); + const a = self.arena.?.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const x = try a.alloc(u16, shape.rows * k_stride); + const w = try a.alloc(u16, dk); + const b = try a.alloc(u16, dk); + const gr = try a.alloc(f32, shape.rows * dk); + for (w) |*v| v.* = c.toBf16(rng.float(f32) * 3 - 0.5); + for (b) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + for (gr) |*v| v.* = rng.float(f32) * 4 - 2; + for (0..shape.rows) |r| { + const row = x[r * k_stride ..][0..k_stride]; + if (fill == .stress) { // 128 + v, 128 - v: every sum and square exact in fp32, the mean 128 + for (0..k_stride / 2) |j| { + const v: f32 = @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 129))) - 64); + row[2 * j] = c.toBf16(128 + v); + row[2 * j + 1] = c.toBf16(128 - v); + } + continue; + } + const offset: f32 = switch (r % 3) { + 0 => 0, + 1 => 16, + else => 128, + }; + for (row) |*v| v.* = c.toBf16(offset + rng.float(f32) * 2 - 1); + } + if (fill == .nonfinite) { + const planted = [_]struct { usize, usize, f32 }{ .{ 0, 3, std.math.nan(f32) }, .{ 1, 70, std.math.inf(f32) }, .{ 2, dk - 1, -std.math.inf(f32) } }; + for (planted) |p| if (p[0] < shape.rows) { + x[p[0] * k_stride + p[1]] = c.toBf16(p[2]); + }; + } + self.rows = shape.rows; + self.at = if (shape.rows <= 8) 70_000 else 300_000; + self.x = x; + self.w = w; + self.b = b; + self.freqs = if (fill == .stress) @splat(0) else cuda.mla.ropeFreqs(theta); + self.extra = try a.alloc(f64, shape.rows * dk); + const p: i32 = @intCast(self.at); + const out = try self.rig.output(shape.rows * dk * 2); + const ig = try self.rig.scratch(shape.rows * dk * 2); + const back = self.at * dk * 2; // the kernel writes row pos + r: the buffers' start less pos rows + self.dev = .{ try self.rig.input(std.mem.sliceAsBytes(x)), try self.rig.input(std.mem.sliceAsBytes(gr)), try self.rig.input(std.mem.sliceAsBytes(w)), try self.rig.input(std.mem.sliceAsBytes(b)), out - back, ig - back, try self.rig.input(std.mem.asBytes(&p)) }; + self.inv = try self.rig.input(std.mem.sliceAsBytes(&self.freqs)); + return true; + } + + pub fn run(self: *IndexWrite) !void { + var a: cuda.Args = .{}; + const d = self.dev; + const roped: c_int = if (self.fault == .unroped) 0 else rope; + inline for (.{ d[0], @as(i64, k_stride), d[1], d[2], d[3], d[4], d[5], d[6], eps, roped, self.inv }) |v| a.add(v); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.rows) }, .block = .{ .x = 32 } }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *IndexWrite) usize { + return self.rows * dk; + } + + /// Rows in float64 with each sum as `sum` gives it, then the pairs below 64 turned at pos + r. + fn outputs(self: *IndexWrite, out: []f64, mag: ?[]f64, sum: anytype) !void { + var v: [dk]f64 = undefined; + var t: [dk]f64 = undefined; + var y: [dk]f64 = undefined; + var m: [dk]f64 = undefined; + var e: [dk]f64 = undefined; + for (0..self.rows) |r| { + var abs: f64 = 0; + for (&v, self.x[r * k_stride ..][0..dk]) |*z, h| { + z.* = c.fromBf16(h); + abs += @abs(z.*); + } + const mean = sum.of(&v) / dk; + for (&t, v) |*z, x| z.* = (x - mean) * (x - mean); + const sd = @sqrt(@as(f64, eps) + sum.of(&t) / dk); + for (0..dk) |i| { + const wi: f64 = c.fromBf16(self.w[i]); + const bi: f64 = c.fromBf16(self.b[i]); + const term = (v[i] - mean) / sd * wi; + y[i] = term + bi; + // the sums' error reaches an output through x - mean (the mean's) and sd (the squares') + m[i] = (2 * @abs(v[i] - mean) + abs / dk) / sd * @abs(wi); + // the divisions (2 ulp each), sqrt.approx, the eps add and the fma after the sums + e[i] = 12 * 0x1p-24 * (@abs(term) + @abs(bi)); + } + const pos: f32 = @floatFromInt(self.at + r); + for (0..rope / 2) |i| { + const angle: f64 = self.freqs[i] * pos; // the fp32 product, as the kernel forms it + const co = @cos(angle); + const si = @sin(angle); + const y0 = y[2 * i]; + const y1 = y[2 * i + 1]; + y[2 * i] = y0 * co - y1 * si; + y[2 * i + 1] = y1 * co + y0 * si; + // an output takes both inputs' errors, then sincosf's 2 ulp, two products and the add + const both = e[2 * i] + e[2 * i + 1] + 8 * 0x1p-24 * (@abs(y0) + @abs(y1)); + const ms = m[2 * i] + m[2 * i + 1]; + e[2 * i] = both; + e[2 * i + 1] = both; + m[2 * i] = ms; + m[2 * i + 1] = ms; + } + @memcpy(out[r * dk ..][0..dk], &y); + if (mag) |mg| @memcpy(mg[r * dk ..][0..dk], &m); + for (self.extra[r * dk ..][0..dk], e) |*z, x| z.* = if (std.math.isFinite(x)) x else 0; + } + } + + const Exact = struct { + fn of(_: Exact, t: []const f64) f64 { + var s: f64 = 0; + for (t) |x| s += x; + return s; + } + }; + + const Sim = struct { + acc: c.Accum, + order: g.Order, + fn of(s: Sim, t: []const f64) f64 { + return rows_.sumIn(s.acc, s.order, t); + } + }; + + pub fn reference(self: *IndexWrite, want: []f64, mag: []f64) !void { + try self.outputs(want, mag, Exact{}); + for (mag) |*x| if (!std.math.isFinite(x.*)) { + x.* = 0; + }; + } + + pub fn bounds(self: *IndexWrite, _: []const f64, _: []const f64, allow: []f64) !void { + for (allow, self.extra) |*l, x| l.* += x * (1 + 0x1p-7); + } + + pub fn simulate(self: *IndexWrite, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.outputs(out, null, Sim{ .acc = acc, .order = order }); + } +}; + +/// Full GLM-5.3's cases and their controls, on the heap so the kernels' contexts keep their address. +pub const Full = struct { + idx: cuda.Module, + ops: cuda.Module, + scores: index.Scores, + fast: index.Scores, + tokens: index.Tokens, + write: IndexWrite, + unroped: index.Scores, + pool_of_4: index.Scores, + late: index.Tokens, + write_unroped: IndexWrite, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, fns: glm.glue.Kernels, kernels: *std.ArrayList(g.Kernel)) !*Full { + const self = try a.create(Full); + errdefer a.destroy(self); + var idx = try cuda.Module.load(gpu.d, cuda.kernels.glm_index); + errdefer idx.unload(); + var ops = try cuda.Module.load(gpu.d, cuda.kernels.glm_ops); + errdefer ops.unload(); + const r: rig_.Rig = .{ .gpu = gpu, .s = s }; + const fast = try idx.function("tf_glm_index_scores"); + const toks = try ops.function("tf_glm_dsa_tokens"); + self.* = .{ + .idx = idx, + .ops = ops, + .scores = .{ .rig = r, .f = fns.scores, .pool = 1, .rope = rope }, + .fast = .{ .rig = r, .f = fns.scores, .fast = fast, .pool = 1, .rope = rope, .label = "cuda glm tf_glm_index_scores, pools of 1 and 64 roped query dims" }, + .tokens = .{ .rig = r, .f = toks, .pool = 1 }, + .write = .{ .rig = r, .f = fns.index_write, .name = "cuda glm tf_glm_index_write, 64 roped key dims" }, + .unroped = .{ .rig = r, .f = fns.scores, .pool = 1, .rope = rope, .fault = .unroped, .label = "control: GLM scores leave full GLM-5.3's queries unroped" }, + .pool_of_4 = .{ .rig = r, .f = fns.scores, .pool = 1, .rope = rope, .fault = .pool_of_4, .label = "control: GLM scores read full GLM-5.3's keys as pools of 4" }, + .late = .{ .rig = r, .f = toks, .pool = 1, .fault = .late, .label = "control: GLM token lists of pools of 1 one position late" }, + .write_unroped = .{ .rig = r, .f = fns.index_write, .name = "control: GLM index write leaves full GLM-5.3's keys unroped", .fault = .unroped }, + }; + inline for (.{ &self.scores, &self.fast, &self.tokens, &self.write, &self.unroped, &self.pool_of_4, &self.late, &self.write_unroped }) |x| try kernels.append(a, x.kernel()); + return self; + } + + pub fn destroy(self: *Full, a: std.mem.Allocator) void { + inline for (.{ &self.scores, &self.fast, &self.tokens, &self.write, &self.unroped, &self.pool_of_4, &self.late, &self.write_unroped }) |x| x.deinit(); + self.ops.unload(); + self.idx.unload(); + a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_glm_index.zig b/zig/tests/cuda/contract_glm_index.zig index 643915b00dc..a89a0ad00d9 100644 --- a/zig/tests/cuda/contract_glm_index.zig +++ b/zig/tests/cuda/contract_glm_index.zig @@ -8,6 +8,7 @@ const rig_ = @import("contract_rig.zig"); const pages = @import("contract_glm_pages.zig"); const select = @import("contract_glm_select.zig"); const dsel = @import("contract_glm_dsel.zig"); +const full_k = @import("contract_glm_full.zig"); const contract = core.contract; const c = contract.spec; @@ -31,14 +32,19 @@ const nan_relu = "relu is fmaxf(x, 0), as Triton's tl.maximum: a NaN dot scores /// A decode window's served shapes: decodeLoop's 2, 4 and 1 tiles a CTA, as cuda_sparse launches Set.dscore. const decode_served = [_]c.Shape{ .{ .rows = 8, .n = 4096, .k = dk }, .{ .rows = 16, .n = 51200, .k = dk }, .{ .rows = 4, .n = 131072, .k = dk } }; -/// scores: rows x pool columns (k: an index key's width); tokens: rows x K pools a row. -pub fn spec(comptime which: enum { scores, tokens }) c.Spec { +/// scores: rows x pool columns (k: an index key's width); tokens: rows x K pools a row; full: full GLM-5.3's indexer. +pub fn spec(comptime which: enum { scores, tokens, scores_full, tokens_full }) c.Spec { return switch (which) { .scores => .{ .name = "cuda glm tf_glm_scores on pages out of order", .accum = .f32, .depth = scoreDepth, .ops = 2, .out = .f32, .served = &.{ .{ .rows = 8, .n = 2048, .k = dk }, .{ .rows = 64, .n = 1024, .k = dk } }, .known = .{ .gate = .nonfinite, .finding = nan_relu } }, .tokens => .{ .name = "cuda glm tf_glm_dsa_tokens on pages out of order", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "integers only: pool ids, positions and page ids" }, .served = &.{ .{ .rows = 8, .n = sparse.topk_pools, .k = 1 }, .{ .rows = 64, .n = sparse.topk_pools, .k = 1 } } }, + .scores_full => .{ .name = "cuda glm tf_glm_scores, pools of 1 and 64 roped query dims", .accum = .f32, .depth = scoreDepth, .ops = 2, .out = .f32, .served = &.{ .{ .rows = 8, .n = 1024, .k = dk }, .{ .rows = 64, .n = 2048, .k = dk } }, .known = .{ .gate = .nonfinite, .finding = nan_relu } }, + .tokens_full => .{ .name = "cuda glm tf_glm_dsa_tokens, pools of 1", .accum = .none, .depth = noSums, .out = .raw, .nan = .{ .stated = "integers only: pool ids, positions and page ids" }, .served = &.{ .{ .rows = 8, .n = 2048, .k = 1 }, .{ .rows = 64, .n = 2048, .k = 1 } } }, }; } +/// A planted fault on full GLM-5.3's indexer: queries or keys left unroped, pools read as 4, rows one position late. +pub const Fault = enum { none, unroped, pool_of_4, late }; + const maxNan = pages.maxNan; const held = pages.held; const sumIn = pages.sumIn; @@ -53,6 +59,15 @@ pub const Scores = struct { wrong_table: bool = false, decode: bool = false, // a decode window's tiles a CTA (glm.index.decodeLoop), as cuda_sparse launches Set.dscore short: bool = false, // the control: the decode tiling is told it has one 64-pool tile fewer + /// Rows a pooled key sums (1: each key) and the queries' roped dims (full GLM-5.3: 1, 64), a fault, a name. + pool: usize = sparse.pool, + rope: usize = 0, + fault: Fault = .none, + label: ?[]const u8 = null, + freqs: [32]f32 = @splat(0), + qr: []f64 = &.{}, // the queries roped in float64 + extra: []f64 = &.{}, // per score: the roped queries' bf16 rounding and sincosf + inv: u64 = 0, shape: c.Shape = undefined, q: []u16 = &.{}, w: []u16 = &.{}, @@ -80,10 +95,14 @@ pub const Scores = struct { } a.free(self.ids); self.ids = &.{}; + a.free(self.qr); + self.qr = &.{}; + a.free(self.extra); + self.extra = &.{}; } pub fn kernel(self: *Scores) g.Kernel { - var declared = spec(.scores); + var declared = if (self.pool == 1) spec(.scores_full) else spec(.scores); if (self.fast != null) { declared.name = "cuda glm tf_glm_index_scores on pages out of order"; declared.replaces = "tf_glm_scores"; @@ -94,13 +113,20 @@ pub const Scores = struct { } if (self.short) declared.name = "control: GLM decode scores write one tile short"; if (self.wrong_table) declared.name = "control: GLM paged scores use a swapped table"; - return .{ .spec = declared, .ctx = self, .vt = &vt, .control = if (self.wrong_table or self.short) .shapes else null }; + if (self.label) |name| declared.name = name; + const planted = self.wrong_table or self.short or self.fault != .none; + return .{ .spec = declared, .ctx = self, .vt = &vt, .control = if (planted) .shapes else null }; } const vt = g.hooks(Scores); fn visible(self: *const Scores, r: usize) usize { - return (self.at + r + 1) / sparse.pool; + return (self.at + r + 1) / self.pool; + } + + /// A page's step in bytes: the test's two-cache page, or past its 512 keys at pools of 1. + fn pageStep(self: *const Scores) usize { + return if (self.pool == 1) pages.part_bytes + pages.rows_a_page * (pages.lw + dk) * 2 else pages.page_bytes; } /// Queries and keys in [-2, 2); stress: integers in [-8, 8] and power-of-two scales; non-finite: NaN and inf. @@ -113,7 +139,7 @@ pub const Scores = struct { var prng = std.Random.DefaultPrng.init(seed); const rng = prng.random(); // decode: up to 8,192 visible pools (64 pages) - self.at = if (self.decode) @as(usize, @min(shape.n, 8192)) * sparse.pool - shape.rows - 4 else if (shape.rows <= 8) 4100 else 2000; + self.at = if (self.decode) @as(usize, @min(shape.n, 8192)) * self.pool - shape.rows - 4 else if (self.pool == 1) (if (shape.rows <= 8) @as(usize, 1000) else 1900) else if (shape.rows <= 8) 4100 else 2000; self.scale = if (fill == .stress) 0.125 else @floatCast(std.math.pow(f64, dk, -0.5)); self.wscale = if (fill == .stress) 0.25 else sparse.headScale(heads); self.seen = self.visible(shape.rows - 1); @@ -129,14 +155,16 @@ pub const Scores = struct { self.q[3] = c.toBf16(std.math.nan(f32)); self.keys[2 * dk + 5] = c.toBf16(std.math.inf(f32)); } - const n_pages = (self.seen + 127) / 128; + try self.ropeQueries(fill); + const pp = pages.rows_a_page / self.pool; // pools a page holds + const n_pages = (self.seen + pp - 1) / pp; self.ids = try pages.shuffled(a, rng, n_pages); - const arena = try a.alloc(u8, (n_pages + 3) * pages.page_bytes); + const arena = try a.alloc(u8, (n_pages + 3) * self.pageStep()); defer a.free(arena); @memset(arena, 0); const pk = pages.part_bytes + pages.rows_a_page * pages.lw * 2; // the cache's pooled keys in page 0 for (0..self.seen) |p| { - const at = pk + @as(usize, @intCast(self.ids[p / 128])) * pages.page_bytes + (p % 128) * dk * 2; + const at = pk + @as(usize, @intCast(self.ids[p / pp])) * self.pageStep() + (p % pp) * dk * 2; @memcpy(arena[at..][0 .. dk * 2], std.mem.sliceAsBytes(self.keys[p * dk ..][0..dk])); } const p: i32 = @intCast(self.at); @@ -145,11 +173,37 @@ pub const Scores = struct { self.in[2] = try self.rig.input(arena) + pk; self.pos = try self.rig.input(std.mem.asBytes(&p)); self.pt = try pages.uploadTable(&self.rig, self.ids, self.wrong_table); + self.inv = if (self.rope > 0) try self.rig.input(std.mem.sliceAsBytes(&self.freqs)) else 0; self.out = try self.rig.output(shape.rows * shape.n * 4); self.base = try self.rig.scratch(shape.rows * shape.n * 4); return true; } + /// Each row's queries roped at its position in float64 (stress: frequencies 0, so the rope is exact). + fn ropeQueries(self: *Scores, fill: g.Fill) !void { + const a = self.rig.gpu.gpa; + self.freqs = if (self.rope > 0 and fill != .stress) cuda.mla.ropeFreqs(8.0e6) else @splat(0); + self.qr = try a.alloc(f64, self.q.len); + for (self.qr, self.q) |*y, x| y.* = c.fromBf16(x); + self.extra = try a.alloc(f64, self.q.len); + @memset(self.extra, 0); + for (0..self.shape.rows) |r| for (0..heads) |h| for (0..self.rope / 2) |i| { + const at = (r * heads + h) * dk + 2 * i; + const x0 = self.qr[at]; + const x1 = self.qr[at + 1]; + const p: f32 = @floatFromInt(self.at + r); + const angle: f64 = self.freqs[i] * p; // the fp32 product, as the kernel forms it + const co = @cos(angle); + const si = @sin(angle); + self.qr[at] = x0 * co - x1 * si; + self.qr[at + 1] = x1 * co + x0 * si; + // bf16's half ulp of the roped value, then sincosf's 2 ulp, two products and the add (stress: exact) + const turn = 8 * 0x1p-24 * (@abs(x0) + @abs(x1)); + const exact = fill == .stress or !std.math.isFinite(turn); + for ([2]usize{ at, at + 1 }) |d| self.extra[d] = if (exact) 0 else 0x1p-8 * @abs(self.qr[d]) + turn; + }; + } + pub fn run(self: *Scores) !void { try self.launch(self.fast orelse self.f, self.fast != null, self.out); try self.rig.s.synchronize(); @@ -159,15 +213,18 @@ pub const Scores = struct { const rows = self.shape.rows; const nb = if (fast and self.short) self.shape.n / 64 - 1 else self.shape.n / 64; const loop: usize = if (fast and self.decode) glm.index.decodeLoop(rows, self.shape.n / 64) else if (fast) glm.index.score_tiles else if (rows >= sparse.score_loop_from) sparse.score_loop else 1; + const pool: c_int = if (self.fault == .pool_of_4) 4 else @intCast(self.pool); + const rope: c_int = if (self.fault == .unroped) 0 else @intCast(self.rope); + const ps: i64 = @intCast(self.pageStep()); var a: cuda.Args = .{}; if (fast) { - inline for (.{ self.in[0], self.in[1], @as(i64, w_stride), self.in[2], out, self.pos, @as(i64, @intCast(rows)), @as(i64, @intCast(self.shape.n)), @as(i64, @intCast(nb)), self.scale, self.wscale, @as(i64, heads), @as(c_int, @intCast(loop)), self.pt, @as(i64, pages.page_bytes) }) |v| a.add(v); + inline for (.{ self.in[0], self.in[1], @as(i64, w_stride), self.in[2], out, self.pos, @as(i64, @intCast(rows)), @as(i64, @intCast(self.shape.n)), @as(i64, @intCast(nb)), self.scale, self.wscale, @as(i64, heads), @as(c_int, @intCast(loop)), self.pt, ps, pool, rope, self.inv }) |v| a.add(v); var g2 = glm.index.scoresGrid(rows, nb); // cuda_sparse's decode grid: nb tiles in runs of loop if (self.decode) g2[1] = @intCast(@max(1, (nb + loop - 1) / loop)); try cuda.launch.launch(f, .{ .grid = .{ .x = g2[0], .y = g2[1] }, .block = .{ .x = glm.index.threads } }, self.rig.s, &a); } else { - inline for (.{ self.in[0], self.in[1], @as(i64, w_stride), self.in[2], out, self.pos, @as(i64, @intCast(self.shape.n)), @as(i64, @intCast(nb)), self.scale, self.wscale, @as(i64, heads), @as(c_int, @intCast(loop)), self.pt, @as(i64, pages.page_bytes) }) |v| a.add(v); + inline for (.{ self.in[0], self.in[1], @as(i64, w_stride), self.in[2], out, self.pos, @as(i64, @intCast(self.shape.n)), @as(i64, @intCast(nb)), self.scale, self.wscale, @as(i64, heads), @as(c_int, @intCast(loop)), self.pt, ps, pool, rope, self.inv }) |v| a.add(v); try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(rows), .y = @intCast((nb + loop - 1) / loop) }, .block = .{ .x = 128 } }, self.rig.s, &a); } } @@ -193,7 +250,7 @@ pub const Scores = struct { for (&terms, 0..) |*t, h| { var abs: f64 = 0; for (&dots, 0..) |*x, d| { - x.* = c.fromBf16(self.q[(r * heads + h) * dk + d]) * c.fromBf16(self.keys[p * dk + d]); + x.* = self.qr[(r * heads + h) * dk + d] * @as(f64, c.fromBf16(self.keys[p * dk + d])); abs += @abs(x.*); } const wv = c.fromBf16(self.w[r * w_stride + h]) * wscale; @@ -210,6 +267,24 @@ pub const Scores = struct { }; } + /// The roped queries' rounding reaches a score through each head's weight, the scale and its keys; -inf is exact. + pub fn bounds(self: *Scores, _: []const f64, _: []const f64, allow: []f64) !void { + for (allow) |*l| if (!std.math.isFinite(l.*)) { + l.* = 0; + }; + if (self.rope == 0) return; + for (0..self.shape.rows) |r| for (0..self.visible(r)) |p| { + var e: f64 = 0; + for (0..heads) |h| { + var s: f64 = 0; + for (0..self.rope) |d| s += self.extra[(r * heads + h) * dk + d] * @abs(@as(f64, c.fromBf16(self.keys[p * dk + d]))); + const w = @abs(@as(f64, c.fromBf16(self.w[r * w_stride + h]))) * @as(f64, self.wscale) * @as(f64, self.scale); + if (std.math.isFinite(s)) e += w * s; + } + allow[r * self.shape.n + p] += e * (1 + 0x1p-7); + }; + } + pub fn simulate(self: *Scores, acc: c.Accum, order: g.Order, out: []f64) !void { var mag: f64 = 0; for (0..self.shape.rows) |r| for (0..self.shape.n) |p| { @@ -218,11 +293,15 @@ pub const Scores = struct { } }; -/// sparse.select_tokens' assembly on pages: each row's K pools' 4 tokens and the visible tail as rows in the pages. +/// sparse.select_tokens' assembly on pages: each row's K pools' tokens and the visible tail as rows in the pages. pub const Tokens = struct { rig: rig_.Rig, f: cuda.Function, wrong_table: bool = false, + /// Tokens a pool holds (full GLM-5.3: 1), a fault (late: launched one position on), a name. + pool: usize = sparse.pool, + fault: Fault = .none, + label: ?[]const u8 = null, shape: c.Shape = undefined, pools: []i64 = &.{}, ids: []i32 = &.{}, @@ -250,15 +329,17 @@ pub const Tokens = struct { } pub fn kernel(self: *Tokens) g.Kernel { - var declared = spec(.tokens); + var declared = if (self.pool == 1) spec(.tokens_full) else spec(.tokens); if (self.wrong_table) declared.name = "control: GLM paged token assembly uses a swapped table"; - return .{ .spec = declared, .ctx = self, .vt = &vt, .control = if (self.wrong_table) .shapes else null }; + if (self.label) |name| declared.name = name; + const planted = self.wrong_table or self.fault != .none; + return .{ .spec = declared, .ctx = self, .vt = &vt, .control = if (planted) .shapes else null }; } const vt = g.hooks(Tokens); fn width(self: *const Tokens) usize { - return 4 * self.shape.n + 3; + return self.pool * self.shape.n + self.pool - 1; } /// From row 2046 on, so the first rows still see K pools or fewer (count 0) and the rest select K of theirs. @@ -273,11 +354,11 @@ pub const Tokens = struct { self.at = 2046; self.pools = try a.alloc(i64, shape.rows * shape.n); for (0..shape.rows) |r| { - const seen = (self.at + r + 1) / sparse.pool; + const seen = (self.at + r + 1) / self.pool; for (self.pools[r * shape.n ..][0..shape.n]) |*v| v.* = rng.uintLessThan(u32, @intCast(seen)); } - self.ids = try pages.shuffled(a, rng, (self.at + shape.rows + pages.rows_a_page - 1) / pages.rows_a_page); - const p: i32 = @intCast(self.at); + self.ids = try pages.shuffled(a, rng, (self.at + shape.rows + @intFromBool(self.fault == .late) + pages.rows_a_page - 1) / pages.rows_a_page); + const p: i32 = @intCast(self.at + @intFromBool(self.fault == .late)); self.in = try self.rig.input(std.mem.sliceAsBytes(self.pools)); self.pos = try self.rig.input(std.mem.asBytes(&p)); self.pt = try pages.uploadTable(&self.rig, self.ids, self.wrong_table); @@ -295,6 +376,7 @@ pub const Tokens = struct { a.add(self.counts); a.add(self.pt); a.add(@as(i64, page_rows)); + a.add(@as(c_int, @intCast(self.pool))); try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows) }, .block = .{ .x = 256 } }, self.rig.s, &a); try self.rig.s.synchronize(); } @@ -319,23 +401,24 @@ pub const Tokens = struct { const a = self.rig.gpu.gpa; const w = self.width(); const k = self.shape.n; + const n_a = self.pool; // tokens a pool const got = try a.dupe(u8, try self.rig.bytes(self.tokens, self.shape.rows * w * 4)); defer a.free(got); const counts = try self.rig.bytes(self.counts, self.shape.rows * 4); for (0..self.shape.rows) |r| { const q: i64 = @intCast(self.at + r); - const seen = @divFloor(q + 1, sparse.pool); + const seen = @divFloor(q + 1, @as(i64, @intCast(n_a))); var tail: i32 = 0; for (0..w) |i| { - const want: i32 = if (i < 4 * k) self.row(self.pools[r * k + i / 4] * 4 + @as(i64, @intCast(i % 4))) else blk: { - const t = seen * 4 + @as(i64, @intCast(i - 4 * k)); + const want: i32 = if (i < n_a * k) self.row(self.pools[r * k + i / n_a] * @as(i64, @intCast(n_a)) + @as(i64, @intCast(i % n_a))) else blk: { + const t = seen * @as(i64, @intCast(n_a)) + @as(i64, @intCast(i - n_a * k)); tail += @intFromBool(t <= q); break :blk if (t <= q) self.row(t) else -1; }; const v = std.mem.readInt(i32, got[(r * w + i) * 4 ..][0..4], .little); if (v != want) return try std.fmt.bufPrint(&self.msg, "row {d} token {d}: {d} where the table gives {d}", .{ r, i, v, want }); } - const n: i32 = if (seen > k) @as(i32, @intCast(4 * k)) + tail else 0; + const n: i32 = if (seen > k) @as(i32, @intCast(n_a * k)) + tail else 0; const v = std.mem.readInt(i32, counts[r * 4 ..][0..4], .little); if (v != n) return try std.fmt.bufPrint(&self.msg, "row {d}: count {d} where {d} is due", .{ r, v, n }); } @@ -349,9 +432,12 @@ pub const Index = struct { select: select.Select, dsel: dsel.Dsel, dsel_short: dsel.Dsel, + fns: glm.glue.Kernels, + full: ?*full_k.Full = null, // full GLM-5.3's indexer cases, made by append + a: ?std.mem.Allocator = null, pub fn init(gpu: check.Gpu, s: cuda.Stream, fns: glm.glue.Kernels) Index { - return .{ .scores = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns.scores }, .select = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .dsel = .{ .base = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .fns = fns }, .dsel_short = .{ .base = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .fns = fns, .short = true } }; + return .{ .scores = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fns.scores }, .select = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .dsel = .{ .base = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .fns = fns }, .dsel_short = .{ .base = .{ .rig = .{ .gpu = gpu, .s = s }, .wide = fns.select_rows_wide, .narrow = fns.select_rows }, .fns = fns, .short = true }, .fns = fns }; } /// After init's value sits at its final address: each kernel's context points into it. @@ -360,9 +446,12 @@ pub const Index = struct { try kernels.append(a, self.select.kernel()); try kernels.append(a, self.dsel.kernel()); try kernels.append(a, self.dsel_short.kernel()); + self.full = try full_k.Full.create(a, self.scores.rig.gpu, self.scores.rig.s, self.fns, kernels); + self.a = a; } pub fn deinit(self: *Index) void { + if (self.full) |f| f.destroy(self.a.?); self.dsel_short.deinit(); self.dsel.deinit(); self.select.deinit(); diff --git a/zig/tests/cuda/contract_glm_pages.zig b/zig/tests/cuda/contract_glm_pages.zig index 5c9a4b4cfe9..56175f8fa2d 100644 --- a/zig/tests/cuda/contract_glm_pages.zig +++ b/zig/tests/cuda/contract_glm_pages.zig @@ -284,7 +284,7 @@ pub const PoolKeys = struct { pub fn run(self: *PoolKeys) !void { var a: cuda.Args = .{}; const pk = self.arena + part_bytes + rows_a_page * lw * 2; // the cache's pooled keys in page 0 - inline for (.{ self.in[0], self.in[1], self.in[2], pk, self.pos, @as(i64, @intCast(self.shape.rows)), self.pt, @as(i64, page_bytes) }) |v| a.add(v); + inline for (.{ self.in[0], self.in[1], self.in[2], pk, self.pos, @as(i64, @intCast(self.shape.rows)), self.pt, @as(i64, page_bytes), @as(c_int, 4) }) |v| a.add(v); try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows / 4 + 2) }, .block = .{ .x = 32 } }, self.rig.s, &a); var i: usize = 0; while (i < self.pools) { // the pools back from their pages, a page's run at a time diff --git a/zig/tests/cuda/contract_glm_pools.zig b/zig/tests/cuda/contract_glm_pools.zig index af34644c185..80ef5c2ce49 100644 --- a/zig/tests/cuda/contract_glm_pools.zig +++ b/zig/tests/cuda/contract_glm_pools.zig @@ -107,7 +107,7 @@ pub const Pools = struct { const x = self.shape; const t = glm.index.tile(x.n); var a: cuda.Args = .{}; - inline for (.{ self.in, self.out, @as(i64, @intCast(x.n)), self.pos, @as(c_int, @intCast(x.k)), @as(c_int, @intCast(t.cap)), @as(c_int, @intCast(t.target)), @as(u64, 0) }) |v| a.add(v); + inline for (.{ self.in, self.out, @as(i64, @intCast(x.n)), self.pos, @as(c_int, @intCast(x.k)), @as(c_int, @intCast(t.cap)), @as(c_int, @intCast(t.target)), @as(u64, 0), @as(c_int, sparse.pool) }) |v| a.add(v); try cuda.launch.launch(self.fast, .{ .grid = .{ .x = @intCast(x.rows) }, .block = .{ .x = glm.index.pool_threads } }, self.rig.s, &a); try self.rig.s.synchronize(); } @@ -116,7 +116,7 @@ pub const Pools = struct { pub fn replaced(self: *Pools) ![]const u8 { const x = self.shape; var a: cuda.Args = .{}; - inline for (.{ self.in, self.base, @as(i64, @intCast(x.n)), self.pos, @as(c_int, @intCast(x.k)) }) |v| a.add(v); + inline for (.{ self.in, self.base, @as(i64, @intCast(x.n)), self.pos, @as(c_int, @intCast(x.k)), @as(c_int, sparse.pool) }) |v| a.add(v); try cuda.launch.launch(self.narrow, .{ .grid = .{ .x = @intCast(x.rows) }, .block = .{ .x = 128 } }, self.rig.s, &a); return self.rig.bytes(self.base, self.outBytes()); } diff --git a/zig/tests/cuda/contract_glm_select.zig b/zig/tests/cuda/contract_glm_select.zig index e28f3ce49cf..a56ff3c92fe 100644 --- a/zig/tests/cuda/contract_glm_select.zig +++ b/zig/tests/cuda/contract_glm_select.zig @@ -111,7 +111,7 @@ pub const Select = struct { fn launch(self: *Select, f: cuda.Function, threads: u32, out: u64) !void { const x = self.shape; var a: cuda.Args = .{}; - inline for (.{ self.in, out, @as(i64, @intCast(x.n)), self.pos, @as(c_int, @intCast(x.k)) }) |v| a.add(v); + inline for (.{ self.in, out, @as(i64, @intCast(x.n)), self.pos, @as(c_int, @intCast(x.k)), @as(c_int, sparse.pool) }) |v| a.add(v); try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(x.rows) }, .block = .{ .x = threads } }, self.rig.s, &a); } diff --git a/zig/tests/cuda/glm_index_check.zig b/zig/tests/cuda/glm_index_check.zig index 0bd928f3281..171e87efb35 100644 --- a/zig/tests/cuda/glm_index_check.zig +++ b/zig/tests/cuda/glm_index_check.zig @@ -83,7 +83,7 @@ pub fn run(gpu: check.Gpu) !void { const rand = rng.random(); var fails: usize = 0; for (cases) |c| { - const np = sp.poolBucket(c.pos, c.rows, c.cap); + const np = sp.poolBucket(c.pos, c.rows, c.cap, .{}); const qi = try gpa.alloc(u16, c.rows * c.heads * d); defer gpa.free(qi); for (qi) |*x| x.* = bf16(rand.floatNorm(f32)); @@ -136,10 +136,10 @@ pub fn run(gpu: check.Gpu) !void { var ms_new: f64 = 0; for (0..3) |rep| { const t0 = std.Io.Timestamp.now(gpu.io, .awake); - try sp.selectTokens(old, ops, s, dq, dw, c.heads, dk, table, dpos, c.pos, c.rows, c.heads, d, c.cap, sa, ta, ca); + try sp.selectTokens(old, ops, s, dq, dw, c.heads, dk, table, dpos, c.pos, c.rows, c.heads, d, .{}, c.cap, sa, ta, ca); try s.synchronize(); const t1 = std.Io.Timestamp.now(gpu.io, .awake); - try sp.selectTokens(new, ops, s, dq, dw, c.heads, dk, table, dpos, c.pos, c.rows, c.heads, d, c.cap, sb, tb, cb); + try sp.selectTokens(new, ops, s, dq, dw, c.heads, dk, table, dpos, c.pos, c.rows, c.heads, d, .{}, c.cap, sb, tb, cb); try s.synchronize(); const t2 = std.Io.Timestamp.now(gpu.io, .awake); if (rep > 0) { @@ -148,7 +148,7 @@ pub fn run(gpu: check.Gpu) !void { } } step(c, np, "selectTokens scores-only"); - try sp.selectTokens(half, ops, s, dq, dw, c.heads, dk, table, dpos, c.pos, c.rows, c.heads, d, c.cap, sc, tc, cc); + try sp.selectTokens(half, ops, s, dq, dw, c.heads, dk, table, dpos, c.pos, c.rows, c.heads, d, .{}, c.cap, sc, tc, cc); try s.synchronize(); step(c, np, "compare scores, pools, tokens, scores-only"); const blk: usize = @min(c.rows, sp.select_rows); @@ -201,7 +201,7 @@ fn decode(gpu: check.Gpu, s: cuda.Stream, ops: cuda.Module, ks: *const glm.glue. const special = [_]f32{ std.math.nan(f32), -std.math.nan(f32), 0.0, -0.0, std.math.inf(f32), -std.math.inf(f32) }; var fails: usize = 0; for (dcases) |c| { - const np = sp.poolBucket(c.pos, c.rows, c.cap); + const np = sp.poolBucket(c.pos, c.rows, c.cap, .{}); var bufs: Bufs = .empty; defer { for (bufs.items) |*b| b.free(); @@ -243,9 +243,9 @@ fn decode(gpu: check.Gpu, s: cuda.Stream, ops: cuda.Module, ks: *const glm.glue. step(.{ .cap = c.cap, .pos = c.pos, .rows = c.rows }, np, "decode select: planted scores"); try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = scores, .len = c.rows * np * 4, .borrowed = true }).upload(0, std.mem.sliceAsBytes(host)); var sel: cuda.Args = .{}; - inline for (.{ scores, pa, @as(i64, @intCast(np)), dpos, @as(c_int, sp.topk_pools) }) |v| sel.add(v); + inline for (.{ scores, pa, @as(i64, @intCast(np)), dpos, @as(c_int, sp.topk_pools), @as(c_int, sp.pool) }) |v| sel.add(v); try cuda.launch.launch(old.glue.select_rows, .{ .grid = .{ .x = @intCast(c.rows) }, .block = .{ .x = 128 } }, s, &sel); - try sp.decodeSelect(new, s, scores, pb, np, dpos, c.pos, c.rows, bits, path); + try sp.decodeSelect(new, s, scores, pb, np, dpos, c.pos, c.rows, bits, path, .{}); try s.synchronize(); var taken: [16]i32 = undefined; try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = path, .len = c.rows * 4, .borrowed = true }).download(0, std.mem.sliceAsBytes(taken[0..c.rows])); @@ -274,7 +274,7 @@ fn decode(gpu: check.Gpu, s: cuda.Stream, ops: cuda.Module, ks: *const glm.glue. const dq = try fromHost(gpu, &bufs, std.mem.sliceAsBytes(qi)); const dw = try fromHost(gpu, &bufs, std.mem.sliceAsBytes(wts)); const dk = try fromHost(gpu, &bufs, std.mem.sliceAsBytes(pk)); - const nb = (sp.scoreColumns(c.pos, c.rows, np) + 63) / 64; // selectTokens' blocks + const nb = (sp.scoreColumns(c.pos, c.rows, np, .{}) + 63) / 64; // selectTokens' blocks if (idx.takesDecode(c.rows, np, nb, dk, 0)) dscored += 1; // the latent table's default ps is 0 var sa = try scratch(gpu, &bufs, c.rows, np); var sb = try scratch(gpu, &bufs, c.rows, np); @@ -290,10 +290,10 @@ fn decode(gpu: check.Gpu, s: cuda.Stream, ops: cuda.Module, ks: *const glm.glue. var ms_new: f64 = 0; for (0..4) |rep| { const t0 = std.Io.Timestamp.now(gpu.io, .awake); - try sp.selectTokens(old, ops, s, dq, dw, 32, dk, .{}, dpos, c.pos, c.rows, 32, d, c.cap, sa, ta, ca); + try sp.selectTokens(old, ops, s, dq, dw, 32, dk, .{}, dpos, c.pos, c.rows, 32, d, .{}, c.cap, sa, ta, ca); try s.synchronize(); const t1 = std.Io.Timestamp.now(gpu.io, .awake); - try sp.selectTokens(new, ops, s, dq, dw, 32, dk, .{}, dpos, c.pos, c.rows, 32, d, c.cap, sb, tb, cb); + try sp.selectTokens(new, ops, s, dq, dw, 32, dk, .{}, dpos, c.pos, c.rows, 32, d, .{}, c.cap, sb, tb, cb); try s.synchronize(); const t2 = std.Io.Timestamp.now(gpu.io, .awake); if (rep > 0) { @@ -326,16 +326,16 @@ fn blocks(gpu: check.Gpu, bufs: *Bufs, set: glm.glue.Set, idx: *const glm.index. step(c, np, "block: upload its position, clear outputs"); const at_v: i32 = @intCast(c.pos + a); const at = try fromHost(gpu, bufs, std.mem.asBytes(&at_v)); - const nb = (sp.scoreColumns(c.pos + a, n, np) + 63) / 64; + const nb = (sp.scoreColumns(c.pos + a, n, np, .{}) + 63) / 64; try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = out_a, .len = n * np * 4, .borrowed = true }).fill8(0, null); try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = out_b, .len = n * np * 4, .borrowed = true }).fill8(0, null); try gpu.d.synchronize(); // the memsets run on the default stream, not on s step(c, np, "block: tf_glm_scores"); var sa: cuda.Args = .{}; - inline for (.{ dq + a * c.heads * d * 2, dw + a * c.heads * 2, @as(i64, @intCast(c.heads)), dk, out_a, at, @as(i64, @intCast(np)), @as(i64, @intCast(nb)), scale, sp.headScale(c.heads), @as(i64, @intCast(c.heads)), @as(c_int, @intCast(loop)), t.pt, @as(i64, @intCast(t.ps)) }) |v| sa.add(v); + inline for (.{ dq + a * c.heads * d * 2, dw + a * c.heads * 2, @as(i64, @intCast(c.heads)), dk, out_a, at, @as(i64, @intCast(np)), @as(i64, @intCast(nb)), scale, sp.headScale(c.heads), @as(i64, @intCast(c.heads)), @as(c_int, @intCast(loop)), t.pt, @as(i64, @intCast(t.ps)), @as(c_int, sp.pool), @as(c_int, 0), @as(u64, 0) }) |v| sa.add(v); try cuda.launch.launch(set.glue.scores, .{ .grid = .{ .x = @intCast(n), .y = @intCast((nb + loop - 1) / loop) }, .block = .{ .x = 128 } }, s, &sa); step(c, np, "block: tf_glm_index_scores"); - try idx.scores(s, dq + a * c.heads * d * 2, dw + a * c.heads * 2, c.heads, dk, out_b, at, n, np, nb, scale, sp.headScale(c.heads), c.heads, t.pt, t.ps); + try idx.scores(s, dq + a * c.heads * d * 2, dw + a * c.heads * 2, c.heads, dk, out_b, at, n, np, nb, scale, sp.headScale(c.heads), c.heads, t.pt, t.ps, .{}); try s.synchronize(); step(c, np, "block: compare"); fails += try same(gpu, "block scores", out_a, out_b, n * np * 4, np, c); @@ -387,10 +387,10 @@ fn ties(gpu: check.Gpu, bufs: *Bufs, rand: std.Random, set: glm.glue.Set, idx: * try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = sa.scores, .len = rows * np * 4, .borrowed = true }).upload(0, std.mem.sliceAsBytes(host)); step(c, np, "ties: tf_glm_select_rows"); var sel: cuda.Args = .{}; - inline for (.{ sa.scores, sa.pools, @as(i64, @intCast(np)), at, @as(c_int, sp.topk_pools) }) |v| sel.add(v); + inline for (.{ sa.scores, sa.pools, @as(i64, @intCast(np)), at, @as(c_int, sp.topk_pools), @as(c_int, sp.pool) }) |v| sel.add(v); try cuda.launch.launch(set.glue.select_rows, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 128 } }, s, &sel); step(c, np, "ties: tf_glm_index_pools"); - try idx.pools(s, sa.scores, sb.pools, at, rows, np, path); + try idx.pools(s, sa.scores, sb.pools, at, rows, np, path, .{}); try s.synchronize(); step(c, np, "ties: read the paths"); var taken: [512]i32 = undefined; diff --git a/zig/tests/cuda/glm_ref_index.zig b/zig/tests/cuda/glm_ref_index.zig index 9514cf62cdb..9d4c8a8d629 100644 --- a/zig/tests/cuda/glm_ref_index.zig +++ b/zig/tests/cuda/glm_ref_index.zig @@ -23,8 +23,8 @@ pub fn selection(r: *Rig, set: glm.glue.Set, ops: cuda.Module) !void { const pos = 6000; const rows = 96; const cap = 4096; - const np = sp.poolBucket(pos, rows, cap); - const cols = @min(np, (sp.scoreColumns(pos, rows, np) + 63) / 64 * 64); + const np = sp.poolBucket(pos, rows, cap, .{}); + const cols = @min(np, (sp.scoreColumns(pos, rows, np, .{}) + 63) / 64 * 64); const qi = try r.bfs(rows * heads * d, 1.0); const wts = try r.bfs(rows * heads, 1.0); const pk = try r.bfs(np * d, 1.0); @@ -32,7 +32,7 @@ pub fn selection(r: *Rig, set: glm.glue.Set, ops: cuda.Module) !void { const s: sp.Scratch = .{ .scores = try r.zeros(rows * np * 4), .ls = try r.zeros(rows * sp.select_list * 4), .li = try r.zeros(rows * sp.select_list * 4), .pools = try r.zeros(rows * sp.topk_pools * 8), .at = try r.zeros(4) }; const tokens = try r.zeros(rows * sp.width * 4); const counts = try r.zeros(rows * 4); - try sp.selectTokens(set, ops, r.s, try r.dev(std.mem.sliceAsBytes(qi)), try r.dev(std.mem.sliceAsBytes(wts)), heads, try r.dev(std.mem.sliceAsBytes(pk)), .{}, try r.dev(std.mem.asBytes(&p0)), pos, rows, heads, d, cap, s, tokens, counts); + try sp.selectTokens(set, ops, r.s, try r.dev(std.mem.sliceAsBytes(qi)), try r.dev(std.mem.sliceAsBytes(wts)), heads, try r.dev(std.mem.sliceAsBytes(pk)), .{}, try r.dev(std.mem.asBytes(&p0)), pos, rows, heads, d, .{}, cap, s, tokens, counts); const raw = try r.back(s.scores, rows * np * 4); const got = std.mem.bytesAsSlice(f32, raw); @@ -110,7 +110,7 @@ pub fn selectionWide(r: *Rig, set: glm.glue.Set) !void { for (cases) |c| { const pos = c[0]; const rows = c[1]; - const np = sp.poolBucket(pos, rows, 1 << 20); + const np = sp.poolBucket(pos, rows, 1 << 20, .{}); const host = try r.a.alloc(f32, rows * np); for (0..rows) |row| { const vis = (pos + row + 1) / 4; @@ -126,7 +126,7 @@ pub fn selectionWide(r: *Rig, set: glm.glue.Set) !void { var ms: [2]f64 = undefined; for ([2]cuda.Function{ set.glue.select_rows, set.glue.select_rows_wide }, [2]u32{ 128, 1024 }, outs, 0..) |f, threads, out, i| { var a: cuda.Args = .{}; - inline for (.{ scores, out, @as(i64, @intCast(np)), at, @as(c_int, sp.topk_pools) }) |v| a.add(v); + inline for (.{ scores, out, @as(i64, @intCast(np)), at, @as(c_int, sp.topk_pools), @as(c_int, sp.pool) }) |v| a.add(v); const cfg: cuda.launch.Config = .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = threads } }; try cuda.launch.launch(f, cfg, r.s, &a); try t0.record(r.s); From 9f670db22df96a87bd46558cc2ca79ed5ef2a89c Mon Sep 17 00:00:00 2001 From: bjornmonnens <787697+bjornmonnens@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:13:37 +0100 Subject: [PATCH 3/8] glm cuda: the latent path takes full GLM-5.3's 576-wide roped rows on the mla image (#3063) Full GLM-5.3 keeps 64 roped key columns past its 512-value latent and splits each 256-wide q head into 192 latent-path dims and 64 roped ones. The DSA block's Layer carries rope (Config.rope, 0 on GLM-5.3-Flash) and its fp32 frequencies; row() is lw + rope and qHead() qk + rope, which size the kv_a and q_b widths, the latent and absorbed q rows, their scratch and the token lists' page rows, and the softmax scale is 1 / sqrt(qk + rope) (1 / 16 on both). A roped row takes cuda.mla's image (loaded only when Config.rope is set): its GPT-J rope turns k_pe at pos + r into the latent row before the cache write and each head's q_pe into qa past the absorbed latent; the chunk tiles are tf_mla_chunks_r16 (chunks_wide<16, false, 64>), now launched on pages and over token lists through Mla.chunksOn as GLM's own chunks are. Roped rows keep 16 heads a block in prompt chunks too: wide_smem<32, 64>() is 113,408 bytes, past the 99 KiB a block may take on sm_86 to sm_121. The merge and expand_v stay GLM's (the values are the latent's). The one new kernel is tf_mla_absorb_q_192 (tf_mla::absorb_q<192>, q rows 256 apart, qa rows 576), under the contract with a planted control and nvcc 13.0 records (72 registers on every SM). A page is padded to whole 576-wide rows and whole token bytes (their lcm), so a token list's page rows stay whole: full GLM-5.3's 79 caches take 4,096 bytes more a page (49,440 rows). GLM-5.3-Flash's page, buffers, kernels and launch arguments are unchanged, pinned by host tests at both shapes. --- docs/kernel-contract.md | 11 +- zig/kernels/cuda/mla.cu | 9 +- zig/src/core/contract/mla_cuda_records.zig | 1 + zig/src/cuda/mla.zig | 27 +- zig/src/families/glm/cuda.zig | 1 + zig/src/families/glm/cuda_dsa_block.zig | 87 ++++-- zig/src/families/glm/cuda_engine.zig | 2 +- zig/src/families/glm/cuda_forward.zig | 8 +- zig/src/families/glm/cuda_glue.zig | 2 + zig/src/families/glm/cuda_latent.zig | 60 +++- zig/src/families/glm/cuda_latent_test.zig | 263 ++++++++++++++++++ .../glm/cuda_snapshot_layout_test.zig | 6 +- zig/src/families/glm/cuda_state.zig | 26 +- zig/src/families/glm/cuda_tile.zig | 4 +- zig/src/families/glm/cuda_weights.zig | 4 +- zig/tests/cuda/contract_mla.zig | 5 +- zig/tests/cuda/contract_mla_proj.zig | 39 ++- zig/tests/cuda/glm_loader_gate.zig | 2 +- 18 files changed, 479 insertions(+), 78 deletions(-) create mode 100644 zig/src/families/glm/cuda_latent_test.zig diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 7bb58007c6c..9817be8710e 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -572,11 +572,12 @@ squares in bf16. CUDA also checks the mla image (`mla.cu`, MLA over a 512-wide latent with 64 roped columns and 128-wide heads, on GLM's chunk bodies): the head-wise gate, the rope (plain, and with YaRN's attention factor at 900,000 positions), the -128-wide absorb_q and expand_v, and the chunk tiles (`tf_mla_chunks_r16`, 576-wide q and keys over a linear cache, -through `tf_glm_merge`; the split form with `tf_mla_merge_part`), each against float64 (eight controls, real launches -each given one planted fault: the gate reading the next head's column, the plain rope one position late, the YaRN -rope without its factor, absorb_q and expand_v reading the next head's weights, the chunks the next head's queries, -the split chunks reading a rank's page z as chunk z, and the per-rank merge one chunk short). +128-wide absorb_q and expand_v, full GLM-5.3's 192-wide absorb_q (`tf_mla_absorb_q_192`, 21 and 22 heads), and the +chunk tiles (`tf_mla_chunks_r16`, 576-wide q and keys over a linear cache, through `tf_glm_merge`; the split form with +`tf_mla_merge_part`), each against float64 (nine controls, real launches each given one planted fault: the gate +reading the next head's column, the plain rope one position late, the YaRN rope without its factor, both absorb_q +forms and expand_v reading the next head's weights, the chunks the next head's queries, the split chunks reading a +rank's page z as chunk z, and the per-rank merge one chunk short). ## CUDA records per nvcc release diff --git a/zig/kernels/cuda/mla.cu b/zig/kernels/cuda/mla.cu index d6ccf00f303..4d7da0e0ddb 100644 --- a/zig/kernels/cuda/mla.cu +++ b/zig/kernels/cuda/mla.cu @@ -1,4 +1,4 @@ -// MLA over a 512-wide latent with 64 roped columns and 128-wide heads (Ling-3.1), on common/mla.cuh's bodies. +// MLA over a 512-wide latent with 64 roped columns (Ling-3.1's 128-wide heads, GLM-5.3's 192), on common/mla.cuh. #include #include @@ -34,6 +34,13 @@ extern "C" __global__ void __launch_bounds__(128) tf_mla::absorb_q<128>(q, wk, qa, rows, heads, rb, qs, qaw); } +// Full GLM-5.3's q_nope (the first 192 of each head's qs columns, 256 there) absorbed the same way. +extern "C" __global__ void __launch_bounds__(128) + tf_mla_absorb_q_192(const __nv_bfloat16* q, const __nv_bfloat16* wk, __nv_bfloat16* qa, int64_t rows, + int64_t heads, int64_t rb, int64_t qs, int64_t qaw) { + tf_mla::absorb_q<192>(q, wk, qa, rows, heads, rb, qs, qaw); +} + // The latent output expanded into 128-wide v heads. extern "C" __global__ void __launch_bounds__(128) tf_mla_expand_v_128(const __nv_bfloat16* ol, const __nv_bfloat16* wv, __nv_bfloat16* out, int64_t rows, diff --git a/zig/src/core/contract/mla_cuda_records.zig b/zig/src/core/contract/mla_cuda_records.zig index 7029988e117..6f627999f09 100644 --- a/zig/src/core/contract/mla_cuda_records.zig +++ b/zig/src/core/contract/mla_cuda_records.zig @@ -7,6 +7,7 @@ pub const records = [_]registry.CudaRecord{ .{ .launch = .{ .name = "mla tf_mla_chunks_split_r16", .symbol = "tf_mla_chunks_split_r16", .image = "mla", .threads = 256, .dynamic = 93568, .opt_in = true, .min_sm = 80 }, .usage = .{ .{ .regs = 74, .static = 0, .bound = 256 }, .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 119, .static = 0, .bound = 256 }, .{ .regs = 119, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "mla tf_mla_merge_part", .symbol = "tf_mla_merge_part", .image = "mla", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 0, .bound = 128 }, .{ .regs = 31, .static = 0, .bound = 128 }, .{ .regs = 31, .static = 0, .bound = 128 }, .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 32, .static = 0, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "mla tf_mla_absorb_q_128", .symbol = "tf_mla_absorb_q_128", .image = "mla", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 56, .static = 512, .bound = 128 }, .{ .regs = 56, .static = 512, .bound = 128 }, .{ .regs = 56, .static = 512, .bound = 128 }, .{ .regs = 56, .static = 512, .bound = 128 }, .{ .regs = 56, .static = 512, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "mla tf_mla_absorb_q_192", .symbol = "tf_mla_absorb_q_192", .image = "mla", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 72, .static = 512, .bound = 128 }, .{ .regs = 72, .static = 512, .bound = 128 }, .{ .regs = 72, .static = 512, .bound = 128 }, .{ .regs = 72, .static = 512, .bound = 128 }, .{ .regs = 72, .static = 512, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "mla tf_mla_expand_v_128", .symbol = "tf_mla_expand_v_128", .image = "mla", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 96, .static = 128, .bound = 128 }, .{ .regs = 96, .static = 128, .bound = 128 }, .{ .regs = 96, .static = 128, .bound = 128 }, .{ .regs = 95, .static = 128, .bound = 128 }, .{ .regs = 95, .static = 128, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "mla tf_mla_rope", .symbol = "tf_mla_rope", .image = "mla", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 26, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 } }, .later_pending = true }, .{ .launch = .{ .name = "mla tf_mla_gate", .symbol = "tf_mla_gate", .image = "mla", .threads = 128 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 } }, .later_pending = true }, diff --git a/zig/src/cuda/mla.zig b/zig/src/cuda/mla.zig index db62e51dcfc..7b8ec056dff 100644 --- a/zig/src/cuda/mla.zig +++ b/zig/src/cuda/mla.zig @@ -1,4 +1,4 @@ -//! mla.cu: MLA over a 512-wide latent with 64 roped columns and 128-wide heads (Ling-3.1), on GLM's chunk bodies. +//! mla.cu: MLA over a 512-wide latent with 64 roped columns (Ling-3.1's 128-wide heads), on GLM's chunk bodies. const std = @import("std"); const kernels = @import("kernels.zig"); const module = @import("module.zig"); @@ -15,6 +15,8 @@ const Args = launch_.Args; pub const latent_width = 512; pub const head_width = 128; pub const rope_width = 64; +/// Full GLM-5.3's q_nope heads, which the absorb also takes (GLM's latent path: a q head of 192 + 64 columns). +pub const glm_nope = 192; /// Heads a chunk block takes (the r16 form). pub const heads_tile = 16; /// Absorb and expand: rows from prompt_rows on go prompt_rb a block (as GLM's latent), fewer rows in one block. @@ -29,6 +31,9 @@ pub fn geometry(kv_lora: usize, nope: usize, v_dim: usize, rope_dim: usize) erro /// Online-softmax partials a chunk writes: o [nch][rows][heads][512] fp32, m and l [nch][rows][heads] fp32. pub const Partials = struct { po: u64, pm: u64, pl: u64 }; +/// Where chunksOn's keys come from: a page table and step, or (sparse) token lists `w` wide and their counts. +pub const On = struct { pt: u64 = 0, ps: usize = 0, tokens: u64 = 0, counts: u64 = 0, w: usize = 0, sparse: bool = false }; + /// The 64 roped columns of `heads` heads a row: in at x + r x_row + h x_head, out likewise (bf16 elements). pub const RopeRows = struct { x: u64, x_row: usize, x_head: usize, out: u64, o_row: usize, o_head: usize }; @@ -62,6 +67,7 @@ pub const Mla = struct { chunks_split_fn: Function, merge_part_fn: Function, absorb_q_fn: Function, + absorb_q_192_fn: Function, expand_v_fn: Function, rope_fn: Function, gate_fn: Function, @@ -76,6 +82,7 @@ pub const Mla = struct { .chunks_split_fn = try mod.function("tf_mla_chunks_split_r16"), .merge_part_fn = try mod.function("tf_mla_merge_part"), .absorb_q_fn = try mod.function("tf_mla_absorb_q_128"), + .absorb_q_192_fn = try mod.function("tf_mla_absorb_q_192"), .expand_v_fn = try mod.function("tf_mla_expand_v_128"), .rope_fn = try mod.function("tf_mla_rope"), .gate_fn = try mod.function("tf_mla_gate"), @@ -97,11 +104,16 @@ pub const Mla = struct { try launch_.launch(f, .{ .grid = .{ .x = @intCast(heads), .y = @intCast(cols), .z = cdiv(rows, rb) }, .block = .{ .x = 128 } }, s, &a); } - /// The absorb: q_nope the first d = 128 of each head's `q_stride` columns, out rows `out_stride` apart per head. + /// The absorb: q_nope the first d (128, or GLM's 192) of each head's `q_stride` columns, out `out_stride` apart. pub fn absorbQ(m: *const Mla, s: Stream, q: u64, q_stride: usize, wk: u64, out: u64, out_stride: usize, rows: usize, heads: usize, d: usize, lw: usize) !void { - if (d != head_width or lw != latent_width or q_stride < d or out_stride < lw) return error.LatentShape; + const f = switch (d) { + head_width => m.absorb_q_fn, + glm_nope => m.absorb_q_192_fn, + else => return error.LatentShape, + }; + if (lw != latent_width or q_stride < d or out_stride < lw) return error.LatentShape; if (rows == 0) return; - try rowBlocks(m.absorb_q_fn, s, q, wk, out, rows, heads, lw / 32, .{ i64of(q_stride), i64of(out_stride) }); + try rowBlocks(f, s, q, wk, out, rows, heads, lw / 32, .{ i64of(q_stride), i64of(out_stride) }); } /// out [rows][heads][dv] bf16 = o_lat [rows][heads][lw] . wv [heads][dv][lw], 128-wide v heads. @@ -121,9 +133,14 @@ pub const Mla = struct { /// The chunk tiles with roped keys: qa and cache rows lw + 64 wide, 16-head blocks, nch chunks' partials into `p`. pub fn chunks(m: *const Mla, s: Stream, qa: u64, cache: u64, pos: u64, p: Partials, rows: usize, heads: usize, nch: usize, scale: f32) !void { + try m.chunksOn(s, qa, cache, pos, .{}, p, rows, heads, nch, scale); + } + + /// GLM's chunk tiles: keys on 512-row pages (pt 0: in order) or each row's `counts` of `tokens`; Ling's: neither. + pub fn chunksOn(m: *const Mla, s: Stream, qa: u64, cache: u64, pos: u64, on: On, p: Partials, rows: usize, heads: usize, nch: usize, scale: f32) !void { if (rows == 0 or nch == 0) return; var a: Args = .{}; - inline for (.{ qa, cache, pos, @as(u64, 0), @as(u64, 0), p.po, p.pm, p.pl, i64of(rows), i64of(heads), @as(i64, 0), scale, @as(c_int, 0), @as(u64, 0), @as(i64, 0) }) |v| a.add(v); + inline for (.{ qa, cache, pos, on.tokens, on.counts, p.po, p.pm, p.pl, i64of(rows), i64of(heads), i64of(on.w), scale, @as(c_int, @intFromBool(on.sparse)), on.pt, i64of(on.ps) }) |v| a.add(v); try launch_.launch(m.chunks_fn, .{ .grid = .{ .x = @intCast(rows), .y = cdiv(heads, heads_tile), .z = @intCast(nch) }, .block = .{ .x = 256 }, .shared = chunksSmem(heads_tile) }, s, &a); } diff --git a/zig/src/families/glm/cuda.zig b/zig/src/families/glm/cuda.zig index 588f1481ec9..850211acac4 100644 --- a/zig/src/families/glm/cuda.zig +++ b/zig/src/families/glm/cuda.zig @@ -50,6 +50,7 @@ test { _ = @import("cuda_formats_csf0_test.zig"); _ = @import("cuda_tile.zig"); _ = @import("cuda_kv8_test.zig"); + _ = @import("cuda_latent_test.zig"); _ = kv8_ref; _ = @import("cuda_prof.zig"); _ = @import("cuda_load_owner.zig"); diff --git a/zig/src/families/glm/cuda_dsa_block.zig b/zig/src/families/glm/cuda_dsa_block.zig index 4d52d0c0878..1b41b70308f 100644 --- a/zig/src/families/glm/cuda_dsa_block.zig +++ b/zig/src/families/glm/cuda_dsa_block.zig @@ -34,6 +34,23 @@ pub const Layer = struct { dims: usize, eps: f32, dense_limit: usize, // the largest context whose top-k selection keeps every visible key (Config.keyWidth) + rope: usize = 0, // qk_rope: roped dims past qk in a q head and past lw in a latent row (none on GLM-5.3-Flash) + rope_inv: u64 = 0, // their fp32 frequencies [rope / 2] on the device + + /// A latent cache row and an absorbed q row: the latent, then the roped key columns (512 or 576). + pub fn row(l: Layer) usize { + return l.lw + l.rope; + } + + /// A q head's columns from q_b: qk latent-path dims, then the roped ones. + pub fn qHead(l: Layer) usize { + return l.qk + l.rope; + } + + /// The softmax scale: 1 / sqrt(qk + rope), 1 / 16 on both. + pub fn scale(l: Layer) f32 { + return @floatCast(std.math.pow(f64, @floatFromInt(l.qHead()), -0.5)); + } }; /// The caches: latent bf16 [capacity][lw], index keys/gates bf16 [capacity][128], pooled keys bf16 [pk_rows][128]. @@ -51,16 +68,16 @@ pub const Caches = struct { /// The block's scratch for up to `rows` rows. pub const Scratch = struct { - dp: u64, // bf16 [rows][q_lora + lw] + dp: u64, // bf16 [rows][q_lora + row] qr: u64, // bf16 [rows][q_lora] xs_qr: u64, // fp32 [rows][q_lora / 64] - lat: u64, // bf16 [rows][lw] + lat: u64, // bf16 [rows][row]: the normed latent, then the roped key xs_lat: u64, // fp32 [rows][lw / 64] - q: u64, // bf16 [rows][heads qk] + q: u64, // bf16 [rows][heads qHead] ikr: u64, // bf16 [rows][160] igr: u64, // fp32 [rows][128] router_part: u64, // fp32 [router_ks][rows][128] - qa: u64, // bf16 [rows][heads][lw] + qa: u64, // bf16 [rows][heads][row]: the absorbed q, then the roped q ol: u64, // bf16 [rows][heads][lw] vn: u64, // bf16 [rows][heads dv] qi: u64, // bf16 [rows][index heads d] @@ -109,18 +126,18 @@ pub fn prepare(set: glue.Set, stream: cuda.Stream, l: Layer, s: Scratch, x: u64, pub fn prepareProfile(set: glue.Set, stream: cuda.Stream, l: Layer, s: Scratch, x: u64, x_stride: usize, rows: usize, qi: bool, profile: ?*prof.Prof) !void { var stamp = prof.span(profile, stream, .replicated_qakva); - const width = l.q_lora + l.lw; + const width = l.q_lora + l.row(); try projection.matmul(set, stream, l.proj, x, x_stride, s.dp, s.mm_part, rows, width, l.dims, false); try glue.rmsnorm(set, stream, s.dp, width, l.q_norm, s.qr, l.q_lora, s.xs_qr, l.eps, rows, l.q_lora); - try glue.rmsnorm(set, stream, s.dp + l.q_lora * 2, width, l.kv_norm, s.lat, l.lw, s.xs_lat, l.eps, rows, l.lw); + try glue.rmsnorm(set, stream, s.dp + l.q_lora * 2, width, l.kv_norm, s.lat, l.row(), s.xs_lat, l.eps, rows, l.lw); stamp.end(); stamp = prof.span(profile, stream, .projections); defer stamp.end(); - try projection.matmul(set, stream, l.q_b, s.qr, l.q_lora, s.q, s.mm_part, rows, l.heads * l.qk, l.q_lora, false); + try projection.matmul(set, stream, l.q_b, s.qr, l.q_lora, s.q, s.mm_part, rows, l.heads * l.qHead(), l.q_lora, false); const ix = l.index; try projection.matmul(set, stream, ix.kw, x, x_stride, s.ikr, s.mm_part, rows, ix.d + ix.heads, l.dims, false); try glue.router(set, stream, x, x_stride, ix.gate, s.igr, s.router_part, rows, l.dims, ix.d); - try latent.absorbQ(set, stream, s.q, l.wk, s.qa, rows, l.heads, l.qk, l.lw); + try latent.absorbQ(set, stream, s.q, l.wk, s.qa, rows, l.heads, l.qk, l.rope, l.lw); if (qi) try projection.matmul(set, stream, ix.qb, s.qr, l.q_lora, s.qi, s.mm_part, rows, ix.heads * ix.d, l.q_lora, false); } @@ -130,15 +147,18 @@ pub fn attend(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, const ix = l.index; const kw_rows = ix.d + ix.heads; var v = s; // the scratch from row r0 - v.lat += r0 * l.lw * 2; + v.dp += r0 * (l.q_lora + l.row()) * 2; + v.lat += r0 * l.row() * 2; v.ikr += r0 * kw_rows * 2; v.igr += r0 * ix.d * 4; - v.qa += r0 * l.heads * l.lw * 2; + v.q += r0 * l.heads * l.qHead() * 2; + v.qa += r0 * l.heads * l.row() * 2; v.ol += r0 * l.heads * l.lw * 2; v.qi += r0 * ix.heads * ix.d * 2; try writeKeys(k, stream, l, c, v, rows, pos); + try ropeQueries(set, stream, l, v, rows, pos); const t, const tk = try tables(l, c); - const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(l.qk), -0.5)); + const scale = l.scale(); if (host_pos < l.dense_limit) { const stamp = prof.span(k.prof, stream, .mla); var dc = c; @@ -154,9 +174,9 @@ pub fn attend(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, defer stamp.end(); if (c.pks != 0) if (kv_host.active) |*g| { // host rows: gather the picks into device slots, attend there const slots = try g.gather(k.ops, stream, ix.gate, c.lc, c.pt, t.page_rows, pos, v.tokens, v.counts, rows, ix.geom.width()); - return latent.sparseAttentionFormat(set, stream, v.qa, slots, 0, .{}, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, rows, l.heads, l.lw, scale); + return latent.sparseAttentionFormat(set, stream, v.qa, slots, 0, .{}, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, rows, l.heads, l.row(), scale); }; - try latent.sparseAttentionFormat(set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, rows, l.heads, l.lw, scale); + try latent.sparseAttentionFormat(set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, rows, l.heads, l.row(), scale); } } @@ -168,7 +188,7 @@ pub fn blockLastRow(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scr const kw_rows = ix.d + ix.heads; try prepareProfile(k.set, stream, l, s, x, x_stride, rows, sparseRows(l, host_pos, rows), k.prof); // every row keeps its query, its latent, its keys var stamp = prof.span(k.prof, stream, .cache_write); - try latent.latentWriteFormat(k.set, stream, s.lat, l.lw, c.lc, c.ls, t, pos, rows, l.lw); // all rows, at pos, before any of them attends + try writeLatent(k.set, stream, l, c, s, t, pos, rows); // all rows, at pos, before any of them attends stamp.end(); stamp = prof.span(k.prof, stream, .index_update); try sparse.indexUpdate(k.set, stream, s.ikr, kw_rows, s.igr, ix.ln_w, ix.ln_b, ix.ape, c.ik, c.ig, c.pk, tk, pos, rows, ix.geom); @@ -186,7 +206,8 @@ fn attendLastRow(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratc const ix = l.index; const r0 = rows - 1; var v = s; // the scratch from the last row (its token lists and partials stay at the front) - v.qa += r0 * l.heads * l.lw * 2; + v.q += r0 * l.heads * l.qHead() * 2; + v.qa += r0 * l.heads * l.row() * 2; v.ol += r0 * l.heads * l.lw * 2; v.qi += r0 * ix.heads * ix.d * 2; var at = pos; // the last row's own position on the device: pos + r0, so its causal limit is unchanged @@ -198,10 +219,11 @@ fn attendLastRow(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratc try cuda_pdl.launch(try k.ops.function("tf_glm_add_i32"), .{ .grid = .{ .x = 1 }, .block = .{ .x = 32 } }, stream, &a); at = v.at; } - const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(l.qk), -0.5)); + try ropeQueries(k.set, stream, l, v, 1, at); + const scale = l.scale(); if (host_pos < l.dense_limit) { // the same keys today's whole-chunk call read for this row var stamp = prof.span(k.prof, stream, .mla); - try latent.attentionFormat(k.set, stream, v.qa, c.lc, c.ls, .{ .pt = c.pt, .ps = c.ps }, at, v.partials, v.ol, v.dummy, 1, l.heads, l.lw, nch, scale, latent.headBlock(rows)); + try latent.attentionFormat(k.set, stream, v.qa, c.lc, c.ls, .{ .pt = c.pt, .ps = c.ps }, at, v.partials, v.ol, v.dummy, 1, l.heads, l.row(), nch, scale, latent.headBlockFor(rows, l.row())); stamp.end(); } if (sparseRows(l, host_pos, rows)) { @@ -209,13 +231,13 @@ fn attendLastRow(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratc try sparse.selectTokensProfile(k.set, k.ops, stream, v.qi, s.ikr + r0 * (ix.d + ix.heads) * 2 + ix.d * 2, ix.d + ix.heads, c.pk, tk, at, host_pos + r0, 1, ix.heads, ix.d, ix.geom, c.pk_rows - 2, v.select, v.tokens, v.counts, null, k.prof); var stamp = prof.span(k.prof, stream, .mla); defer stamp.end(); - try latent.sparseAttentionFormat(k.set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, 1, l.heads, l.lw, scale); + try latent.sparseAttentionFormat(k.set, stream, v.qa, c.lc, c.ls, t, v.tokens, v.counts, ix.geom.width(), v.partials, v.ol, 1, l.heads, l.row(), scale); } } /// forward.dense_attention: latent.attention in `part_rows`-row blocks, each at its first row's position. fn denseAttention(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, pos: u64, rows: usize, nch: usize, part_rows: usize, scale: f32) !void { - const hb = latent.headBlock(rows); + const hb = latent.headBlockFor(rows, l.row()); var r0: usize = 0; while (r0 < rows) : (r0 += part_rows) { const n = @min(part_rows, rows - r0); @@ -228,15 +250,16 @@ fn denseAttention(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scrat try cuda_pdl.launch(try k.ops.function("tf_glm_add_i32"), .{ .grid = .{ .x = 1 }, .block = .{ .x = 32 } }, stream, &a); at = s.at; } - const off = r0 * l.heads * l.lw * 2; - try latent.attentionFormat(k.set, stream, s.qa + off, c.lc, c.ls, .{ .pt = c.pt, .ps = c.ps }, at, s.partials, s.ol + off, s.dummy, n, l.heads, l.lw, nch, scale, hb); + const qa = s.qa + r0 * l.heads * l.row() * 2; + try latent.attentionFormat(k.set, stream, qa, c.lc, c.ls, .{ .pt = c.pt, .ps = c.ps }, at, s.partials, s.ol + r0 * l.heads * l.lw * 2, s.dummy, n, l.heads, l.row(), nch, scale, hb); } } /// A cache's tables: latent rows `t`, and pooled keys `tk` (on their own device pages under TF_GLM_KV_HOST). fn tables(l: Layer, c: Caches) !struct { latent.Table, latent.Table } { - if (c.ps % (l.lw * 2) != 0) return error.LatentShape; // pages whole latent rows apart (the token lists' unit) - const t: latent.Table = .{ .pt = c.pt, .ps = c.ps, .page_rows = c.ps / (l.lw * 2) }; + const rb = l.row() * 2; + if (c.ps % rb != 0) return error.LatentShape; // pages whole latent rows apart (the token lists' unit) + const t: latent.Table = .{ .pt = c.pt, .ps = c.ps, .page_rows = c.ps / rb }; return .{ t, .{ .pt = c.pt, .ps = if (c.pks != 0) c.pks else c.ps, .page_rows = t.page_rows } }; } @@ -246,13 +269,29 @@ fn writeKeys(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, r const kw_rows = ix.d + ix.heads; const t, const tk = try tables(l, c); var stamp = prof.span(k.prof, stream, .cache_write); - try latent.latentWriteFormat(set, stream, s.lat, l.lw, c.lc, c.ls, t, pos, rows, l.lw); + try writeLatent(set, stream, l, c, s, t, pos, rows); stamp.end(); stamp = prof.span(k.prof, stream, .index_update); try sparse.indexUpdate(set, stream, s.ikr, kw_rows, s.igr, ix.ln_w, ix.ln_b, ix.ape, c.ik, c.ig, c.pk, tk, pos, rows, ix.geom); stamp.end(); } +/// The latent rows into the cache at pos; a roped row's key columns roped first (k_pe from dp, at pos + r). +fn writeLatent(set: glue.Set, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, t: latent.Table, pos: u64, rows: usize) !void { + if (l.rope != 0) { + const kpe: latent.RopeRows = .{ .x = s.dp + (l.q_lora + l.lw) * 2, .x_row = l.q_lora + l.row(), .x_head = 0, .out = s.lat + l.lw * 2, .o_row = l.row(), .o_head = 0 }; + try latent.rope(set, stream, kpe, rows, 1, pos, l.rope_inv); + } + try latent.latentWriteFormat(set, stream, s.lat, l.row(), c.lc, c.ls, t, pos, rows, l.row()); +} + +/// A roped row's queries: each head's rope dims of q (past qk) roped at pos + r into qa past the latent. +fn ropeQueries(set: glue.Set, stream: cuda.Stream, l: Layer, s: Scratch, rows: usize, pos: u64) !void { + if (l.rope == 0) return; + const q: latent.RopeRows = .{ .x = s.q + l.qk * 2, .x_row = l.heads * l.qHead(), .x_head = l.qHead(), .out = s.qa + l.lw * 2, .o_row = l.heads * l.row(), .o_head = l.row() }; + try latent.rope(set, stream, q, rows, l.heads, pos, l.rope_inv); +} + /// The existing row projections and cache writes, without attention or output projections. pub fn commit(k: Kernels, stream: cuda.Stream, l: Layer, c: Caches, s: Scratch, x: u64, stride: usize, rows: usize, pos: u64, host_pos: usize) !void { try prepareProfile(k.set, stream, l, s, x, stride, rows, sparseRows(l, host_pos, rows), k.prof); diff --git a/zig/src/families/glm/cuda_engine.zig b/zig/src/families/glm/cuda_engine.zig index 86e3453b9e4..c8e944693dc 100644 --- a/zig/src/families/glm/cuda_engine.zig +++ b/zig/src/families/glm/cuda_engine.zig @@ -157,7 +157,7 @@ pub const Engine = struct { errdefer gpa.free(spans); for (spans, 0..) |*sp, q| sp.* = (try shard.Share.of(&c, q, world)).vocab; const block32 = if (exl3.isExl3(gpa, text)) null else try @import("cuda_experts.zig").wantsBlock32(gpa, text); - var m = try fw.Modules.load(d, ctx, block32); + var m = try fw.Modules.load(d, ctx, block32, c.rope != 0); errdefer m.deinit(); const pair = prompt_pair.wanted(o.settings.pair, o.settings.solo, world); var pieces = try fw.Pieces.init(d, o.settings.pieces, pair); diff --git a/zig/src/families/glm/cuda_forward.zig b/zig/src/families/glm/cuda_forward.zig index 27af7e78e80..c31bf91f458 100644 --- a/zig/src/families/glm/cuda_forward.zig +++ b/zig/src/families/glm/cuda_forward.zig @@ -55,9 +55,10 @@ pub const Modules = struct { pack_dense: cuda.Function, quant: quant.Kernels, q4: q4.Kernels, + mla: ?cuda.mla.Mla, // `roped` (Config.rope: full GLM-5.3's 576-wide latent rows): the roped MLA image /// `block32`: a csf0_v1 checkpoint's block 32 experts' image too, for its codes' values (experts.wantsBlock32). - pub fn load(d: *const cuda.Driver, ctx: *const cuda.Context, block32: ?cuda.experts32.Values) !Modules { + pub fn load(d: *const cuda.Driver, ctx: *const cuda.Context, block32: ?cuda.experts32.Values, roped: bool) !Modules { try cuda_pdl.bind(ctx); const k = cuda.kernels; var m: Modules = undefined; @@ -85,6 +86,8 @@ pub const Modules = struct { m.exl3 = try exl3.Kernels.load(d); errdefer m.exl3.unload(); m.mm = try mm_mod.Kernels.load(m.mods[7]); + m.mla = if (roped) try cuda.mla.Mla.load(d) else null; + errdefer if (m.mla) |*x| x.unload(); m.index = null; errdefer if (m.index) |*x| x.unload(); const mode = index_mod.Mode.read() catch return error.BadIndexSetting; @@ -119,6 +122,7 @@ pub const Modules = struct { pub fn deinit(m: *Modules) void { if (m.index) |*x| x.unload(); if (m.dscore) |*x| x.unload(); + if (m.mla) |*x| x.unload(); m.exl3.unload(); for (&m.mods) |*x| x.unload(); m.lane.unload(); @@ -177,7 +181,7 @@ pub const Forward = struct { } pub fn set(f: *const Forward) glue.Set { - return .{ .glue = &f.m.glue, .index = if (f.m.index) |*x| x else null, .mm = if (f.m.tiled) &f.m.mm else null, .packs = f.m.packs, .prompt = f.ranks[0].b.prefill, .linear = .{ .lane = &f.m.lane }, .copy_rows = f.m.copy_rows, .dsel = f.m.dsel, .dscore = if (f.m.dscore) |*x| x else null }; + return .{ .glue = &f.m.glue, .index = if (f.m.index) |*x| x else null, .mm = if (f.m.tiled) &f.m.mm else null, .packs = f.m.packs, .prompt = f.ranks[0].b.prefill, .linear = .{ .lane = &f.m.lane }, .copy_rows = f.m.copy_rows, .dsel = f.m.dsel, .dscore = if (f.m.dscore) |*x| x else null, .mla = if (f.m.mla) |*x| x else null }; } /// The layer sums' boundary (cuda_boundary.zig): every rank's fp32 partial into every gathered buffer. diff --git a/zig/src/families/glm/cuda_glue.zig b/zig/src/families/glm/cuda_glue.zig index 631d570dcd1..a724d161bbe 100644 --- a/zig/src/families/glm/cuda_glue.zig +++ b/zig/src/families/glm/cuda_glue.zig @@ -19,6 +19,8 @@ pub const Set = struct { dsel: bool = false, /// A decode window's index scores on glm_index_scores (TF_GLM_DSCORES; null keeps tf_glm_scores). dscore: ?*const index_mod.Kernels = null, + /// Full GLM-5.3's roped latent rows (576): cuda.mla's absorb, rope and 16-head chunk tiles; GLM-5.3-Flash: none. + mla: ?*const cuda.mla.Mla = null, }; /// A hidden-size norm's weight: bf16, or float32 (FP4-Local's) read as float32 by the _f32w kernels. diff --git a/zig/src/families/glm/cuda_latent.zig b/zig/src/families/glm/cuda_latent.zig index 82e40283881..c79cc58f25b 100644 --- a/zig/src/families/glm/cuda_latent.zig +++ b/zig/src/families/glm/cuda_latent.zig @@ -1,4 +1,4 @@ -//! GLM-5.3-Flash's MLA on the 512-wide latent cache (DSA layers): the Python family's latent on BF16, row by row. +//! GLM's MLA on the latent cache (DSA layers), BF16 row by row: 512 wide, or 576 with full GLM-5.3's roped key columns. const std = @import("std"); const cuda = @import("cuda"); @@ -18,6 +18,30 @@ pub fn headBlock(rows: usize) usize { return if (rows >= 64) heads_tile_wide else heads_tile; } +/// The latent's width, and the roped key columns a full GLM-5.3 row carries past it (cuda.mla's). +pub const latent_width = 512; +pub const rope_width = cuda.mla.rope_width; +pub const roped_row = latent_width + rope_width; + +/// headBlock for rows `row` wide: roped rows keep 16 heads, as wide_smem<32, 64>() is past a block's shared memory. +pub fn headBlockFor(rows: usize, row: usize) usize { + return if (row == roped_row) heads_tile else headBlock(rows); +} + +/// The roped key columns of a q and key row: none at 512 (GLM-5.3-Flash), 64 at 576 (full GLM-5.3). +fn ropeOf(row: usize) !usize { + return switch (row) { + latent_width => 0, + roped_row => rope_width, + else => error.LatentShape, + }; +} + +/// The roped image a roped row's call takes. +fn roped(set: glue.Set) !*const cuda.mla.Mla { + return set.mla orelse error.NoRopedKernels; +} + /// latent.chunks_for: 512-key chunks to cover `length` keys. pub fn chunksFor(length: usize) usize { return (length + chunk - 1) / chunk; @@ -27,12 +51,25 @@ fn cdiv(a: usize, b: usize) u32 { return @intCast((a + b - 1) / b); } -/// latent.absorb_q (BF16 kv_b): out [rows][heads][lw] bf16 = q [rows][heads][d] . wk [heads][d][lw], fp32 sums. -pub fn absorbQ(set: glue.Set, stream: cuda.Stream, q: u64, wk: u64, out: u64, rows: usize, heads: usize, d: usize, lw: usize) !void { +/// latent.absorb_q (BF16 kv_b): out [rows][heads][lw + rd] = q [rows][heads][d + rd] . wk, fp32; rd roped columns. +pub fn absorbQ(set: glue.Set, stream: cuda.Stream, q: u64, wk: u64, out: u64, rows: usize, heads: usize, d: usize, rd: usize, lw: usize) !void { + if (rd != 0) { + if (rd != rope_width or d != cuda.mla.glm_nope) return error.LatentShape; + return (try roped(set)).absorbQ(stream, q, d + rd, wk, out, lw + rd, rows, heads, d, lw); + } if (d != 256 or lw != 512) return error.LatentShape; try rowBlocks(set.glue.absorb_q, stream, q, wk, out, rows, heads, lw / 32); } +/// Where rope turns a row's 64 columns: from x + r x_row + h x_head into out + r o_row + h o_head (bf16 elements). +pub const RopeRows = cuda.mla.RopeRows; + +/// The GPT-J pairs of `heads` heads a row at device i32 pos + r, fp32 frequencies `inv` [32] (no YaRN factor). +pub fn rope(set: glue.Set, stream: cuda.Stream, v: RopeRows, rows: usize, heads: usize, pos: u64, inv: u64) !void { + if (inv == 0) return error.NoRopeFreqs; + try (try roped(set)).rope(stream, v, rows, heads, pos, inv, 1); +} + /// The absorb and expand launches: rows in one block in decode windows, prompt_rb a block in prompt chunks. fn rowBlocks(f: cuda.Function, stream: cuda.Stream, in: u64, w: u64, out: u64, rows: usize, heads: usize, cols: usize) !void { const rb = if (rows >= prompt_rows) prompt_rb else rows; @@ -74,7 +111,7 @@ pub fn latentWrite(set: glue.Set, stream: cuda.Stream, lat: u64, lat_stride: usi try cuda_pdl.launch(set.glue.lat_write, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 128 } }, stream, &a); } -/// The chunk partials of one attention call: po fp32 [nch][rows][heads][lw], pm and pl fp32 [nch][rows][heads]. +/// The chunk partials of one attention call: po fp32 [nch][rows][heads][512], pm and pl fp32 [nch][rows][heads]. pub const Partials = struct { po: u64, pm: u64, pl: u64 }; /// latent.attention: causal qa over the cache in `nch` 512-key chunks into out bf16; `dummy`: the merge's count i32. @@ -87,10 +124,16 @@ pub fn attentionFormat(set: glue.Set, stream: cuda.Stream, qa: u64, cache: u64, try merge(set, stream, p, out, dummy, rows, heads, lw, nch, false); } -/// latent._dense_chunks (sparse false: keys through pos + r) and _sparse_chunks (row r's `counts` tokens of `tokens`). +/// latent._dense_chunks (keys through pos + r) and _sparse_chunks (row r's `counts` of `tokens`); `lw` 512 or 576. fn chunks(set: glue.Set, stream: cuda.Stream, qa: u64, cache: u64, scales: u64, t: Table, pos: u64, tokens: u64, counts: u64, p: Partials, rows: usize, heads: usize, lw: usize, nch: usize, w: usize, scale: f32, hb: usize, sparse: bool) !void { - if (lw != 512) return error.LatentShape; + const rope_cols = try ropeOf(lw); if (scales != 0 and t.pt != 0) return error.Fp8OnPages; + if (rope_cols != 0) { + if (scales != 0) return error.LatentShape; // the E4M3 cache holds the latent alone + if (hb != heads_tile) return error.HeadBlock; + const on: cuda.mla.On = .{ .pt = t.pt, .ps = t.ps, .tokens = tokens, .counts = counts, .w = w, .sparse = sparse }; + return (try roped(set)).chunksOn(stream, qa, cache, pos, on, .{ .po = p.po, .pm = p.pm, .pl = p.pl }, rows, heads, nch, scale); + } const f = switch (hb) { heads_tile => if (scales == 0) set.glue.chunks_16 else set.glue.chunks_16_fp8, heads_tile_wide => if (scales == 0) set.glue.chunks_32 else set.glue.chunks_32_fp8, @@ -116,12 +159,13 @@ pub fn sparseAttention(set: glue.Set, stream: cuda.Stream, qa: u64, cache: u64, pub fn sparseAttentionFormat(set: glue.Set, stream: cuda.Stream, qa: u64, cache: u64, scales: u64, t: Table, tokens: u64, counts: u64, w: usize, p: Partials, out: u64, rows: usize, heads: usize, lw: usize, scale: f32) !void { const nch = chunksFor(w); - try chunks(set, stream, qa, cache, scales, t, 0, tokens, counts, p, rows, heads, lw, nch, w, scale, headBlock(rows), true); + try chunks(set, stream, qa, cache, scales, t, 0, tokens, counts, p, rows, heads, lw, nch, w, scale, headBlockFor(rows, lw), true); try merge(set, stream, p, out, counts, rows, heads, lw, nch, true); } +/// The partials and out hold the latent alone (the roped columns score, the values are the latent's). fn merge(set: glue.Set, stream: cuda.Stream, p: Partials, out: u64, counts: u64, rows: usize, heads: usize, lw: usize, nch: usize, sparse: bool) !void { - if (lw != 512) return error.LatentShape; + _ = try ropeOf(lw); var a: cuda.Args = .{}; inline for (.{ p.po, p.pm, p.pl, out, counts, @as(i64, @intCast(rows)), @as(i64, @intCast(heads)), @as(c_int, @intCast(nch)), @as(c_int, @intFromBool(sparse)) }) |v| a.add(v); try cuda_pdl.launch(set.glue.merge, .{ .grid = .{ .x = @intCast(rows), .y = @intCast(heads) }, .block = .{ .x = 128 } }, stream, &a); diff --git a/zig/src/families/glm/cuda_latent_test.zig b/zig/src/families/glm/cuda_latent_test.zig new file mode 100644 index 00000000000..90ce221f6cb --- /dev/null +++ b/zig/src/families/glm/cuda_latent_test.zig @@ -0,0 +1,263 @@ +//! GLM's latent path launches at GLM-5.3-Flash's 512-wide rows and full GLM-5.3's 576 (cuda.mla's roped image). + +const std = @import("std"); +const cuda = @import("cuda"); +const glue = @import("cuda_glue.zig"); +const latent = @import("cuda_latent.zig"); +const dsa = @import("cuda_dsa_block.zig"); +const state = @import("cuda_state.zig"); +const t = std.testing; + +/// One launch as the driver saw it: function, grid, block, dynamic shared bytes and the arguments' values. +const Seen = struct { id: usize, grid: [3]u32, block: u32, shared: u32, args: [16]u64 }; + +/// Argument sizes (8 or 4 bytes) of the launches whose values the tests read, by fake handle. +fn sizes(id: usize) []const u8 { + return switch (id) { + ids.chunks_16, ids.chunks_32, mla_ids.chunks => "888888888884488", + ids.merge => "888888844", + ids.lat_write => "8888888", + ids.absorb_q, ids.expand_v => "888888", + mla_ids.absorb_q_192, mla_ids.absorb_q => "88888888", + mla_ids.rope => "888888884", + ops_ids.dsa_tokens => "88488884", + else => "", + }; +} + +const Launch = struct { + var n: usize = 0; + var seen: [128]Seen = undefined; + + fn run(f: cuda.abi.Function, gx: c_uint, gy: c_uint, gz: c_uint, bx: c_uint, _: c_uint, _: c_uint, shared: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) c_int { + const id = @intFromPtr(f); + var s: Seen = .{ .id = id, .grid = .{ gx, gy, gz }, .block = bx, .shared = shared, .args = @splat(0) }; + for (sizes(id), 0..) |size, i| { + const at = args.?[i].?; + s.args[i] = if (size == '8') @as(*const u64, @ptrCast(@alignCast(at))).* else @as(*const u32, @ptrCast(@alignCast(at))).*; + } + seen[n] = s; + n += 1; + return 0; + } + + /// The launches of function `id`, in order. + fn of(id: usize, out: []Seen) []Seen { + var k: usize = 0; + for (seen[0..n]) |s| if (s.id == id) { + out[k] = s; + k += 1; + }; + return out[0..k]; + } +}; + +/// Fake handles: glue's kernels 1 .. in field order, cuda.mla's from 201, glm_ops' from 301. +const ids = struct { + const absorb_q = fieldId("absorb_q"); + const expand_v = fieldId("expand_v"); + const lat_write = fieldId("lat_write"); + const chunks_16 = fieldId("chunks_16"); + const chunks_32 = fieldId("chunks_32"); + const merge = fieldId("merge"); +}; +const mla_ids = struct { + const chunks = 201; + const absorb_q = 204; + const absorb_q_192 = 205; + const rope = 207; +}; +const ops_ids = struct { + const dsa_tokens = 301; +}; +const mla_fields = .{ "chunks_fn", "chunks_split_fn", "merge_part_fn", "absorb_q_fn", "absorb_q_192_fn", "expand_v_fn", "rope_fn", "gate_fn" }; + +fn fieldId(comptime name: []const u8) usize { + inline for (@typeInfo(glue.Kernels).@"struct".field_names, 1..) |f, i| if (comptime std.mem.eql(u8, f, name)) return i; + unreachable; +} + +const Ops = struct { + fn function(out: *cuda.abi.Function, _: cuda.abi.Module, name: [*:0]const u8) callconv(.c) c_int { + out.* = @ptrFromInt(if (std.mem.eql(u8, std.mem.span(name), "tf_glm_dsa_tokens")) @as(usize, ops_ids.dsa_tokens) else 302); + return 0; + } +}; + +const Fakes = struct { + d: cuda.Driver, + ks: glue.Kernels, + m: cuda.mla.Mla, + + fn init(f: *Fakes) void { + f.d = undefined; + f.d.api.cuLaunchKernel = Launch.run; + f.d.api.cuModuleGetFunction = Ops.function; + inline for (@typeInfo(glue.Kernels).@"struct".field_names, 1..) |name, i| @field(f.ks, name) = .{ .d = &f.d, .handle = @ptrFromInt(i) }; + f.m = undefined; + inline for (mla_fields, 201..) |name, i| @field(f.m, name) = .{ .d = &f.d, .handle = @ptrFromInt(i) }; + Launch.n = 0; + } + + fn stream(f: *Fakes) cuda.Stream { + return .{ .d = &f.d, .handle = null }; + } +}; + +fn args16(vals: []const u64) [16]u64 { + var a: [16]u64 = @splat(0); + @memcpy(a[0..vals.len], vals); + return a; +} + +const p: latent.Partials = .{ .po = 0x1000, .pm = 0x2000, .pl = 0x3000 }; +const flash_ps: u64 = 13056 * 512; // GLM-5.3-Flash's page: 12 caches +const full_ps: u64 = 79 * 1408 * 512 + 4096; // full GLM-5.3's: 79 caches, padded to whole 576-wide rows + +test "GLM latent: GLM-5.3-Flash's absorb, chunks and merge keep their kernels, grids, smem and arguments" { + var f: Fakes = undefined; + f.init(); + const set: glue.Set = .{ .glue = &f.ks }; + try latent.absorbQ(set, f.stream(), 0x10, 0x20, 0x30, 100, 32, 256, 0, 512); + try t.expectEqual(Seen{ .id = ids.absorb_q, .grid = .{ 32, 16, 2 }, .block = 128, .shared = 0, .args = args16(&.{ 0x10, 0x20, 0x30, 100, 32, 64 }) }, Launch.seen[0]); + try t.expectError(error.LatentShape, latent.absorbQ(set, f.stream(), 0x10, 0x20, 0x30, 3, 32, 192, 0, 512)); + for ([_]usize{ 16, 32 }, [_]usize{ ids.chunks_16, ids.chunks_32 }, [_]u32{ glue.chunksSmem(16), glue.chunksSmem(32) }) |hb, id, smem| { + Launch.n = 0; + try latent.attentionFormat(set, f.stream(), 0x40, 0x50, 0, .{ .pt = 0x60, .ps = flash_ps }, 0x70, p, 0x80, 0x90, 3, 32, 512, 2, 0.0625, hb); + try t.expectEqual(@as(usize, 2), Launch.n); + const c = Launch.seen[0]; + try t.expectEqual(id, c.id); + try t.expectEqual([3]u32{ 3, @intCast(32 / hb), 2 }, c.grid); + try t.expectEqual(smem, c.shared); + try t.expectEqualSlices(u64, &.{ 0x40, 0x50, 0x70, 0, 0, 0x1000, 0x2000, 0x3000, 3, 32, 0, @as(u32, @bitCast(@as(f32, 0.0625))), 0, 0x60, flash_ps }, c.args[0..15]); + try t.expectEqual(Seen{ .id = ids.merge, .grid = .{ 3, 32, 1 }, .block = 128, .shared = 0, .args = args16(&.{ 0x1000, 0x2000, 0x3000, 0x80, 0x90, 3, 32, 2, 0 }) }, Launch.seen[1]); + } + Launch.n = 0; + try latent.sparseAttention(set, f.stream(), 0x40, 0x50, .{}, 0xa0, 0xb0, 2051, p, 0x80, 64, 32, 512, 0.0625); + try t.expectEqual(ids.chunks_32, Launch.seen[0].id); // 64 rows: 32 heads a block + try t.expectEqual([3]u32{ 64, 1, 5 }, Launch.seen[0].grid); + try t.expectEqual(@as(u64, 1), Launch.seen[0].args[12]); +} + +test "GLM latent: full GLM-5.3's 576-wide rows take cuda.mla's absorb_q_192 and 16-head roped tiles, the same merge" { + var f: Fakes = undefined; + f.init(); + const set: glue.Set = .{ .glue = &f.ks, .mla = &f.m }; + try latent.absorbQ(set, f.stream(), 0x10, 0x20, 0x30, 3, 22, 192, 64, 512); + try t.expectEqual(Seen{ .id = mla_ids.absorb_q_192, .grid = .{ 22, 16, 1 }, .block = 128, .shared = 0, .args = args16(&.{ 0x10, 0x20, 0x30, 3, 22, 3, 256, 576 }) }, Launch.seen[0]); + try t.expectEqual(@as(usize, 1), Launch.n); + Launch.n = 0; + try latent.attentionFormat(set, f.stream(), 0x40, 0x50, 0, .{ .pt = 0x60, .ps = full_ps }, 0x70, p, 0x80, 0x90, 3, 22, latent.roped_row, 2, 0.0625, 16); + try t.expectEqual(@as(usize, 2), Launch.n); + const c = Launch.seen[0]; + try t.expectEqual(@as(usize, mla_ids.chunks), c.id); + try t.expectEqual([3]u32{ 3, 2, 2 }, c.grid); // 22 heads: two blocks of 16, the second guarded past 22 + try t.expectEqual(@as(u32, 256), c.block); + try t.expectEqual(cuda.mla.chunksSmem(16), c.shared); + try t.expectEqualSlices(u64, &.{ 0x40, 0x50, 0x70, 0, 0, 0x1000, 0x2000, 0x3000, 3, 22, 0, @as(u32, @bitCast(@as(f32, 0.0625))), 0, 0x60, full_ps }, c.args[0..15]); + try t.expectEqual(Seen{ .id = ids.merge, .grid = .{ 3, 22, 1 }, .block = 128, .shared = 0, .args = args16(&.{ 0x1000, 0x2000, 0x3000, 0x80, 0x90, 3, 22, 2, 0 }) }, Launch.seen[1]); + Launch.n = 0; + try latent.sparseAttention(set, f.stream(), 0x40, 0x50, .{ .pt = 0x60, .ps = full_ps, .page_rows = full_ps / 1152 }, 0xa0, 0xb0, 2048, p, 0x80, 64, 22, latent.roped_row, 0.0625); + const s = Launch.seen[0]; + try t.expectEqual(@as(usize, mla_ids.chunks), s.id); // 64 rows still 16 heads a block + try t.expectEqual([3]u32{ 64, 2, 4 }, s.grid); + try t.expectEqualSlices(u64, &.{ 0, 0xa0, 0xb0, 0x1000, 0x2000, 0x3000, 64, 22, 2048, @as(u32, @bitCast(@as(f32, 0.0625))), 1, 0x60, full_ps }, s.args[2..15]); + try t.expectEqual(@as(u64, 1), Launch.seen[1].args[8]); // the merge skips count-0 rows + Launch.n = 0; + try t.expectError(error.HeadBlock, latent.attentionFormat(set, f.stream(), 0x40, 0x50, 0, .{}, 0x70, p, 0x80, 0x90, 64, 22, latent.roped_row, 1, 0.0625, 32)); + try t.expectError(error.LatentShape, latent.attentionFormat(set, f.stream(), 0x40, 0x50, 0x55, .{}, 0x70, p, 0x80, 0x90, 3, 22, latent.roped_row, 1, 0.0625, 16)); + try t.expectError(error.LatentShape, latent.attentionFormat(set, f.stream(), 0x40, 0x50, 0, .{}, 0x70, p, 0x80, 0x90, 3, 22, 544, 1, 0.0625, 16)); + const flash_set: glue.Set = .{ .glue = &f.ks }; + try t.expectError(error.NoRopedKernels, latent.absorbQ(flash_set, f.stream(), 0x10, 0x20, 0x30, 3, 22, 192, 64, 512)); + try t.expectError(error.NoRopedKernels, latent.sparseAttention(flash_set, f.stream(), 0x40, 0x50, .{}, 0xa0, 0xb0, 2048, p, 0x80, 3, 22, latent.roped_row, 0.0625)); + try t.expectError(error.LatentShape, latent.absorbQ(set, f.stream(), 0x10, 0x20, 0x30, 3, 22, 256, 64, 512)); + try t.expectEqual(@as(usize, 0), Launch.n); +} + +test "GLM latent: roped rows keep 16 heads a block, as 32 would take 113,408 bytes of smem, past sm_86..121's 99 KiB" { + try t.expectEqual(@as(usize, 32), latent.headBlockFor(64, 512)); + try t.expectEqual(@as(usize, 16), latent.headBlockFor(8, 512)); + try t.expectEqual(@as(usize, 16), latent.headBlockFor(64, latent.roped_row)); + const wide32: u32 = (32 * 576 + 2 * 32 * 576 + 32 * 32) * 2 + (32 * 4 + 2 * 32) * 4; // common/mla.cuh's wide_smem<32, 64>() + try t.expectEqual(@as(u32, 113_408), wide32); + try t.expect(wide32 > 101_376 and cuda.mla.chunksSmem(16) <= 101_376); +} + +/// A rank's DSA layer at either shape, its indexer at GLM-5.3-Flash's pools of 4 or full GLM-5.3's every key. +fn layer(full: bool) dsa.Layer { + return .{ .proj = .{ .bf16 = 0 }, .q_norm = 0, .kv_norm = 0, .q_b = .{ .bf16 = 0 }, .wk = 0x11_0000, .wv = 0x12_0000, .o = .{ .bf16 = 0 }, .index = .{ .kw = .{ .bf16 = 0 }, .gate = 0, .ln_w = 0, .ln_b = 0, .ape = 0, .qb = .{ .bf16 = 0 }, .heads = 32, .d = 128, .geom = if (full) .{ .pool = 1, .topk = 2048 } else .{} }, .heads = if (full) 22 else 32, .qk = if (full) 192 else 256, .dv = 256, .lw = 512, .q_lora = if (full) 2048 else 1536, .dims = 6144, .eps = 1e-5, .dense_limit = 1 << 20, .rope = if (full) 64 else 0, .rope_inv = if (full) 0x13_0000 else 0 }; +} + +fn scratch() dsa.Scratch { + var s = std.mem.zeroes(dsa.Scratch); + s.dp = 0x100_0000; + s.lat = 0x200_0000; + s.q = 0x300_0000; + s.qa = 0x400_0000; + s.ol = 0x500_0000; + s.tokens = 0x600_0000; + s.counts = 0x610_0000; + s.partials = .{ .po = 0x700_0000, .pm = 0x710_0000, .pl = 0x720_0000 }; + s.dummy = 0x730_0000; + return s; +} + +test "GLM DSA block: a window's rows from r0 rope full GLM-5.3's keys and queries at 576 wide, GLM-5.3-Flash's none" { + var f: Fakes = undefined; + const r0 = 2; + const s = scratch(); + var got: [8]Seen = undefined; + for ([_]bool{ false, true }) |full| { + f.init(); + const k: dsa.Kernels = .{ .set = .{ .glue = &f.ks, .mla = if (full) &f.m else null }, .ops = .{ .d = &f.d, .handle = null } }; + const l = layer(full); + const c: dsa.Caches = .{ .lc = 0x800_0000, .ik = 0x810_0000, .ig = 0x820_0000, .pk = 0x830_0000, .pk_rows = 4098, .pt = 0x840_0000, .ps = if (full) full_ps else flash_ps }; + try dsa.attend(k, f.stream(), l, c, s, r0, 3, 0x850_0000, 5, 1, 3); + const row: u64 = if (full) 576 else 512; + const heads: u64 = l.heads; + try t.expectEqualSlices(u64, &.{ s.lat + r0 * row * 2, row, c.lc, 0x850_0000, row, c.pt, c.ps }, Launch.of(ids.lat_write, &got)[0].args[0..7]); + const ropes = Launch.of(mla_ids.rope, &got); + try t.expectEqual(@as(usize, if (full) 2 else 0), ropes.len); + if (full) { + const one: u64 = @as(u32, @bitCast(@as(f32, 1))); + const width: u64 = 2048 + 576; // dp: [q_a | kv_a] after the norms' reads, k_pe at 2048 + 512 + try t.expectEqual([3]u32{ 3, 1, 1 }, ropes[0].grid); + try t.expectEqualSlices(u64, &.{ s.dp + r0 * width * 2 + (2048 + 512) * 2, width, 0, s.lat + r0 * 576 * 2 + 512 * 2, 576, 0, 0x850_0000, 0x13_0000, one }, ropes[0].args[0..9]); + try t.expectEqual([3]u32{ 3, 22, 1 }, ropes[1].grid); + try t.expectEqual(@as(u32, 32), ropes[1].block); + try t.expectEqualSlices(u64, &.{ s.q + r0 * 22 * 256 * 2 + 192 * 2, 22 * 256, 256, s.qa + r0 * 22 * 576 * 2 + 512 * 2, 22 * 576, 576, 0x850_0000, 0x13_0000, one }, ropes[1].args[0..9]); + try t.expect(Launch.seen[0].id == mla_ids.rope); // the key's rope before its write + } + const chunk = Launch.of(if (full) mla_ids.chunks else ids.chunks_16, &got)[0]; + try t.expectEqual([3]u32{ 3, @intCast((heads + 15) / 16), 1 }, chunk.grid); + try t.expectEqualSlices(u64, &.{ s.qa + r0 * heads * row * 2, c.lc }, chunk.args[0..2]); + try t.expectEqual(@as(u64, @as(u32, @bitCast(@as(f32, 0.0625)))), chunk.args[11]); // 1 / sqrt(256) both + try t.expectEqual(s.ol + r0 * heads * 512 * 2, Launch.of(ids.merge, &got)[0].args[3]); + } + var l = layer(true); + l.rope_inv = 0; + f.init(); + const k: dsa.Kernels = .{ .set = .{ .glue = &f.ks, .mla = &f.m }, .ops = .{ .d = &f.d, .handle = null } }; + try t.expectError(error.NoRopeFreqs, dsa.attend(k, f.stream(), l, .{ .lc = 0, .ik = 0, .ig = 0, .pk = 0, .pk_rows = 0 }, s, 0, 3, 0x850_0000, 5, 1, 3)); +} + +test "GLM DSA block: token lists resolve pages to 576-wide rows on full GLM-5.3's padded page, Flash's 6,528 rows" { + for ([_]bool{ false, true }) |full| { + var f: Fakes = undefined; + f.init(); + var got: [8]Seen = undefined; + const k: dsa.Kernels = .{ .set = .{ .glue = &f.ks, .mla = if (full) &f.m else null }, .ops = .{ .d = &f.d, .handle = null } }; + var l = layer(full); + l.dense_limit = 1; // every row sparse + const c: dsa.Caches = .{ .lc = 0x800_0000, .ik = 0x810_0000, .ig = 0x820_0000, .pk = 0x830_0000, .pk_rows = 4098, .pt = 0x840_0000, .ps = if (full) full_ps else flash_ps }; + try dsa.attend(k, f.stream(), l, c, scratch(), 0, 3, 0x850_0000, 4096, 1, 3); + try t.expectEqual(@as(u64, if (full) 49_440 else 6_528), Launch.of(ops_ids.dsa_tokens, &got)[0].args[6]); + const chunk = Launch.of(if (full) mla_ids.chunks else ids.chunks_16, &got)[0]; + try t.expectEqual(@as(u32, if (full) 4 else 5), chunk.grid[2]); // 2,048 or 2,051 tokens a row + try t.expectEqual(@as(u64, 1), chunk.args[12]); + } + const flash = state.Shape.of(&@import("config.zig").Config{}, 12); + const full = state.Shape.of(&@import("config.zig").Config{ .rope = 64, .kpool = 1 }, 79); + try t.expectEqual(flash_ps, flash.pageBytes()); + try t.expectEqual(full_ps, full.pageBytes()); +} diff --git a/zig/src/families/glm/cuda_snapshot_layout_test.zig b/zig/src/families/glm/cuda_snapshot_layout_test.zig index becdf2a2a96..77b7faebe3f 100644 --- a/zig/src/families/glm/cuda_snapshot_layout_test.zig +++ b/zig/src/families/glm/cuda_snapshot_layout_test.zig @@ -106,7 +106,11 @@ test "cache shape: GLM-5.3-Flash's pages keep their bytes, full GLM-5.3's 79 cac try t.expectEqual(@as(usize, 576), full.row); try t.expectEqual(@as(usize, 512 * 576 * 2), full.latentBytes()); try t.expectEqual(@as(usize, 512 * 128 * 2), full.pkBytes()); - try t.expectEqual(@as(u64, 79 * (576 * 2 + 128 * 2) * state.page_rows), full.pageBytes()); + // 79 caches' 56,950,784 bytes, padded to whole 576-wide rows and 512 tokens (4,608 bytes): 4,096 more + try t.expectEqual(@as(u64, 79 * (576 * 2 + 128 * 2) * state.page_rows + 4096), full.pageBytes()); + try t.expectEqual(@as(u64, 0), full.pageBytes() % (576 * 2)); + try t.expectEqual(@as(u64, 0), full.pageBytes() % state.page_rows); + try t.expectEqual(@as(u64, 49_440), full.pageBytes() / (576 * 2)); // dsa_block's page_rows: a token list's rows } /// Full GLM-5.3's caches on a state: 78 DSA layers and no KDA, 576-wide latent rows, a pooled key a row. diff --git a/zig/src/families/glm/cuda_state.zig b/zig/src/families/glm/cuda_state.zig index 3be6dfde8f7..e512e6c4232 100644 --- a/zig/src/families/glm/cuda_state.zig +++ b/zig/src/families/glm/cuda_state.zig @@ -91,9 +91,10 @@ pub const Shape = struct { return s.latentBytes() + s.pkBytes(); } - /// A page's bytes: every cache's part (13,056 a row on GLM-5.3-Flash). + /// A page's bytes: every cache's part, padded to whole latent rows (page_rows a page) and whole token bytes. pub fn pageBytes(s: Shape) u64 { - return s.caches * s.cacheBytes(); + const unit = s.row * 2 / std.math.gcd(s.row * 2, page_rows) * page_rows; + return (s.caches * s.cacheBytes() + unit - 1) / unit * unit; } /// TF_GLM_KV_HOST: every cache's pooled keys on a device page of their own. @@ -152,10 +153,12 @@ fn b16Shapes(w: *const weights.Weights) [12][2]usize { const s = &w.share; const n = s.kda.len() * c.kda_dim; const kw = @import("cuda_kda_block.zig").rowWidth(s.kda.len()); // TF_GLM_KDA_PAD + const row = c.latentRow(); // kv_a: the latent, then its roped key columns + const qh = c.nope + c.rope; // a q head return .{ - .{ kw, c.hidden }, .{ n, c.kda_dim }, .{ c.hidden, n }, - .{ c.q_lora + c.kv_lora, c.hidden }, .{ s.mla.len() * c.nope, c.q_lora }, .{ c.i_dim + c.i_heads, c.hidden }, - .{ c.i_heads * c.i_dim, c.q_lora }, .{ c.hidden, s.mla.len() * c.v_dim }, .{ 2 * s.shared.len(), c.hidden }, + .{ kw, c.hidden }, .{ n, c.kda_dim }, .{ c.hidden, n }, + .{ c.q_lora + row, c.hidden }, .{ s.mla.len() * qh, c.q_lora }, .{ c.i_dim + c.i_heads, c.hidden }, + .{ c.i_heads * c.i_dim, c.q_lora }, .{ c.hidden, s.mla.len() * c.v_dim }, .{ 2 * s.shared.len(), c.hidden }, .{ c.hidden, 2 * c.hidden }, // the MTP head's eh_proj if (c.exl3) .{ 2 * s.dense.len(), c.hidden } else .{ c.hidden, 2 * c.hidden }, // bf16 dense layers: [gate | up] if (c.exl3) .{ c.hidden, s.dense.len() } else .{ c.hidden, 2 * c.hidden }, // and down @@ -270,9 +273,12 @@ pub const Buffers = struct { const pairs = rows * slots; const count: usize = c.experts; const lw: usize = c.kv_lora; + const row: usize = c.latentRow(); // the latent, then its roped key columns + const qh: usize = c.nope + c.rope; // a q head const part_rows = if (prefill) @min(rows, dsa_block.prompt_att_rows) else seg; const nch = latent.chunksFor(@min(capacity, dense_reach) + seg); - const partial_rows = @max(nch * part_rows, latent.chunksFor(sparse.width) * seg); // dense calls, or one sparse + const width: usize = c.keyWidth(); // a token list (sparse.Geometry.width) + const partial_rows = @max(nch * part_rows, latent.chunksFor(width) * seg); // dense calls, or one sparse const np_max = capacity / c.kpool; const sel = selectLs(rows, prefill, seg, np_max); var mm: usize = 4; @@ -291,10 +297,10 @@ pub const Buffers = struct { if (own_proj) rows * kw * 2 else 4, rows * n * 2, rows * n * 2, // kproj, ka, kg rows * n * 2, rows * n * 4, rows * n * 2, rows * n * 4, // saves out, k, v, g rows * LL * 4, rows * n * 4, rows * n * 2, // saves b, wide q, y - rows * (c.q_lora + lw) * 2, rows * c.q_lora * 2, rows * (c.q_lora / 64) * 4, - rows * lw * 2, rows * (lw / 64) * 4, rows * HL * c.nope * 2, + rows * (c.q_lora + row) * 2, rows * c.q_lora * 2, rows * (c.q_lora / 64) * 4, + rows * row * 2, rows * (lw / 64) * 4, rows * HL * qh * 2, rows * (c.i_dim + c.i_heads) * 2, rows * c.i_dim * 4, glue.router_ks * rows * @max(count, c.i_dim) * 4, - rows * HL * lw * 2, rows * HL * lw * 2, rows * HL * c.v_dim * 2, + rows * HL * row * 2, rows * HL * lw * 2, rows * HL * c.v_dim * 2, rows * c.i_heads * c.i_dim * 2, partial_rows * HL * lw * 4, partial_rows * HL * 4, partial_rows * HL * 4, 4, // dummy @@ -303,7 +309,7 @@ pub const Buffers = struct { rows * sparse.select_list * 4, (if (prefill) rows + s.world else rows) * (c.i_topk / c.kpool) * 8, // pools; a split's equal blocks end at most world - 1 rows past them 4, - rows * sparse.width * 4, + rows * width * 4, rows * 4, mm, 4, // a prompt block's position diff --git a/zig/src/families/glm/cuda_tile.zig b/zig/src/families/glm/cuda_tile.zig index 3fef15dd2ad..f45027a5256 100644 --- a/zig/src/families/glm/cuda_tile.zig +++ b/zig/src/families/glm/cuda_tile.zig @@ -39,8 +39,8 @@ fn layerLinears(gpa: std.mem.Allocator, l: *Layer, list: *std.ArrayList(Lin)) !v try addProj(list, gpa, &x.o, x.dims, n); }, .mla => |*x| { - try addProj(list, gpa, &x.proj, x.q_lora + x.lw, x.dims); - try addProj(list, gpa, &x.q_b, x.heads * x.qk, x.q_lora); + try addProj(list, gpa, &x.proj, x.q_lora + x.row(), x.dims); + try addProj(list, gpa, &x.q_b, x.heads * x.qHead(), x.q_lora); try addProj(list, gpa, &x.index.kw, x.index.d + x.index.heads, x.dims); try addProj(list, gpa, &x.index.qb, x.index.heads * x.index.d, x.q_lora); try addProj(list, gpa, &x.o, x.dims, x.heads * x.dv); diff --git a/zig/src/families/glm/cuda_weights.zig b/zig/src/families/glm/cuda_weights.zig index 48ddff20cb9..3954321e72d 100644 --- a/zig/src/families/glm/cuda_weights.zig +++ b/zig/src/families/glm/cuda_weights.zig @@ -250,7 +250,8 @@ const Loader = struct { const q_norm = try L.put("layers.{d}.dsa.q_norm", .{i}); try L.whole(try L.get("layers.{d}.self_attn.kv_a_layernorm.weight", .{i}), .bf16); const kv_norm = try L.put("layers.{d}.dsa.kv_norm", .{i}); - const q_b = try formats.cutProj(L, prefix, i, &.{.{ .rel = "self_attn.q_b_proj", .rows = .{ h.lo * qk, h.hi * qk } }}, wants, "layers.{d}.dsa.q_b"); + const qh = qk + c.rope; // a q head's rows: its latent-path dims, then its roped ones + const q_b = try formats.cutProj(L, prefix, i, &.{.{ .rel = "self_attn.q_b_proj", .rows = .{ h.lo * qh, h.hi * qh } }}, wants, "layers.{d}.dsa.q_b"); const kv_b = try L.get("layers.{d}.self_attn.kv_b_proj.weight", .{i}); const per = qk + c.v_dim; // a head's kv_b rows: its keys, then its values const total = c.mla_heads * per; @@ -283,6 +284,7 @@ const Loader = struct { .qk = qk, .dv = c.v_dim, .lw = c.kv_lora, + .rope = c.rope, .q_lora = c.q_lora, .dims = c.hidden, .eps = c.eps, diff --git a/zig/tests/cuda/contract_mla.zig b/zig/tests/cuda/contract_mla.zig index 837c785f07e..261066ce415 100644 --- a/zig/tests/cuda/contract_mla.zig +++ b/zig/tests/cuda/contract_mla.zig @@ -1,4 +1,4 @@ -//! The mla image (mla.cu) under the contract: its seven launches through gates 1-4, and a planted control for each. +//! The mla image (mla.cu) under the contract: its eight launches through gates 1-4, and a planted control for each. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -227,12 +227,13 @@ pub const Group = struct { try mod.function("tf_mla_chunks_r16"), try mod.function("tf_mla_chunks_split_r16"), try mod.function("tf_mla_merge_part"), + try mod.function("tf_mla_absorb_q_192"), }; for (fs[4..6]) |f| try f.allowDynamicShared(cuda.mla.chunksSmem(cuda.mla.heads_tile)); const self = try a.create(Group); self.* = .{ .a = a, .mod = mod }; for (&self.rows, entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .f = fs[@intFromBool(e.kind == .rope)] }; - for (&self.projs, proj_k.entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .f = fs[if (e.kind == .absorb) 2 else 3] }; + for (&self.projs, proj_k.entries) |*x, e| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .entry = e, .f = fs[if (e.kind == .expand) 3 else if (e.nope == 192) 7 else 2] }; for (&self.chunks, chunks_k.forms) |*x, form| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = fs[4], .merge = merge, .fault = form.fault, .split = if (form.split) .{ fs[5], fs[6] } else null }; for (&self.rows) |*x| try kernels.append(a, x.kernel()); for (&self.projs) |*x| try kernels.append(a, x.kernel()); diff --git a/zig/tests/cuda/contract_mla_proj.zig b/zig/tests/cuda/contract_mla_proj.zig index 0fad3887700..c2f95a07449 100644 --- a/zig/tests/cuda/contract_mla_proj.zig +++ b/zig/tests/cuda/contract_mla_proj.zig @@ -1,4 +1,4 @@ -//! The mla image's absorb_q and expand_v (128-wide heads) under the contract. +//! The mla image's absorb_q (128- and full GLM-5.3's 192-wide q_nope) and expand_v (128-wide heads) under the contract. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -9,25 +9,27 @@ const c = contract.spec; const g = contract.gates; const lw = 512; // the latent width -const qs = 192; // a q head: 128 nope columns, then 64 rope +const rope = 64; // a q head: its nope columns, then 64 roped ones (192 or 256) const qaw = 576; // an absorbed q row: the latent, then the roped columns (left as they were) const rows_rb = 64; // cuda_latent.prompt_rows and prompt_rb: rows from 64 on go 64 a block pub const Kind = enum { absorb, expand }; -/// next_head: a control red at gate 3, each head launched with the next head's weights. -pub const Entry = struct { name: []const u8, kind: Kind, next_head: bool = false }; +/// next_head: a control red at gate 3, each head launched with the next head's weights; nope: absorb's q_nope. +pub const Entry = struct { name: []const u8, kind: Kind, next_head: bool = false, nope: usize = 128 }; pub const entries = [_]Entry{ .{ .name = "cuda mla tf_mla_absorb_q_128 (q_nope . wk into the latent)", .kind = .absorb }, .{ .name = "cuda mla tf_mla_expand_v_128 (latent . wv into 128-wide v heads)", .kind = .expand }, .{ .name = "control: mla tf_mla_absorb_q_128 reads each head's wk from the next head", .kind = .absorb, .next_head = true }, .{ .name = "control: mla tf_mla_expand_v_128 reads each head's wv from the next head", .kind = .expand, .next_head = true }, + .{ .name = "cuda mla tf_mla_absorb_q_192 (full GLM-5.3's q_nope . wk into the latent)", .kind = .absorb, .nope = 192 }, + .{ .name = "control: mla tf_mla_absorb_q_192 reads each head's wk from the next head", .kind = .absorb, .next_head = true, .nope = 192 }, }; -/// absorb: four fma steps a thread, three butterfly steps, four warps' partials, two more steps. -fn depthAbsorb(_: c.Shape) usize { - return 12; +/// absorb: k / 32 fma steps a thread (four at 128, six at 192), three butterfly steps, the warps' partials, two more. +fn depthAbsorb(s: c.Shape) usize { + return s.k / 32 + 8; } /// expand: eight fma steps a thread, the warp's five steps, then the two warps. @@ -36,13 +38,15 @@ fn depthExpand(_: c.Shape) usize { } const absorb_shapes = [_]c.Shape{ .{ .rows = 1, .n = 32, .k = 128 }, .{ .rows = 8, .n = 64, .k = 128 }, .{ .rows = 70, .n = 32, .k = 128 } }; +// full GLM-5.3: 21 or 22 heads a rank at TP=3 +const absorb192_shapes = [_]c.Shape{ .{ .rows = 1, .n = 22, .k = 192 }, .{ .rows = 8, .n = 21, .k = 192 }, .{ .rows = 70, .n = 22, .k = 192 } }; const expand_shapes = [_]c.Shape{ .{ .rows = 1, .n = 32, .k = lw }, .{ .rows = 8, .n = 64, .k = lw }, .{ .rows = 70, .n = 32, .k = lw } }; pub fn spec(e: Entry) c.Spec { const no: c.Tile = .{}; const rows_edge: c.Tile = .{ .size = rows_rb }; return switch (e.kind) { - .absorb => .{ .name = e.name, .accum = .f32, .depth = depthAbsorb, .out = .bf16, .tiles = .{ rows_edge, no, no }, .served = &absorb_shapes }, + .absorb => .{ .name = e.name, .accum = .f32, .depth = depthAbsorb, .out = .bf16, .tiles = .{ rows_edge, no, no }, .served = if (e.nope == 192) &absorb192_shapes else &absorb_shapes }, .expand => .{ .name = e.name, .accum = .f32, .depth = depthExpand, .out = .bf16, .tiles = .{ rows_edge, no, no }, .served = &expand_shapes }, }; } @@ -88,7 +92,12 @@ pub const Proj = struct { } fn xWidth(self: *const Proj) usize { - return if (self.entry.kind == .absorb) qs else lw; + return if (self.entry.kind == .absorb) self.entry.nope + rope else lw; + } + + /// A head's weight rows: absorb's q_nope, expand's 128 v columns. + fn headRows(self: *const Proj) usize { + return if (self.entry.kind == .absorb) self.entry.nope else 128; } pub fn count(self: *const Proj) usize { @@ -97,7 +106,7 @@ pub const Proj = struct { pub fn prepare(self: *Proj, shape: c.Shape, fill: g.Fill, seed: u64) !bool { if (shape.rows == 0 or shape.n == 0) return false; - if (shape.k != (if (self.entry.kind == .absorb) @as(usize, 128) else lw)) return false; + if (shape.k != (if (self.entry.kind == .absorb) self.entry.nope else lw)) return false; self.free(); self.rig.reset(); self.shape = shape; @@ -107,7 +116,7 @@ pub const Proj = struct { const rng = prng.random(); self.x = try a.alloc(u16, shape.rows * heads * self.xWidth()); for (self.x) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 2); - const wn = heads * 128 * lw; // wk [heads][128][lw], wv [heads][128][lw] + const wn = heads * self.headRows() * lw; // wk [heads][nope][lw], wv [heads][128][lw] self.w = try a.alloc(u16, wn); for (self.w) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.125); switch (fill) { @@ -150,7 +159,7 @@ pub const Proj = struct { self.w[self.wAt(hd, h + i, o)] = c.toBf16(v); }; // x = 512 x odd (terms past fp16's range), the second half -x, the first eight of it -x + 512: small sums - const odd: u32 = if (self.entry.kind == .absorb) 64 else 16; // every partial sum under 2^24 + const odd: u32 = if (self.entry.kind == .absorb) @intCast(8192 / k) else 16; // every partial sum under 2^24 for (0..self.shape.rows) |r| for (0..heads) |hd| for (0..h) |i| { const v: f32 = @floatFromInt(512 * (1 + 2 * rng.uintLessThan(u32, odd))); const at = (r * heads + hd) * self.xWidth(); @@ -159,9 +168,9 @@ pub const Proj = struct { }; } - /// Weight of reduced index i and output column o in head hd: absorb wk [hd*128 + i][o], expand wv [hd*128 + o][i]. + /// Weight of reduced index i and output column o in head hd: absorb wk [hd*nope + i][o], expand wv [hd*128 + o][i]. fn wAt(self: *const Proj, hd: usize, i: usize, o: usize) usize { - return if (self.entry.kind == .absorb) (hd * 128 + i) * lw + o else (hd * 128 + o) * lw + i; + return if (self.entry.kind == .absorb) (hd * self.headRows() + i) * lw + o else (hd * 128 + o) * lw + i; } pub fn run(self: *Proj) !void { @@ -171,7 +180,7 @@ pub const Proj = struct { var a: cuda.Args = .{}; inline for (.{ self.xd, self.wd, self.out, @as(i64, @intCast(s.rows)), @as(i64, @intCast(s.n)), @as(i64, @intCast(rb)) }) |v| a.add(v); if (self.entry.kind == .absorb) { - a.add(@as(i64, qs)); + a.add(@as(i64, @intCast(self.xWidth()))); a.add(@as(i64, qaw)); } const cols: u32 = if (self.entry.kind == .absorb) lw / 32 else 128 / 16; diff --git a/zig/tests/cuda/glm_loader_gate.zig b/zig/tests/cuda/glm_loader_gate.zig index 311d8aacb99..4cd0dcc6912 100644 --- a/zig/tests/cuda/glm_loader_gate.zig +++ b/zig/tests/cuda/glm_loader_gate.zig @@ -518,7 +518,7 @@ pub fn run(gpu: check.Gpu, dir: []const u8) !void { const a = arena.allocator(); const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, try std.fs.path.join(a, &.{ dir, "config.json" }), a, .limited(1 << 24)); const c = try glm.config.parse(a, text); - var m = try glm.forward.Modules.load(gpu.d, gpu.ctx, try glm.experts.wantsBlock32(a, text)); + var m = try glm.forward.Modules.load(gpu.d, gpu.ctx, try glm.experts.wantsBlock32(a, text), false); defer m.deinit(); var stream = try cuda.Stream.init(gpu.d, false); defer stream.deinit(); From f894c05bb5ef9eeee9706b7716d3308f23131048 Mon Sep 17 00:00:00 2001 From: bjornmonnens <787697+bjornmonnens@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:33:41 +0100 Subject: [PATCH 4/8] changelog: #3949 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44625cb98a1..f043b0b2188 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA on unified-memory Linux (GB10): the start-up memory budget is at most the free memory CUDA reports, less the same reserve, instead of `/proc/meminfo` alone, and the server first drops the checkpoint's own shards from the page cache, so a checkpoint that was just read is not refused for its own cached pages; discrete cards, Windows, Metal and HIP are unchanged (#3192, part of #1857). - Docs: the first gfx1201 receipt in the repository, Flash Next oQ2-MTP at `--tp 2` on two Radeon AI PRO R9700s against #2401's 1.2.3 numbers on the same card class, and `docs/recipes/flash-next-hip.md` as the home for Flash Next on HIP (#3608, refs #2401). Thanks to @timmyit. +- GLM-5.3 on CUDA: the latent row width and cache count, the DSA indexer's pool size, key store and index rope, and 576-wide roped latent rows are read from the model instead of fixed at GLM-5.3-Flash's values (one new kernel, `tf_mla_absorb_q_192`), so full GLM-5.3's shapes (79 caches of 576-value rows, pools of 1, top 2,048, 64 roped index dims) can run on the Flash pieces; GLM-5.3-Flash's launches and replies are unchanged (#3949, part of #3063). + ## 1.3.3 From e3bdcad31a9fe5a924fe676ccb871475efb0f16a Mon Sep 17 00:00:00 2001 From: bjornmonnens <787697+bjornmonnens@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:44:57 +0100 Subject: [PATCH 5/8] glm index emulator: sincosf on macOS, whose libm does not declare it (#3949) --- tools/glm_index_emulate/cuda_runtime.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/glm_index_emulate/cuda_runtime.h b/tools/glm_index_emulate/cuda_runtime.h index cc0a8f9e9af..7911640ec46 100644 --- a/tools/glm_index_emulate/cuda_runtime.h +++ b/tools/glm_index_emulate/cuda_runtime.h @@ -79,6 +79,13 @@ inline int __float_as_int(float f) { int i; std::memcpy(&i, &f, 4); return i; } inline float __fadd_rn(float a, float b) { return a + b; } inline float __fmul_rn(float a, float b) { return a * b; } inline float __fmaf_rn(float a, float b, float c) { return std::fma(a, b, c); } +#ifdef __APPLE__ +// glibc's sincosf, which Apple's libm does not declare (model and kernel both turn through it, so they stay equal) +inline void sincosf(float x, float* s, float* c) { + *s = std::sin(x); + *c = std::cos(x); +} +#endif using std::fmaxf; using std::max; using std::min; From 1d9516adfa67fbcc201fba938cc60682c72dd595 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:18:37 +0000 Subject: [PATCH 6/8] Follow main 7948cc42d GLM dependent launches in host recorders Main 7948cc42d3f74b3b5e6d4ef8776c3777172c20d0 routes GLM launches through cuLaunchKernelEx. Forward that entry through main's pdl.forwardEx in the new recording fixtures and keep the merged code in zig fmt style. --- zig/exl3_prompt_host.zig | 2 ++ zig/glm_exl3_prompt_host.zig | 1 + zig/src/families/glm/cuda_latent_test.zig | 1 + zig/src/families/glm/cuda_sparse.zig | 1 + 4 files changed, 5 insertions(+) diff --git a/zig/exl3_prompt_host.zig b/zig/exl3_prompt_host.zig index 3cd2e5fbe39..1b41026c0b1 100644 --- a/zig/exl3_prompt_host.zig +++ b/zig/exl3_prompt_host.zig @@ -54,6 +54,7 @@ fn run(rows: usize, prompt: bool, shared: bool) !void { Capture.reset(); var d: cuda.Driver = undefined; d.api.cuLaunchKernel = Capture.launch; + d.api.cuLaunchKernelEx = glm.pdl.forwardEx(Capture.launch); d.api.cuMemcpy2DAsync_v2 = Capture.copy; const s: cuda.Stream = .{ .d = &d, .handle = null }; var k: ex.Experts = .{ .mod = undefined, .group = function(&d, 1), .rot_in = function(&d, 2), .grouped = @splat(function(&d, 3)), .gateup = function(&d, 4), .down_combine = function(&d, 5) }; @@ -266,6 +267,7 @@ test "exl3 prompt: GLM admission facts through shared lanes keep drafted plain a test "exl3 prompt: each projection group launches the kernel of its own verified width, with the same arguments" { var d: cuda.Driver = undefined; d.api.cuLaunchKernel = Capture.launch; + d.api.cuLaunchKernelEx = glm.pdl.forwardEx(Capture.launch); const s: cuda.Stream = .{ .d = &d, .handle = null }; var k: ex.Experts = .{ .mod = undefined, .group = function(&d, 1), .rot_in = function(&d, 2), .grouped = @splat(function(&d, 3)), .gateup = function(&d, 4), .down_combine = function(&d, 5) }; k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13), .gateup_k6 = function(&d, 14), .down_k6 = function(&d, 15) }; diff --git a/zig/glm_exl3_prompt_host.zig b/zig/glm_exl3_prompt_host.zig index 1308d03e361..a0cf655c204 100644 --- a/zig/glm_exl3_prompt_host.zig +++ b/zig/glm_exl3_prompt_host.zig @@ -77,6 +77,7 @@ fn run(rows: usize, prompt: bool, shared: bool, count: usize) !void { Record.reset(); var d: cuda.Driver = undefined; d.api.cuLaunchKernel = Record.launch; + d.api.cuLaunchKernelEx = glm.pdl.forwardEx(Record.launch); d.api.cuMemcpy2DAsync_v2 = Record.copy; var k: glm.exl3.Kernels = undefined; inline for (.{ "group", "rot_in", "gateup", "down_combine" }, .{ 9, 5, 13, 14 }) |field, id| @field(k, field) = Record.function(&d, id); diff --git a/zig/src/families/glm/cuda_latent_test.zig b/zig/src/families/glm/cuda_latent_test.zig index 90ce221f6cb..b0d79e169a0 100644 --- a/zig/src/families/glm/cuda_latent_test.zig +++ b/zig/src/families/glm/cuda_latent_test.zig @@ -92,6 +92,7 @@ const Fakes = struct { fn init(f: *Fakes) void { f.d = undefined; f.d.api.cuLaunchKernel = Launch.run; + f.d.api.cuLaunchKernelEx = @import("cuda_pdl.zig").forwardEx(Launch.run); f.d.api.cuModuleGetFunction = Ops.function; inline for (@typeInfo(glue.Kernels).@"struct".field_names, 1..) |name, i| @field(f.ks, name) = .{ .d = &f.d, .handle = @ptrFromInt(i) }; f.m = undefined; diff --git a/zig/src/families/glm/cuda_sparse.zig b/zig/src/families/glm/cuda_sparse.zig index f4bef0244ef..a7313948392 100644 --- a/zig/src/families/glm/cuda_sparse.zig +++ b/zig/src/families/glm/cuda_sparse.zig @@ -273,6 +273,7 @@ test "GLM index geometry: indexUpdate passes GLM-5.3-Flash's rope 0 and pools of }; var d: cuda.Driver = undefined; d.api.cuLaunchKernel = R.launch; + d.api.cuLaunchKernelEx = @import("cuda_pdl.zig").forwardEx(R.launch); var ks: glue.Kernels = undefined; ks.index_write = .{ .d = &d, .handle = @ptrFromInt(1) }; ks.pool_keys = .{ .d = &d, .handle = @ptrFromInt(2) }; From 188c78749f4d1a4ef827befb0155686c101f6b00 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:18:37 +0000 Subject: [PATCH 7/8] Re-pin changed GLM CUDA sources after #3949 on current main --- zig/tests/fixtures/gradient-serving.tsv | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 5af388e902c..7d29aa30156 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -18,17 +18,17 @@ zig/kernels/cuda/flashnext_mtp.cu 5d213b1b4a1d0588eea3acb4633a0c8bc4d9bdf6f27485 zig/kernels/cuda/fp8_experts.cu 156aa7337b41c67d200d8b58a24422cc96cfa032c9fd0711080f09ddc733baee raw zig/kernels/cuda/gdn.cu e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228 raw zig/kernels/cuda/glm_glue.cu 74e69a7c20827d498c190334fffaa896f2a4f05e107fdf9d2d34b09b55a1c75c raw #2722 (one added line, the include of glm_index_decode.cuh: the decode select's scan and merge) -zig/kernels/cuda/glm_glue_attn.cuh a8c16ed0c54130689d19386de84217aac232c007effafdb6c7fc149ac7188051 raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) +zig/kernels/cuda/glm_glue_attn.cuh 2a0bc3c4966555fad4ae812e62b28558f41774fd5b2dbef6fa9b6d220ba260d8 raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_bmm.cuh 6077ea47fc9f462f072a973d44ef4cab711526a3f374cfeb91f1cd65f5fad8f9 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_hc.cuh 0fc7a68598eb22884edf28d39d051399e85e2e3e13fd45953c8d3faf5defd3b8 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) -zig/kernels/cuda/glm_glue_index.cuh ed61d03673005220aeebc43a1da5e5701566fcd5e89fee5d21d3830b20cf73ec raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) +zig/kernels/cuda/glm_glue_index.cuh 76c330e99c8dca37589873f7082f35046027873635973d3ef1f2af286b3884a6 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_latent.cuh 67964ea6596deae54f52a8a365850c3a19dab75160cb9582d7bbeaff5d896f5a raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_moe.cuh 474148b5bf8f6d4d83a4a205ae90d0d347f2a40f1f8093fe1b2508282d0d86b7 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_norm.cuh a3664d9833c17ff4718b7342c529ddd7fa958cbc51a8ffac9b7fab508afbcf92 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_router.cuh 99911df38e6ad2826491b3fa5efd47aea5e54eebb7cd83eed586ba0dd9305658 raw zig/kernels/cuda/glm_glue_rows.cuh 8d22166c33ce75fb2dfe5383694a8503044613420d7a06e90e6d1a0b88c197b2 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_kda.cu aef9f980f8a928f2b6c439c7e1eda499fba12c32a7605e39062bef83952a83d2 raw #2142: the KDA chain and saved-row replay moved to common/kda.cuh; SASS identical on sm_80/86/89/120/121 (5,465 functions); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) -zig/kernels/cuda/glm_ops.cu bf90d5eeb62c145d8a140db90e057fa53d3c1f6b77f739d14122a0e04a216b51 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh); dependent-launch inputs without __restrict__ (no non-coherent load above the wait) +zig/kernels/cuda/glm_ops.cu a1bce733ad303e91ba3765cb7006742861ee33fa3d9b26d21bed4e4036b5c6a7 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh); dependent-launch inputs without __restrict__ (no non-coherent load above the wait) zig/kernels/cuda/glm_quant.cu e04ee0760ddd215244117bbf113f625ce2e9da3eef04345eb0741e1cd2c876ea raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_triton.cuh 8eee12f24bbf283a08a29f9396e3db5588b48fce85abe74de7f85adc12fa94f4 raw zig/kernels/cuda/common/glue_math.cuh b7234684fc786b3700473358632bf10f0b2d2240e5957eefddb13254dae5d746 raw From a970627cfe7a90d6b15fc5f658ac26cb81aca22e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:37:22 +0000 Subject: [PATCH 8/8] changelog: #3949's line from lines/3949.txt in place of its own --- CHANGELOG.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f043b0b2188..5190f9a1bcf 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: GLM-5.3-Flash's latent cache and indexer accept full GLM-5.3's shapes (slice (a) of #3063) (#3949). Thanks to @bjornmonnens. + - Qwen3.8-27B on Metal (M1 to M4): `--mtp-drafts N` loads the checkpoint's MTP head from `mtp-4bit.safetensors` and drafts chains of up to N tokens for every stream, alone or in shared rounds, and `--mtp-confidence` stops a chain below its floor; before, the Metal build refused both flags (#2464, refs #2368). Thanks to @jschmied. - Flash Next on CUDA: `TF_FLASHNEXT_GATHER_EARLY=1` (default `0`) gathers a shared decode pass's n-gram rows for every lane in one pooled call instead of one call a stream, for passes of at most 64 lanes (wider passes keep the per-stream call); which rows are read and how a row is dequantized do not change, so replies stay main's, and the measured mean decode gain on one GB10 rises to +2.10% at eight streams (#4009). Thanks to @BadAd84. @@ -20,14 +22,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA: Enable dense MTP drafting for Qwen3.5-family targets with compatible checkpoint tensors (#3582). Thanks to @tacosta. - - - CUDA on unified-memory Linux (GB10): the start-up memory budget is at most the free memory CUDA reports, less the same reserve, instead of `/proc/meminfo` alone, and the server first drops the checkpoint's own shards from the page cache, so a checkpoint that was just read is not refused for its own cached pages; discrete cards, Windows, Metal and HIP are unchanged (#3192, part of #1857). - Docs: the first gfx1201 receipt in the repository, Flash Next oQ2-MTP at `--tp 2` on two Radeon AI PRO R9700s against #2401's 1.2.3 numbers on the same card class, and `docs/recipes/flash-next-hip.md` as the home for Flash Next on HIP (#3608, refs #2401). Thanks to @timmyit. -- GLM-5.3 on CUDA: the latent row width and cache count, the DSA indexer's pool size, key store and index rope, and 576-wide roped latent rows are read from the model instead of fixed at GLM-5.3-Flash's values (one new kernel, `tf_mla_absorb_q_192`), so full GLM-5.3's shapes (79 caches of 576-value rows, pools of 1, top 2,048, 64 roped index dims) can run on the Flash pieces; GLM-5.3-Flash's launches and replies are unchanged (#3949, part of #3063). - - ## 1.3.3