From 23cb2ef994c9b27c6eaa4b3aa994df0c0be62646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:51:58 +0100 Subject: [PATCH 1/4] core: one copy of TFQ3's shared arithmetic (TFQ3 format move, piece 2) Span, the overlap test, matWords, validBits and the 4-bit uint4 predicate move into core/tfq3_format.zig. Flash Next, GLM and CUDA keep every public name, signature, error name and check order as thin wrappers; matScales, tensorWords, tensorScales and span stay per backend. A core test pins each moved function against main's bodies over edge values. --- zig/src/core/tfq3_arith_test.zig | 101 ++++++++++++++++++ zig/src/core/tfq3_format.zig | 33 +++++- zig/src/cuda/tfq3_format.zig | 47 +++++++- zig/src/families/flashnext/tfq3_check.zig | 15 +-- .../families/flashnext/tfq3_check_test.zig | 10 ++ zig/src/families/glm/tfq3_check.zig | 13 +-- 6 files changed, 193 insertions(+), 26 deletions(-) create mode 100644 zig/src/core/tfq3_arith_test.zig diff --git a/zig/src/core/tfq3_arith_test.zig b/zig/src/core/tfq3_arith_test.zig new file mode 100644 index 00000000000..ab8972e4d7a --- /dev/null +++ b/zig/src/core/tfq3_arith_test.zig @@ -0,0 +1,101 @@ +//! TFQ3's shared arithmetic against the copies it replaced (main 91dbadce65), kept here verbatim as the oracles. +const std = @import("std"); +const f = @import("tfq3_format.zig"); +const t = std.testing; +const max = std.math.maxInt; + +/// Flash Next tfq3_check.zig:87 and GLM tfq3_check.zig:127 on main: one body, refusing as Tfq3Overflow. +fn mainMatWords(r: usize, c: usize, bits: usize) error{Tfq3Overflow}!usize { + const rc = std.math.mul(usize, r, c) catch return error.Tfq3Overflow; + return (std.math.mul(usize, rc, bits) catch return error.Tfq3Overflow) / 32; +} + +/// CUDA tfq3_format.zig:40 on main. +fn mainValidBits(bits: u32) bool { + return bits == 3 or bits == 4 or bits == 5; +} + +/// Flash Next tfq3_check.zig:79, the inline loop in `header` on main. +fn mainFlashNextOverlap(head: usize, all: []const f.Span) bool { + for (all, 0..) |a, i| { + if (a.len > 0 and a.off < head) return true; + for (all[i + 1 ..]) |b| if (a.len > 0 and b.len > 0 and a.off < b.off + b.len and b.off < a.off + a.len) return true; + } + return false; +} + +/// GLM tfq3_check.zig:93 `disjoint` on main, true where it refused. +fn mainGlmOverlap(head: usize, spans: []const f.Span) bool { + for (spans, 0..) |a, i| { + if (a.len > 0 and a.off < head) return true; + for (spans[i + 1 ..]) |b| { + if (a.len == 0 or b.len == 0) continue; + if (a.off < b.off + b.len and b.off < a.off + a.len) return true; + } + } + return false; +} + +const dims = [_]usize{ 0, 1, 2, 15, 16, 17, 31, 32, 33, 127, 128, 129, 640, 2048, 2560, 4096, max(u16), max(u32) - 1, max(u32), 1 << 32, 1 << 33, max(usize) / 32, max(usize) / 5, max(usize) / 4, max(usize) / 3, max(usize) / 2, max(usize) - 1, max(usize) }; +const widths = [_]usize{ 0, 1, 2, 3, 4, 5, 6, 8, 16, 32, max(u32), max(usize) }; + +test "TFQ3 arithmetic: matWords equals main's checked body on every edge, null exactly where main refused" { + for (dims) |r| for (dims) |c| for (widths) |bits| { + const got = f.matWords(r, c, bits); + if (mainMatWords(r, c, bits)) |want| try t.expectEqual(@as(?usize, want), got) else |_| try t.expectEqual(@as(?usize, null), got); + }; + try t.expectEqual(@as(?usize, 204800), f.matWords(640, 2560, 4)); // a Flash Next gate or up projection at 4 bits + try t.expectEqual(@as(?usize, 256000), f.matWords(2560, 640, 5)); + try t.expectEqual(@as(?usize, 786432), f.matWords(2048, 4096, 3)); // a GLM projection at 3 bits + try t.expectEqual(@as(?usize, 0), f.matWords(1, 7, 4)); // floor: 28 bits are no whole word + try t.expectEqual(@as(?usize, 1), f.matWords(1, 8, 4)); + try t.expectEqual(@as(?usize, 274), f.matWords(17, 129, 4)); // off the 16 x 128 grid (CUDA's tensorWords: 256) + try t.expectEqual(@as(?usize, null), f.matWords(1 << 33, 1 << 33, 0)); // R * C overflows: refused though bits is 0 + try t.expectEqual(@as(?usize, null), f.matWords(1 << 62, 1, 4)); // the second product overflows; / 32 would fit + try t.expectEqual(@as(?usize, max(usize) / 32), f.matWords(max(usize), 1, 1)); +} + +test "TFQ3 arithmetic: validBits is CUDA's 3/4/5 and Flash Next's 3..5 range on every u32 edge" { + var bits: u32 = 0; + while (bits < 70) : (bits += 1) { + try t.expectEqual(mainValidBits(bits), f.validBits(bits)); + try t.expectEqual(!(bits < 3 or bits > 5), f.validBits(bits)); // Flash Next tfq3_check.zig:100 on main + } + for ([_]u32{ 1 << 31, max(u32) - 1, max(u32) }) |b| try t.expect(!f.validBits(b)); +} + +test "TFQ3 arithmetic: uint4Misaligned is every copy's 4-bit, off-a-uint4 test, and nothing else" { + const offs = [_]u64{ 0, 1, 2, 3, 4, 5, 7, 8, 12, 15, 16, 17, 204800, 204801, max(u32), 1 << 32, max(u64) - 3, max(u64) - 1, max(u64) }; + var bits: u32 = 0; + while (bits < 9) : (bits += 1) for (offs) |o| try t.expectEqual(bits == 4 and o % 4 != 0, f.uint4Misaligned(bits, o)); + try t.expect(f.uint4Misaligned(4, max(u64))); + try t.expect(!f.uint4Misaligned(4, max(u64) - 3)); + try t.expect(!f.uint4Misaligned(5, 1)); // 3/5-bit words are read one at a time + try t.expect(!f.uint4Misaligned(max(u32), 1)); +} + +test "TFQ3 arithmetic: overlaps refuses exactly what main's Flash Next loop and GLM disjoint refused" { + // every three spans with off 0..6 and len 0..4 (ends fit, as both callers check first), two header lengths + var n: usize = 0; + for ([_]usize{ 0, 3 }) |head| for (0..35) |x| for (0..35) |y| for (0..35) |z| { + const all = [3]f.Span{ .{ .off = x / 5, .len = x % 5 }, .{ .off = y / 5, .len = y % 5 }, .{ .off = z / 5, .len = z % 5 } }; + const want = mainFlashNextOverlap(head, &all); + try t.expectEqual(want, mainGlmOverlap(head, &all)); + try t.expectEqual(want, f.overlaps(head, &all)); + n += @intFromBool(want); + }; + try t.expect(n > 0 and n < 2 * 35 * 35 * 35); + const s = struct { + fn sp(off: usize, len: usize) f.Span { + return .{ .off = off, .len = len }; + } + }.sp; + try t.expect(!f.overlaps(144, &.{ s(16384, 32768), s(49152, 16), s(65536, 1) })); // Flash Next's valid shard + try t.expect(!f.overlaps(144, &.{ s(144, 10), s(154, 10), s(164, 10) })); // touching ends share no byte + try t.expect(!f.overlaps(144, &.{ s(400, 10), s(300, 10), s(200, 10) })); // reversed order, still disjoint + try t.expect(!f.overlaps(144, &.{ s(0, 0), s(200, 0), s(200, 0) })); // empty spans never overlap, even at 0 + try t.expect(f.overlaps(144, &.{ s(143, 1), s(200, 10), s(300, 10) })); // the header's last byte + try t.expect(f.overlaps(144, &.{ s(200, 10), s(300, 10), s(209, 1) })); // first and third share byte 209 + try t.expect(f.overlaps(144, &.{ s(200, 100), s(250, 1), s(400, 1) })); // one inside another + try t.expect(!f.overlaps(0, &.{})); +} diff --git a/zig/src/core/tfq3_format.zig b/zig/src/core/tfq3_format.zig index 8fd0308f6a4..9cd98e440cc 100644 --- a/zig/src/core/tfq3_format.zig +++ b/zig/src/core/tfq3_format.zig @@ -1,4 +1,4 @@ -//! TFQ3's on-disk records and wire constants, one copy for every backend; each backend keeps its checks and loaders. +//! TFQ3's on-disk records, wire constants and shared arithmetic, one copy; each backend keeps its checks and loaders. const std = @import("std"); pub const magic_layer: u32 = 0x57504654; // "TFPW": layer_NN.tffpw and mtp_00.tffpw, routed experts @@ -62,6 +62,36 @@ pub const NonMoeHeader = extern struct { pad1: u64, }; +/// A byte range of a file: [off, off + len). +pub const Span = struct { off: usize, len: usize }; + +/// Words of an R x C matrix at `bits`: floor(R * C * bits / 32), checked R * C first; null when a product overflows. +pub fn matWords(r: usize, c: usize, bits: usize) ?usize { + const rc = std.math.mul(usize, r, c) catch return null; + const all = std.math.mul(usize, rc, bits) catch return null; + return all / 32; +} + +/// A width the routed kernels decode: 3, 4 or 5 bits (each backend's dense rule may admit fewer). +pub fn validBits(bits: u32) bool { + return bits == 3 or bits == 4 or bits == 5; +} + +/// A 4-bit matrix whose words start off 16 bytes: the kernels read 4-bit words four at a time as uint4. +pub fn uint4Misaligned(bits: u32, word_off: u64) bool { + return bits == 4 and word_off % 4 != 0; +} + +/// Whether two non-empty spans share a byte or one starts inside the first `head` bytes; each end must fit usize. +pub fn overlaps(head: usize, spans: []const Span) bool { + for (spans, 0..) |a, i| { + if (a.len == 0) continue; + if (a.off < head) return true; + for (spans[i + 1 ..]) |b| if (b.len > 0 and a.off < b.off + b.len and b.off < a.off + a.len) return true; + } + return false; +} + comptime { std.debug.assert(@sizeOf(LayerHeader) == 144); std.debug.assert(@sizeOf(ExpertMeta) == 64); @@ -70,4 +100,5 @@ comptime { test { _ = @import("tfq3_format_test.zig"); + _ = @import("tfq3_arith_test.zig"); } diff --git a/zig/src/cuda/tfq3_format.zig b/zig/src/cuda/tfq3_format.zig index 93dca594da9..a77d6952c34 100644 --- a/zig/src/cuda/tfq3_format.zig +++ b/zig/src/cuda/tfq3_format.zig @@ -37,9 +37,7 @@ comptime { if (@sizeOf(TfpnTensorMeta) != 128) @compileError("TfpnTensorMeta must be 128 bytes"); } -pub fn validBits(bits: u32) bool { - return bits == 3 or bits == 4 or bits == 5; -} +pub const validBits = format.validBits; pub fn tensorWords(r: u32, c: u32, bits: u32) u64 { return @as(u64, r / 16) * @as(u64, c / 128) * @as(u64, bits * 2) * 32; @@ -100,7 +98,7 @@ pub fn validateTfpnNamed(bytes: []const u8, bad_name: ?*[]const u8) !DenseShard const metas: []align(1) const TfpnTensorMeta = std.mem.bytesAsSlice(TfpnTensorMeta, raw_meta); for (metas) |*m| { if (!validBits(m.b_bits) or m.r == 0 or m.c == 0 or (m.r % 128) != 0 or (m.c % 128) != 0) return error.InvalidTfq3Shard; - if (m.b_bits == 4 and m.word_off % 4 != 0) { + if (format.uint4Misaligned(m.b_bits, m.word_off)) { if (bad_name) |name| name.* = m.nameSlice(); return error.MisalignedTfq3Tensor; } @@ -139,7 +137,8 @@ pub fn validateTfpw(bytes: []const u8, expect_experts: ?u32, expect_hidden: ?u32 const sc_dn = tensorScales(h.hidden_size, h.moe_inter); for (metas) |m| { if (!validBits(m.b_bits)) return error.InvalidTfq3Shard; - if (m.b_bits == 4 and (m.gate_word_off % 4 != 0 or m.up_word_off % 4 != 0 or m.down_word_off % 4 != 0)) return error.MisalignedTfq3Tensor; + const b = m.b_bits; // all three alignments before any bounds + if (format.uint4Misaligned(b, m.gate_word_off) or format.uint4Misaligned(b, m.up_word_off) or format.uint4Misaligned(b, m.down_word_off)) return error.MisalignedTfq3Tensor; const gu_w = tensorWords(h.moe_inter, h.hidden_size, m.b_bits); const dn_w = tensorWords(h.hidden_size, h.moe_inter, m.b_bits); if ((std.math.add(u64, m.gate_word_off, gu_w) catch return error.InvalidTfq3Shard) > h.stream_words) return error.InvalidTfq3Shard; @@ -300,3 +299,41 @@ test "tfq3 format validates PWV3, TFPN, and TFPW headers and rejects corruption" try std.testing.expectEqual(@as(u32, 3), pw.metas[0].b_bits); try std.testing.expectError(error.InvalidTfq3Shard, validateTfpw(tfpw, 2, 128, 128, null)); } + +test "CUDA TFQ3: a TFPW expert's three 4-bit alignments are checked before any of its bounds" { + const at = @as(usize, @intCast(section_align)); + const buf = try std.testing.allocator.alloc(u8, 4 * at); // weights at 32 KiB: 3 x 2048 words + defer std.testing.allocator.free(buf); + @memset(buf, 0); + const gw = tensorWords(128, 128, 4); + var h = std.mem.zeroes(TfpwHeader); + h.magic = magic_tfpw; + h.version = format_version; + h.num_experts = 1; + h.num_tensors = 3; + h.hidden_size = 128; + h.moe_inter = 128; + h.stream_words = 3 * gw; + h.scale_halfs = 3; + h.off_meta = @sizeOf(TfpwHeader); + h.off_scales = section_align; + h.off_weights = 2 * section_align; + @memcpy(buf[0..@sizeOf(TfpwHeader)], std.mem.asBytes(&h)); + var em = std.mem.zeroes(TfpwExpertMeta); + em.b_bits = 4; + em.up_word_off = gw; + em.down_word_off = 2 * gw; + em.up_sc_off = 1; + em.down_sc_off = 2; + const meta = buf[@sizeOf(TfpwHeader)..][0..@sizeOf(TfpwExpertMeta)]; + @memcpy(meta, std.mem.asBytes(&em)); + _ = try validateTfpw(buf, 1, 128, 128, null); + // gate on a uint4 but past the words, up off one: Flash Next's per-projection order refuses this as truncated + em.gate_word_off = 3 * gw; + em.up_word_off = gw + 1; + @memcpy(meta, std.mem.asBytes(&em)); + try std.testing.expectError(error.MisalignedTfq3Tensor, validateTfpw(buf, 1, 128, 128, null)); + em.up_word_off = gw; + @memcpy(meta, std.mem.asBytes(&em)); + try std.testing.expectError(error.InvalidTfq3Shard, validateTfpw(buf, 1, 128, 128, null)); +} diff --git a/zig/src/families/flashnext/tfq3_check.zig b/zig/src/families/flashnext/tfq3_check.zig index 414d7434aab..e9543df6d6e 100644 --- a/zig/src/families/flashnext/tfq3_check.zig +++ b/zig/src/families/flashnext/tfq3_check.zig @@ -29,8 +29,7 @@ pub const Error = error{ Tfq3Table, // TFQ3 shards without the shared table, or a table too short or not version 3 }; -/// A byte range of a file: [off, off + len). -pub const Span = struct { off: usize, len: usize }; +pub const Span = format.Span; /// A checked shard: its three sections, their extents in words and halfs, and the 5-bit routed specialization. pub const Layout = struct { meta: Span, scales: Span, weights: Span, words: usize, halfs: usize, has_5b: bool = false }; @@ -75,17 +74,13 @@ pub fn header(head: []const u8, file_len: usize, want_layer: ?u32) Error!Layout .words = words, .halfs = halfs, }; - const all = [_]Span{ out.meta, out.scales, out.weights }; - for (all, 0..) |a, i| { - if (a.len > 0 and a.off < @sizeOf(LayerHeader)) return error.Tfq3Overlap; - for (all[i + 1 ..]) |b| if (a.len > 0 and b.len > 0 and a.off < b.off + b.len and b.off < a.off + a.len) return error.Tfq3Overlap; - } + if (format.overlaps(@sizeOf(LayerHeader), &.{ out.meta, out.scales, out.weights })) return error.Tfq3Overlap; return out; } /// Words of an R x C matrix at `bits` (16-row strips of 128-column blocks, bits * 2 words a lane) and its halfs. pub fn matWords(r: usize, c: usize, bits: usize) Error!usize { - return try mul(try mul(r, c), bits) / 32; + return format.matWords(r, c, bits) orelse error.Tfq3Overflow; } pub fn matScales(r: usize, c: usize) usize { @@ -97,14 +92,14 @@ pub fn experts(meta: []const u8, l: *Layout) Error!void { if (meta.len < l.meta.len) return error.Tfq3Truncated; for (0..num_experts) |e| { const m = try read(ExpertMeta, meta, e * @sizeOf(ExpertMeta)); - if (m.b_bits < 3 or m.b_bits > 5) return error.Tfq3Bits; + if (!format.validBits(m.b_bits)) return error.Tfq3Bits; l.has_5b = l.has_5b or m.b_bits == 5; const io = [3][2]usize{ .{ moe_inter, hidden_size }, .{ moe_inter, hidden_size }, .{ hidden_size, moe_inter } }; const w_offs = [3]u64{ m.gate_word_off, m.up_word_off, m.down_word_off }; const s_offs = [3]u32{ m.gate_sc_off, m.up_sc_off, m.down_sc_off }; for (io, w_offs, s_offs) |rc, wo, so| { // 4-bit words are read four at a time as uint4 (moe_mv, prefill); 3/5-bit words and scales one at a time - if (m.b_bits == 4 and wo % 4 != 0) return error.Tfq3Misaligned; + if (format.uint4Misaligned(m.b_bits, wo)) return error.Tfq3Misaligned; if (try add(try cast(wo), try matWords(rc[0], rc[1], m.b_bits)) > l.words) return error.Tfq3Truncated; if (try add(so, matScales(rc[0], rc[1])) > l.halfs) return error.Tfq3Truncated; } diff --git a/zig/src/families/flashnext/tfq3_check_test.zig b/zig/src/families/flashnext/tfq3_check_test.zig index 132d67a32bd..52c2596dcec 100644 --- a/zig/src/families/flashnext/tfq3_check_test.zig +++ b/zig/src/families/flashnext/tfq3_check_test.zig @@ -198,3 +198,13 @@ test "Flash Next TFQ3 check: a 4-bit projection's words start on the 16 bytes th _ = try check.layer(shard(buf, header(3), odd), 3); } } + +test "Flash Next TFQ3 check: each projection is checked whole before the next, so a gate past its section wins" { + const buf = try t.allocator.alloc(u8, file_len); + defer t.allocator.free(buf); + // gate on a uint4 but past the words, up off one: CUDA's all-alignments-first order refuses this as misaligned + var e = expert(4); + e.gate_word_off = 3 * proj_words; + e.up_word_off += 1; + try t.expectError(error.Tfq3Truncated, check.layer(shard(buf, header(3), e), 3)); +} diff --git a/zig/src/families/glm/tfq3_check.zig b/zig/src/families/glm/tfq3_check.zig index c31397a042b..0f8a4174d8f 100644 --- a/zig/src/families/glm/tfq3_check.zig +++ b/zig/src/families/glm/tfq3_check.zig @@ -55,8 +55,7 @@ pub const Error = error{ Tfq3TensorParallel, // TFQ3 files with --tp: their records are whole tensors, never a rank's share }; -/// A byte range of a file: [off, off + len). -pub const Span = struct { off: usize, len: usize }; +pub const Span = format.Span; fn cast(v: u64) Error!usize { return std.math.cast(usize, v) orelse error.Tfq3Overflow; @@ -91,13 +90,7 @@ pub fn span(file_len: usize, off: u64, len: usize, gpu: bool) Error!Span { /// Refuses spans that share a byte; `head` is the fixed header's length, which no section may cover. pub fn disjoint(head: usize, spans: []const Span) Error!void { - for (spans, 0..) |a, i| { - if (a.len > 0 and a.off < head) return error.Tfq3Overlap; - for (spans[i + 1 ..]) |b| { - if (a.len == 0 or b.len == 0) continue; - if (a.off < b.off + b.len and b.off < a.off + a.len) return error.Tfq3Overlap; - } - } + if (format.overlaps(head, spans)) return error.Tfq3Overlap; } fn read(comptime T: type, bytes: []const u8, off: usize) Error!T { @@ -125,7 +118,7 @@ pub const NonMoeLayout = struct { metas: Span, count: usize, scales: Span, weigh /// Words of an R x C TFQ3 matrix at `bits`, and its half scales (one a 128 x 128 block). pub fn matWords(r: usize, c: usize, bits: usize) Error!usize { - return try mul(try mul(r, c), bits) / 32; + return format.matWords(r, c, bits) orelse error.Tfq3Overflow; } pub fn matScales(r: usize, c: usize) Error!usize { From 9c219920744373e10c423cbf5b23d84dfc0cc07d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:54:05 +0100 Subject: [PATCH 2/4] core tfq3 arith test: the 2^32 and 2^33 edges only on a 64-bit usize, so the test compiles for x86-linux --- zig/src/core/tfq3_arith_test.zig | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/zig/src/core/tfq3_arith_test.zig b/zig/src/core/tfq3_arith_test.zig index ab8972e4d7a..75fcd5df36e 100644 --- a/zig/src/core/tfq3_arith_test.zig +++ b/zig/src/core/tfq3_arith_test.zig @@ -36,7 +36,10 @@ fn mainGlmOverlap(head: usize, spans: []const f.Span) bool { return false; } -const dims = [_]usize{ 0, 1, 2, 15, 16, 17, 31, 32, 33, 127, 128, 129, 640, 2048, 2560, 4096, max(u16), max(u32) - 1, max(u32), 1 << 32, 1 << 33, max(usize) / 32, max(usize) / 5, max(usize) / 4, max(usize) / 3, max(usize) / 2, max(usize) - 1, max(usize) }; +const wide = @bitSizeOf(usize) >= 64; // the 2^32 and 2^33 edges only exist on 64-bit usize (x86-linux is 32-bit) +const dims = [_]usize{ 0, 1, 2, 15, 16, 17, 31, 32, 33, 127, 128, 129, 640, 2048, 2560, 4096, max(u16), max(u32) - 1, max(u32) } ++ + (if (wide) [_]usize{ 1 << 32, 1 << 33 } else [_]usize{}) ++ + [_]usize{ max(usize) / 32, max(usize) / 5, max(usize) / 4, max(usize) / 3, max(usize) / 2, max(usize) - 1, max(usize) }; const widths = [_]usize{ 0, 1, 2, 3, 4, 5, 6, 8, 16, 32, max(u32), max(usize) }; test "TFQ3 arithmetic: matWords equals main's checked body on every edge, null exactly where main refused" { @@ -50,8 +53,10 @@ test "TFQ3 arithmetic: matWords equals main's checked body on every edge, null e try t.expectEqual(@as(?usize, 0), f.matWords(1, 7, 4)); // floor: 28 bits are no whole word try t.expectEqual(@as(?usize, 1), f.matWords(1, 8, 4)); try t.expectEqual(@as(?usize, 274), f.matWords(17, 129, 4)); // off the 16 x 128 grid (CUDA's tensorWords: 256) - try t.expectEqual(@as(?usize, null), f.matWords(1 << 33, 1 << 33, 0)); // R * C overflows: refused though bits is 0 - try t.expectEqual(@as(?usize, null), f.matWords(1 << 62, 1, 4)); // the second product overflows; / 32 would fit + const half: usize = 1 << (@bitSizeOf(usize) / 2 + 1); + try t.expectEqual(@as(?usize, null), f.matWords(half, half, 0)); // R * C overflows: refused though bits is 0 + const quarter: usize = 1 << (@bitSizeOf(usize) - 2); + try t.expectEqual(@as(?usize, null), f.matWords(quarter, 1, 4)); // the second product overflows; / 32 would fit try t.expectEqual(@as(?usize, max(usize) / 32), f.matWords(max(usize), 1, 1)); } From d6b4b7dcfe867937a5d1fe0b89e25f57740b7d6d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:44:09 +0000 Subject: [PATCH 3/4] changelog: #5341 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7861f35a3a9..d4d3d253af4 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 +- TFQ3: Flash Next, GLM and the other TFQ3 readers share one copy of the format's span, overlap and packed-size arithmetic in `core/tfq3_format.zig` (format move, piece 2); results and refusals are unchanged (#5341). Thanks @jschmied. + - CUDA: Qwen with `--kv-cache fp8` gives the same tokens with the default `TF_QWEN_PDL` on as with it off; the FP8 RoPE kernel no longer starts before its head norms finish (#PR, fixes #5308). Thanks to @jojomondag for the report. - Tools: a device check that drafted output equals plain output under seeded sampling, on Metal and CUDA, for releases and PR qualification (#5249). From 8e69512ddc1c92215ba3e2a383b73961c5f897d7 Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:03:23 +0900 Subject: [PATCH 4/4] cuda: the shared router tiles read their shared-memory rows as 32-bit words tiles() in common/router_tiles.cuh read each 16-byte row of its shared-memory tiles as one uint4; it now reads the row as four 32-bit words. With the uint4 reads, nvcc 13.0.88 and 13.3.73 on GB10 emitted more than one PTX form for the router-tiles entries across compiles of the same source, some with another image. With the word reads, every compile measured gave one form, and the images, register counts and router contract results are main's. The #5157 note in docs/recipes/cuda-sass-identity.md records this, scoped to the three router-tiles entries, those two releases and the hosts measured. gradient-serving.tsv pins the new header, and a source test in tools/zig/test_cuda_sources.py holds the word reads. --- CHANGELOG.md | 2 ++ docs/recipes/cuda-sass-identity.md | 8 ++++++++ tools/zig/test_cuda_sources.py | 9 +++++++++ zig/kernels/cuda/common/router_tiles.cuh | 6 ++++-- zig/tests/fixtures/gradient-serving.tsv | 2 +- 5 files changed, 24 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4d3d253af4..e21ec2e2c22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -122,6 +122,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Metal kernels: Step-5's `s5_embed`, MiniMax-M3's `mm_embed` and Spark2.5's `sp_embed` take their affine-quantized embedding row from one macro; each shader's compiler-visible tokens are identical to before (#5203, refs #2251). +- CUDA kernels: the shared router tiles (`common/router_tiles.cuh`) read each 16-byte shared-memory row as four 32-bit words, which gave `tf_moe_router_tiles`, `tf_nemo_router_tiles` and the router control one PTX form in every compile measured on GB10 and x86-64 with nvcc 13.0.88 and 13.3.73; their images, register counts and outputs are unchanged (#5360, refs #5123, #5157). + ## 1.3.6 diff --git a/docs/recipes/cuda-sass-identity.md b/docs/recipes/cuda-sass-identity.md index c89fd3cbcad..d1684228947 100644 --- a/docs/recipes/cuda-sass-identity.md +++ b/docs/recipes/cuda-sass-identity.md @@ -45,6 +45,14 @@ compiles and 9 of 50 `compute_86` compiles on GB10. The `compute_80` alternates The same 13.3.73 wheels on x86-64 gave one form in 100 and in 50; the earlier x86-64 nvcc 13.0.88 control did too. The instability is not 13.0-only: it appeared on GB10 with both compiler versions, not on those x86-64 controls. +The observations above are of `common/router_tiles.cuh` reading each 16-byte shared-memory row as one `uint4`. +Reading it as four 32-bit words, `tf_moe_router_tiles`, `tf_nemo_router_tiles` and `tf_ctl_moe_router_tiles_row` +each gave one PTX form in every compile measured: at `compute_80` and `compute_86` with nvcc 13.0.88 and 13.3.73 +on GB10, with randomization enabled and disabled; at `compute_89`, `compute_120` and `compute_121` with 13.0.88 on +one GB10 and 13.3.73 on another, with randomization enabled; and on x86-64. Their images equal the common form's +at sm_80, 86, 89, 120 and 121 with both releases, so the records keep their register counts. This is observed for +those entries, releases and hosts, not established by construction. + An unstable rebuild is a qualification failure, not evidence of an arithmetic difference. The reported comparison did not compare every PTX operand or run the forms against each other on a GPU. Do not change a record's common value because one rebuild differs. diff --git a/tools/zig/test_cuda_sources.py b/tools/zig/test_cuda_sources.py index 53e4adcab83..7b7fdecbd24 100644 --- a/tools/zig/test_cuda_sources.py +++ b/tools/zig/test_cuda_sources.py @@ -90,5 +90,14 @@ def test_layout_rejects_wrong_coordinate(self): self.assertIn("static assertion failed", result.stderr) +class RouterTilesLoads(unittest.TestCase): + def test_staged_rows_are_read_as_words(self): + text = (check.ROOT / "zig/kernels/cuda/common/router_tiles.cuh").read_text() + self.assertNotIn("reinterpret_cast(xs +", text) + self.assertNotIn("reinterpret_cast(ws +", text) + self.assertIn("xv[i] = uint4{xp[0], xp[1], xp[2], xp[3]};", text) + self.assertIn("wv[i] = uint4{wp[0], wp[1], wp[2], wp[3]};", text) + + if __name__ == "__main__": unittest.main() diff --git a/zig/kernels/cuda/common/router_tiles.cuh b/zig/kernels/cuda/common/router_tiles.cuh index 214323b58d0..4948f472a3b 100644 --- a/zig/kernels/cuda/common/router_tiles.cuh +++ b/zig/kernels/cuda/common/router_tiles.cuh @@ -60,8 +60,10 @@ __device__ __forceinline__ void tiles(const __nv_bfloat16* __restrict__ X, const uint4 xv[8], wv[8]; #pragma unroll for (int i = 0; i < 8; ++i) { - xv[i] = *reinterpret_cast(xs + (ty + 16 * i) * TS + 4 * q); - wv[i] = *reinterpret_cast(ws + (tx + 16 * i) * TS + 4 * q); + const uint32_t* xp = xs + (ty + 16 * i) * TS + 4 * q; + const uint32_t* wp = ws + (tx + 16 * i) * TS + 4 * q; + xv[i] = uint4{xp[0], xp[1], xp[2], xp[3]}; + wv[i] = uint4{wp[0], wp[1], wp[2], wp[3]}; } #pragma unroll for (int w = 0; w < 4; ++w) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 31986beb487..a017a3024a8 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -53,7 +53,7 @@ zig/kernels/cuda/probe.cu 94a3118894b3066e0f0f6fc1cfc3c03828d291077cb26c437b62fc zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt zig/kernels/cuda/qmm.cu a55a9d00d9097c5f5bd88c8c538a0481fe13b37badd2e3faf4cdde9c86c9f93d raw zig/kernels/cuda/common/qmm_frag.cuh 418dce9d64df0b8751c8ca982ae3f93c5fc54e4aecb9a8df3f0780129dcb675a raw -zig/kernels/cuda/common/router_tiles.cuh aab559bf104e3f47344deaa9ae10622b6962b8a77b398f572ba974055dfafd3c raw +zig/kernels/cuda/common/router_tiles.cuh 4821df3837800da846781f4942c6e1239e35742272249df5a0915b37110813f3 raw zig/kernels/cuda/common/router_mma.cuh 3aca244a38f2e4b4f28bf74f333f384b1060b764c25b004cef4e6c636e7cc1dd raw zig/kernels/cuda/qmm_group.cu 8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0 raw zig/kernels/cuda/qmm_prefill.cu e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6 raw #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel