Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -120,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

Expand Down
8 changes: 8 additions & 0 deletions docs/recipes/cuda-sass-identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions tools/zig/test_cuda_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<const uint4*>(xs +", text)
self.assertNotIn("reinterpret_cast<const uint4*>(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()
6 changes: 4 additions & 2 deletions zig/kernels/cuda/common/router_tiles.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -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<const uint4*>(xs + (ty + 16 * i) * TS + 4 * q);
wv[i] = *reinterpret_cast<const uint4*>(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)
Expand Down
106 changes: 106 additions & 0 deletions zig/src/core/tfq3_arith_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//! 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 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" {
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)
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));
}

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, &.{}));
}
33 changes: 32 additions & 1 deletion zig/src/core/tfq3_format.zig
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -70,4 +100,5 @@ comptime {

test {
_ = @import("tfq3_format_test.zig");
_ = @import("tfq3_arith_test.zig");
}
47 changes: 42 additions & 5 deletions zig/src/cuda/tfq3_format.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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));
}
15 changes: 5 additions & 10 deletions zig/src/families/flashnext/tfq3_check.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -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 {
Expand All @@ -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;
}
Expand Down
10 changes: 10 additions & 0 deletions zig/src/families/flashnext/tfq3_check_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Loading
Loading