diff --git a/docs/recipes/flash-next-cuda.md b/docs/recipes/flash-next-cuda.md index b0ee2602f2a..eb62c6211ec 100644 --- a/docs/recipes/flash-next-cuda.md +++ b/docs/recipes/flash-next-cuda.md @@ -19,6 +19,15 @@ contract receipts. Compile success and host tests do not establish checkpoint fi limits must be measured with the exact checkpoint, binary, device topology and request settings. Prefix retention with MTP is outside this path's qualified scope; evaluate with `--prompt-cache-gib 0`. +A projection whose parts are block FP8 (e4m3 codes with an fp32 `weight_scale_inv` a 128 x 128 block) loads as stored +on the FP8G lane: its leading parts stack row for row into one packed weight whose rows past them are zero codes with +a scale of one, and a trailing BF16 part, such as an indexer projection stored beside block-FP8 q, k and v or the +DeltaNet in-projection's 48-row `in_proj_b` and `in_proj_a` beside its block-FP8 qkv and z, is held as the exact rows +a second BF16 matmul computes and copied into their columns after the lane's. The tail's rows need not fill a 128-row +block: a tail row is a zero code on the lane, so its product there is a zero that the copy replaces, and the +packers zero and one-fill the rows past the projection's own. A projection storing an MXFP8 `weight_scale` or affine +words is not this arm and takes the reader it took before. + ### NVIDIA's NVFP4 checkpoint on two GB10s `nvidia/Qwen3.8-Flash-Next-NVFP4` (the checkpoint SGLang's Flash Next recipes serve) loads as stored: NVFP4 routed diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 35d165e1a85..07f6ada7a61 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -277,6 +277,9 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/cuda.zig"), .target = host, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = mods.core } } }) })).step); @import("flashnext_glue_host.zig").steps(b, cuda, mods.core, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), step); @import("flashnext_scoring_host.zig").steps(b, cuda, mods.core, mods.lanes, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), step); + const block_fp8 = b.addRunArtifact(b.addTest(.{ .root_module = flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), .filters = &.{"block FP8:"} })); + b.step("test-flashnext-block-fp8-host", "Block-FP8 projections and their BF16 tail on the FP8G lane, without a device").dependOn(&block_fp8.step); + step.dependOn(&block_fp8.step); b.step("test-pocket-device-host", "Actual pocket device hooks under CUDA ABI failures").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), .filters = &.{"Learning persistence:"} })).step); b.step("test-flashnext-readout-fused-host", "The fused read-out's down tile choice and its refusals by name, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), .filters = &.{"fused read-out:"} })).step); b.step("test-living-host", "Family-neutral learner, saved form and commit gate on host").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.living })).step); diff --git a/zig/src/families/flashnext/cuda_batch.zig b/zig/src/families/flashnext/cuda_batch.zig index d0f693fc858..a0fbfa769b4 100644 --- a/zig/src/families/flashnext/cuda_batch.zig +++ b/zig/src/families/flashnext/cuda_batch.zig @@ -29,7 +29,6 @@ const low = wt.low; const eps = wt.eps; const vocab = wt.vocab; const experts_n = wt.experts_n; -const slots = wt.slots; const moe_w = wt.moe_w; const tile = wt.tile; const head_dim = wt.head_dim; @@ -129,6 +128,15 @@ pub fn Pass(comptime Tri: type) type { /// qmm.cu's arithmetic over m rows into out (bf16) or part (fp32 K slices); returns the slices (1 when folded). pub fn lane(self: *Self, x: u64, xs: u64, w: Q4, out: u64, part: u64, m: usize, sk: usize) !usize { + if (w.tail) |t| { + // the FP8G rows over the whole output, its zero rows where the tail goes, then the tail copied in + if (sk != 1) return error.UnexpectedTensor; + const used = try tiles.matmul(self.k, self.stream, x, xs, w, out, part, self.s.native_part, m, sk); + if (used != 1) return error.UnexpectedTensor; + try self.k.nativeMatmul(self.stream, x, w.k, m, t.native, self.s.tail, self.s.native_part, .bf16); + try ops.copyCols(self.k, self.stream, self.s.tail, t.n, out + t.at * 2, w.n, t.n, m); + return 1; + } if (try zs.lane(self.k, self.stream, self.s, self.zero_slices, x, w, part, m, sk)) |one| return one; return tiles.matmul(self.k, self.stream, x, xs, w, out, part, self.s.native_part, m, sk); } @@ -180,9 +188,9 @@ pub fn Pass(comptime Tri: type) type { try self.tri.hcWriteback(h, h, pss, s.moe_f32 + r0 * dims * 4, "*fp32", inj, dummy, "*bf16", dummy, "*bf16", rs, n, dims, streams, 4, 1, 1, 1); return; } - const y = s.y + r0 * slots * dims * 4; - const wts = s.wts + r0 * slots * 4; - try self.tri.hcWriteback(h, h, pss, dummy, "*bf16", inj, y, "*fp32", wts, "*fp32", rs, n, dims, streams, 2, 10, 11, 1); + const y = s.y + r0 * s.slots * dims * 4; + const wts = s.wts + r0 * s.slots * 4; + try self.tri.hcWriteback(h, h, pss, dummy, "*bf16", inj, y, "*fp32", wts, "*fp32", rs, n, dims, streams, 2, s.slots - 1, s.slots, 1); } /// A read-out over rows [r0, r0 + n) of the streams: mixed and its group sums, and the inject gates. @@ -441,10 +449,10 @@ pub fn Pass(comptime Tri: type) type { pub fn moeBlockKeep(self: *Self, lw: *const Layer, keep: LayerKeep) !void { const s = self.s; const n = self.rows; - const pairs = n * slots; + const pairs = n * s.slots; try self.copy(keep.moe_x, s.mixed, n * dims * 2); try self.tri.routerMany(s.mixed, lw.router.ptr, s.router_l, dims, n); - try self.tri.topkMany(s.router_l, s.picks, s.wts, n); + try self.tri.topkMany(s.router_l, s.picks, s.wts, n, s.slots); try self.copy(keep.moe_ids, s.picks, pairs * 4); try self.copy(keep.moe_wts, s.wts, pairs * 4); const e = experts_n + 1; @@ -454,13 +462,13 @@ pub fn Pass(comptime Tri: type) type { // prompt rows on 64-pair factored tiles, expert_rows' bits try self.k.router.route(self.stream, s.picks, pairs, e, tk.fexp_tile, plan); const items64 = cdiv(pairs, tk.fexp_tile) + e; - try tiles.experts(self.stream, self.k.tiles.fexp_up, 2, s.mixed, dims, slots, lw.experts_up.ptr, dims / 32, moe_w / 32, plan, s.moe_act, moe_w, items64); + try tiles.experts(self.stream, self.k.tiles.fexp_up, 2, s.mixed, dims, s.slots, lw.experts_up.ptr, dims / 32, moe_w / 32, plan, s.moe_act, moe_w, items64); try tiles.experts(self.stream, self.k.tiles.fexp_down, 4, s.moe_act, moe_w, 0, lw.experts_down.ptr, moe_w / 32, dims / 32, plan, s.y, dims, items64); return; } try self.k.router.route(self.stream, s.picks, pairs, e, rows_tile, plan); const items = cdiv(pairs, rows_tile) + e; - try self.k.moe.run(self.stream, true, s.mixed, dims, slots, lw.experts_up.ptr, dims / 32, moe_w / 32, plan, s.moe_act, moe_w, items); + try self.k.moe.run(self.stream, true, s.mixed, dims, s.slots, lw.experts_up.ptr, dims / 32, moe_w / 32, plan, s.moe_act, moe_w, items); try self.k.moe.run(self.stream, false, s.moe_act, moe_w, 0, lw.experts_down.ptr, moe_w / 32, dims / 32, plan, s.y, dims, items); } diff --git a/zig/src/families/flashnext/cuda_batch_hc.zig b/zig/src/families/flashnext/cuda_batch_hc.zig index 312f9898cc6..e9fd6cb1a87 100644 --- a/zig/src/families/flashnext/cuda_batch_hc.zig +++ b/zig/src/families/flashnext/cuda_batch_hc.zig @@ -8,7 +8,6 @@ const dims = wt.dims; const streams = wt.streams; const wide = wt.wide; const low = wt.low; -const slots = wt.slots; const eps = wt.eps; const pss_n = (dims / 256) * streams; @@ -45,9 +44,9 @@ pub fn writebackNorm(pass: anytype, hc_w: wt.HcW, r0: usize, n: usize) !void { pass.pending_f32 = false; return pass.tri.hcWritebackNorm(h, h, pss, s.moe_f32 + r0 * dims * 4, inj, dummy, dummy, scale, norm, eps, rs, n, dims, streams, 4, 1, 1, 1); } - const y = s.y + r0 * slots * dims * 4; - const wts = s.wts + r0 * slots * 4; - try pass.tri.hcWritebackNorm(h, h, pss, dummy, inj, y, wts, scale, norm, eps, rs, n, dims, streams, 2, 10, 11, 1); + const y = s.y + r0 * s.slots * dims * 4; + const wts = s.wts + r0 * s.slots * 4; + try pass.tri.hcWritebackNorm(h, h, pss, dummy, inj, y, wts, scale, norm, eps, rs, n, dims, streams, 2, s.slots - 1, s.slots, 1); } /// A native read-out over rows [r0, r0 + n) whose normed rows are in: down, act and gates, up, the mix. diff --git a/zig/src/families/flashnext/cuda_batch_head.zig b/zig/src/families/flashnext/cuda_batch_head.zig index a20a788bb42..56cdd840795 100644 --- a/zig/src/families/flashnext/cuda_batch_head.zig +++ b/zig/src/families/flashnext/cuda_batch_head.zig @@ -7,7 +7,6 @@ const HcKeep = batch.HcKeep; const dims = wt.dims; const wide = wt.wide; const streams = wt.streams; -const slots = wt.slots; const vocab = wt.vocab; const pss_n = batch.pss_n; pub fn head(self: anytype, logits_host: ?[]u8) !void { @@ -59,8 +58,8 @@ pub fn head(self: anytype, logits_host: ?[]u8) !void { try self.copy(s.h, s.h + r * wide * 2, wide * 2); try self.copy(s.pss, s.pss + r * pss_n * 4, pss_n * 4); try self.copy(s.inj, s.inj + r * streams * 2, streams * 2); - try self.copy(s.y, s.y + r * slots * dims * 4, slots * dims * 4); - try self.copy(s.wts, s.wts + r * slots * 4, slots * 4); + try self.copy(s.y, s.y + r * s.slots * dims * 4, s.slots * dims * 4); + try self.copy(s.wts, s.wts + r * s.slots * 4, s.slots * 4); if (self.pending_f32) try self.copy(s.moe_f32, s.moe_f32 + r * dims * 4, dims * 4); } if (self.hooks.streams == 0) try self.writeback(0, 1); diff --git a/zig/src/families/flashnext/cuda_batch_moe.zig b/zig/src/families/flashnext/cuda_batch_moe.zig index 992607e5f87..847288d20f8 100644 --- a/zig/src/families/flashnext/cuda_batch_moe.zig +++ b/zig/src/families/flashnext/cuda_batch_moe.zig @@ -4,7 +4,6 @@ const wt = @import("cuda_prompt_wt.zig"); const batch = @import("cuda_batch.zig"); const LayerKeep = batch.LayerKeep; const dims = wt.dims; -const slots = wt.slots; /// After a layer's experts, when something adds to or keeps its output: the slots' fp32 sum, adds, kept branch. pub fn moeAdds(self: anytype, layer: usize, keep: LayerKeep) !void { @@ -23,10 +22,10 @@ pub fn moeAdds(self: anytype, layer: usize, keep: LayerKeep) !void { pub fn sumSlots(self: anytype, r0: usize, rows: usize) !void { const s = self.s; var a: cuda.Args = .{}; - a.add(s.y + r0 * slots * dims * 4); - a.add(s.wts + r0 * slots * 4); + a.add(s.y + r0 * s.slots * dims * 4); + a.add(s.wts + r0 * s.slots * 4); a.add(s.moe_f32 + r0 * dims * 4); a.add(batch.cint(dims)); - a.add(batch.cint(slots)); + a.add(batch.cint(s.slots)); try cuda.launch.launch(self.k.moe_sum, .{ .grid = .{ .x = @intCast(rows), .y = dims / 256 }, .block = .{ .x = 256 } }, self.stream, &a); } diff --git a/zig/src/families/flashnext/cuda_batch_side.zig b/zig/src/families/flashnext/cuda_batch_side.zig index 282557604aa..7043f96c486 100644 --- a/zig/src/families/flashnext/cuda_batch_side.zig +++ b/zig/src/families/flashnext/cuda_batch_side.zig @@ -4,8 +4,6 @@ const cuda = @import("cuda"); const wt = @import("cuda_prompt_wt.zig"); const dims = wt.dims; -const slots = wt.slots; -const moe_w = wt.moe_w; /// On by default: its slot rows of y are apart from the routed experts', so the bits match; =0 runs it after them. pub fn on() bool { @@ -40,7 +38,7 @@ pub fn run(pass: anytype, st: cuda.Stream, native: anytype, n: usize) !void { const glue = pass.tri.own orelse return error.NativeGlueRequired; try pass.k.nativeMatmul(st, s.mixed, dims, n, native.shared[0].native.?, s.shared_gate, s.native_part, .bf16); try pass.k.nativeMatmul(st, s.mixed, dims, n, native.shared[1].native.?, s.shared_up, s.native_part, .bf16); - try glue.sharedSwiGLU(st, s.shared_gate, s.shared_up, s.shared_act, n, moe_w); + try glue.sharedSwiGLU(st, s.shared_gate, s.shared_up, s.shared_act, n, native.shared_width); try down(pass, st, s.shared_act, native, n); } @@ -48,11 +46,11 @@ pub fn run(pass: anytype, st: cuda.Stream, native: anytype, n: usize) !void { pub fn down(pass: anytype, st: cuda.Stream, input: u64, native: anytype, n: usize) !void { const s = pass.s; const w = native.shared[2].native.?; - if (w.n == dims and cuda.qmmf_shared.eligible(pass.k.native_lane, n, w, moe_w, slots * dims)) - return pass.k.native_lane.matmulF32Strided(st, input, moe_w, n, w, s.y + (slots - 1) * dims * 4, slots * dims); + if (w.n == dims and cuda.qmmf_shared.eligible(pass.k.native_lane, n, w, native.shared_width, s.slots * dims)) + return pass.k.native_lane.matmulF32Strided(st, input, native.shared_width, n, w, s.y + (s.slots - 1) * dims * 4, s.slots * dims); const glue = pass.tri.own orelse return error.NativeGlueRequired; - try pass.k.nativeMatmul(st, input, moe_w, n, w, s.shared_out, s.native_part, .f32); - try glue.sharedScatter(st, s.shared_out, s.y, n, dims, slots); + try pass.k.nativeMatmul(st, input, native.shared_width, n, w, s.shared_out, s.native_part, .f32); + try glue.sharedScatter(st, s.shared_out, s.y, n, dims, s.slots); } /// After y is cleared: the shared expert forked onto the side stream (one GPU, not a prompt fill), or null. diff --git a/zig/src/families/flashnext/cuda_batch_state.zig b/zig/src/families/flashnext/cuda_batch_state.zig index 30f047ff104..6c122af75e8 100644 --- a/zig/src/families/flashnext/cuda_batch_state.zig +++ b/zig/src/families/flashnext/cuda_batch_state.zig @@ -240,6 +240,8 @@ const partRows = sizes.partRows; /// Device scratch for chunks of up to `cap` rows. pub const Scratch = struct { cap: usize, + /// A row's expert slots: the checkpoint's top-k and the shared one. + slots: usize = slots, /// The shared expert's stream (cuda_batch_side.zig); null: it runs after the routed experts on the pass's stream. side: ?shared.Side = null, bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, @@ -301,6 +303,7 @@ pub const Scratch = struct { shared_up: u64 = 0, shared_act: u64 = 0, shared_out: u64 = 0, + tail: u64 = 0, // a block-FP8 projection's BF16 tail rows [cap, tail_n] before they are copied into place y: u64 = 0, branch: u64 = 0, /// A layer's MoE output in fp32 [cap + 1, dims] when something adds to it, and the pocket's activations [cap, 128]. @@ -379,7 +382,7 @@ pub const Scratch = struct { /// Bytes `alloc(cap)` takes on the device. pub fn bytes(cap: usize, z: Sizes) usize { const head_rows = z.head_rows; - const pairs = cap * slots; + const pairs = cap * z.slots; const nblk = cdiv(pairs, plan_small); const items = cdiv(pairs, tile) + experts_n + 1; var n: usize = 0; @@ -393,8 +396,8 @@ pub const Scratch = struct { n += att_rows * nch * q_heads * (head_dim + 2) * 4 + cap * out_k * 2 * 2 + cap * (out_k / 32) * 4; n += fused_rows * (idw + 2) * 4 + lanes_bytes; n += cap * (experts_n + 1) * 4 + pairs * 4 * 2 + pairs * 4 + items * 3 * 4 + 8 + pairs * 4 + nblk * (experts_n + 1) * 4 + pairs * 4; - n += cap * moe_w * 6 + cap * dims * 4; - n += pairs * moe_w * 2 + (pairs + slots) * dims * 4 + cap * dims * 2; + n += cap * z.shared * 6 + cap * dims * 4 + cap * wt.tail_n * 2; + n += pairs * moe_w * 2 + (pairs + z.slots) * dims * 4 + cap * dims * 2; n += cap * dims * 2 + cap * (dims / 32) * 4 + cap * wide * 2 + cap * dims * 2 + 4 * cap * dims * 4; n += cap * wide * 2 * 2 + cap * streams * 4 + vocab * 2 + head_rows * vocab + half * 4 + 4096; n += (cap + 1) * dims * 4 + cap * pocket_stride * 4; @@ -404,12 +407,12 @@ pub const Scratch = struct { pub fn alloc(gpa: std.mem.Allocator, d: *const cuda.Driver, stream: cuda.Stream, cap: usize, z: Sizes) !Scratch { const head_rows = z.head_rows; - var s: Scratch = .{ .cap = cap, .head_rows = head_rows }; + var s: Scratch = .{ .cap = cap, .head_rows = head_rows, .slots = z.slots }; errdefer { cuda.completion.drain(d, stream, "Flash Next scratch work did not drain before rollback"); s.free(gpa); } - const pairs = cap * slots; + const pairs = cap * z.slots; const nblk = cdiv(pairs, plan_small); const items = cdiv(pairs, tile) + experts_n + 1; s.ids = try s.add(gpa, d, cap * 4); @@ -465,12 +468,13 @@ pub const Scratch = struct { s.counts = try s.add(gpa, d, 8); s.rank = try s.add(gpa, d, pairs * 4); s.hist = try s.add(gpa, d, nblk * (experts_n + 1) * 4); - s.shared_gate = try s.add(gpa, d, cap * moe_w * 2); - s.shared_up = try s.add(gpa, d, cap * moe_w * 2); - s.shared_act = try s.add(gpa, d, cap * moe_w * 2); + s.shared_gate = try s.add(gpa, d, cap * z.shared * 2); + s.shared_up = try s.add(gpa, d, cap * z.shared * 2); + s.shared_act = try s.add(gpa, d, cap * z.shared * 2); s.shared_out = try s.add(gpa, d, cap * dims * 4); + s.tail = try s.add(gpa, d, cap * wt.tail_n * 2); s.moe_act = try s.add(gpa, d, pairs * moe_w * 2); - s.y = try s.add(gpa, d, (pairs + slots) * dims * 4); // a spare row: the exchange's odd-row pad + s.y = try s.add(gpa, d, (pairs + z.slots) * dims * 4); // a spare row: the exchange's odd-row pad s.branch = try s.add(gpa, d, cap * dims * 2); s.moe_f32 = try s.add(gpa, d, (cap + 1) * dims * 4); s.pocket_act = try s.add(gpa, d, cap * pocket_stride * 4); diff --git a/zig/src/families/flashnext/cuda_config.zig b/zig/src/families/flashnext/cuda_config.zig index 1054083b322..782bb6e196b 100644 --- a/zig/src/families/flashnext/cuda_config.zig +++ b/zig/src/families/flashnext/cuda_config.zig @@ -3,6 +3,7 @@ const std = @import("std"); const wt = @import("cuda_prompt_wt.zig"); const gdn = @import("cuda_gdn.zig"); +const widths = @import("cuda_widths.zig"); /// One config field and the value the kernels and buffers assume. const Want = struct { name: []const u8, value: i64 }; @@ -17,9 +18,7 @@ const shapes = [_]Want{ .{ .name = "num_key_value_heads", .value = wt.kv_heads }, .{ .name = "head_dim", .value = wt.head_dim }, .{ .name = "num_experts", .value = wt.experts_n }, - .{ .name = "num_experts_per_tok", .value = wt.slots - 1 }, .{ .name = "moe_intermediate_size", .value = wt.moe_w }, - .{ .name = "shared_expert_intermediate_size", .value = wt.moe_w }, .{ .name = "hc_count", .value = wt.streams }, .{ .name = "hc_lowrank", .value = wt.low }, .{ .name = "linear_num_key_heads", .value = gdn.nk }, @@ -97,16 +96,24 @@ pub fn mismatch(text: std.json.ObjectMap, quant: ?std.json.ObjectMap) ?[]const u if (int(q, "bits") != 4) return "quantization.bits"; if (int(q, "group_size") != 32) return "quantization.group_size"; if (q.get("mode")) |m| if (m != .string or !std.mem.eql(u8, m.string, "affine")) return "quantization.mode"; - return geometry(text); + if (geometry(text)) |field| return field; + // the MLX path's experts and captured kernels route top-10 with a 640-wide shared expert only + return if (widthsOf(text).widths.isDefault()) null else "num_experts_per_tok"; +} + +/// The routing and shared widths `text` names: a supported shape, or the field whose value has none. +pub fn widthsOf(text: std.json.ObjectMap) widths.Selected { + return widths.select(int(text, "num_experts_per_tok"), int(text, "shared_expert_intermediate_size"), int(text, learned_key) orelse 0); } fn geometry(text: std.json.ObjectMap) ?[]const u8 { // a folder Living Weights taught widens the shared expert by its pocket (a whole number of groups, 128 at most) const learned = int(text, learned_key) orelse 0; if (learned < 0 or learned > 128 or @mod(learned, 32) != 0) return learned_key; - for (shapes) |w| { - const want = if (std.mem.eql(u8, w.name, "shared_expert_intermediate_size")) w.value + learned else w.value; - if (int(text, w.name) != want) return w.name; + for (shapes) |w| if (int(text, w.name) != w.value) return w.name; + switch (widthsOf(text)) { + .field => |field| return field, + .widths => {}, } return semantics(text); } @@ -200,32 +207,67 @@ fn rope(text: std.json.ObjectMap) ?[]const u8 { /// Reads `dir`/config.json; error.UnsupportedCheckpoint names the field in a log line when one differs. pub fn check(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !void { - _ = try mode(gpa, io, dir); + _ = try read(gpa, io, dir); } pub fn mode(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Mode { - const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); - defer gpa.free(path); - const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 24)); - defer gpa.free(bytes); - const parsed = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + return (try read(gpa, io, dir)).mode; +} + +/// What a checked config.json selects: the quantization's mode and the routing and shared widths. +pub const Checked = struct { mode: Mode, widths: widths.Widths }; + +pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Checked { + const parsed = try parse(gpa, io, dir); defer parsed.deinit(); - if (parsed.value != .object) return error.UnsupportedCheckpoint; const root = parsed.value.object; - const text = if (root.get("text_config")) |v| (if (v == .object) v.object else root) else root; + const text = textOf(root); const quant = if (root.get("quantization")) |v| (if (v == .object) v.object else null) else null; const selected: Mode = if (quant != null) .affine else .modelopt; var field = if (selected == .affine) mismatch(text, quant) else if (object(root, "quantization_config")) |q| modeloptMismatch(text, q) else "quantization"; if (field == null) if (given(root, "tie_word_embeddings")) |v| if (!holds(v, .{ .flag = false })) { field = "tie_word_embeddings"; }; - std.log.err("flashnext: config.json's {s} differs from the supported Flash Next CUDA layout", .{field orelse return selected}); + if (field == null) return .{ .mode = selected, .widths = widthsOf(text).widths }; + std.log.err("flashnext: config.json's {s} differs from the supported Flash Next CUDA layout", .{field.?}); return error.UnsupportedCheckpoint; } +/// The routing and shared widths `dir`/config.json selects; a width outside the supported list is refused by name. +pub fn widthsIn(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !widths.Widths { + const parsed = try parse(gpa, io, dir); + defer parsed.deinit(); + switch (widthsOf(textOf(parsed.value.object))) { + .widths => |w| return w, + .field => |field| { + std.log.err("flashnext: config.json's {s} differs from the supported Flash Next CUDA layout", .{field}); + return error.UnsupportedCheckpoint; + }, + } +} + +fn parse(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !std.json.Parsed(std.json.Value) { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 24)); + defer gpa.free(bytes); + const parsed = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + if (parsed.value != .object) { + parsed.deinit(); + return error.UnsupportedCheckpoint; + } + return parsed; +} + +fn textOf(root: std.json.ObjectMap) std.json.ObjectMap { + return if (root.get("text_config")) |v| (if (v == .object) v.object else root) else root; +} + /// The served config's text fields, as the checked-in checkpoint has them (a test's base to change one at a time). fn served(gpa: std.mem.Allocator, text: *std.json.ObjectMap, rope_params: *std.json.ObjectMap, mtp: *std.json.ObjectMap, kinds: *std.json.Array, ple: *std.json.Array) !void { for (shapes) |w| try text.put(gpa, w.name, .{ .integer = w.value }); + try text.put(gpa, "num_experts_per_tok", .{ .integer = @intCast(widths.default.top_k) }); + try text.put(gpa, "shared_expert_intermediate_size", .{ .integer = @intCast(widths.default.shared) }); try text.put(gpa, "rms_norm_eps", .{ .float = 1e-06 }); try text.put(gpa, "output_gate_type", .{ .string = "sigmoid" }); try text.put(gpa, "hidden_act", .{ .string = "silu" }); @@ -268,6 +310,31 @@ test "the served shapes pass and a 6-bit checkpoint or another width is named" { try std.testing.expectEqualStrings("quantization", mismatch(text, null).?); } +test "a top-5 config with a 1280-wide shared expert selects that shape, and the MLX path refuses it by name" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + var text: std.json.ObjectMap = .empty; + var rope_params: std.json.ObjectMap = .empty; + var mtp: std.json.ObjectMap = .empty; + var kinds: std.json.Array = .init(gpa); + var ple: std.json.Array = .init(gpa); + try served(gpa, &text, &rope_params, &mtp, &kinds, &ple); + try std.testing.expectEqual(widths.default, widthsOf(text).widths); + try text.put(gpa, "num_experts_per_tok", .{ .integer = 5 }); + try text.put(gpa, "shared_expert_intermediate_size", .{ .integer = 1280 }); + try std.testing.expectEqual(@as(?[]const u8, null), geometry(text)); + try std.testing.expectEqual(widths.Widths{ .top_k = 5, .shared = 1280 }, widthsOf(text).widths); + var quant: std.json.ObjectMap = .empty; + try quant.put(gpa, "bits", .{ .integer = 4 }); + try quant.put(gpa, "group_size", .{ .integer = 32 }); + try std.testing.expectEqualStrings("num_experts_per_tok", mismatch(text, quant).?); + try text.put(gpa, "shared_expert_intermediate_size", .{ .integer = 640 }); + try std.testing.expectEqualStrings("shared_expert_intermediate_size", geometry(text).?); + try text.put(gpa, "num_experts_per_tok", .{ .integer = 8 }); + try std.testing.expectEqualStrings("num_experts_per_tok", geometry(text).?); +} + test "a taught folder's wider shared expert passes with its pocket's count, and not without it" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -478,3 +545,7 @@ fn addMxfp8(a: std.mem.Allocator, entries: *std.json.ObjectMap, layer: usize, pr const name = try std.fmt.allocPrint(a, "model.language_model.layers.{d}.{s}.{s}", .{ layer, prefix, part }); try entries.put(a, name, .{ .object = p }); } + +test { + _ = @import("cuda_widths.zig"); +} diff --git a/zig/src/families/flashnext/cuda_glue.zig b/zig/src/families/flashnext/cuda_glue.zig index 9a1b01c41fb..764aea34ac4 100644 --- a/zig/src/families/flashnext/cuda_glue.zig +++ b/zig/src/families/flashnext/cuda_glue.zig @@ -537,9 +537,9 @@ pub const Glue = struct { try g.route.logits(s, x, x_stride, w, out, rows, wt.dims, wt.experts_n + 1); } - /// Each row's ten experts and the shared one: picks and weights [rows, 11] (core route rows). - pub fn topkMany(g: *const Glue, s: cuda.Stream, logits: u64, pick: u64, wts: u64, rows: usize) !void { - try g.route.topk(s, logits, wt.experts_n + 1, wt.experts_n, wt.slots - 1, pick, wts, wt.slots, rows, true); + /// Each row's top-k experts and the shared one: picks and weights [rows, slots] (core route rows). + pub fn topkMany(g: *const Glue, s: cuda.Stream, logits: u64, pick: u64, wts: u64, rows: usize, slots: usize) !void { + try g.route.topk(s, logits, wt.experts_n + 1, wt.experts_n, slots - 1, pick, wts, slots, rows, true); } }; diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 5ad7e03cda5..1b1aa7a4a78 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -22,7 +22,12 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu // refused before the stream, the glue or a captured set loads: the largest pass, wider at --parallel 1 on one rank const chunk = try @import("cuda_chunk.zig").soloRows(try prompt.chunkRows(), o.one_stream and o.tp == 1); _ = try @import("cuda_modelopt_threads.zig").configured(); // TF_FLASHNEXT_LOAD_THREADS, refused before any load - const mode = try config.mode(gpa, io, dir); + const checked = try config.read(gpa, io, dir); + const mode = checked.mode; + if (captured != null and !@import("cuda_widths.zig").capturedServes(checked.widths)) { + std.log.err("flashnext: config.json's num_experts_per_tok is {d}; a captured kernel set routes top-10 only", .{checked.widths.top_k}); + return error.FlashNextWidthsOnCapturedGlue; + } if (o.tp != 1 and mode != .modelopt) return error.FlashNextRanksNeedModelopt; if (o.tp != 1 and captured != null) return error.FlashNextRanksOnCapturedGlue; // the decode graph captures each layer's collectives; the dense split adds its own until a later stage qualifies it @@ -83,7 +88,7 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu _ = try own.engine.reserve(@max(@min(o.context, own.engine.chunk), if (o.slide) @as(usize, @import("cuda_train.zig").pack_rows) else 0)); // the MTP head unless --no-drafts (TF_FLASHNEXT_DRAFTS and _CONFIDENCE: the chain's rule, 6 and -0.4) if (o.drafts and (o.tp == 1 or o.rank == 0)) { - own.head = try mtp.Head.init(gpa, io, driver, &own.stream, dir); + own.head = try mtp.Head.init(gpa, io, driver, &own.stream, dir, e.widths); const drafts = try @import("sys").environment.read(usize, "TF_FLASHNEXT_DRAFTS", mtp.default_depth); own.depth = @max(1, @min(mtp.max_chain, drafts)); const greedy = try @import("sys").environment.read(usize, "TF_FLASHNEXT_DRAFTS_GREEDY", mtp.default_depth_greedy); diff --git a/zig/src/families/flashnext/cuda_launch.zig b/zig/src/families/flashnext/cuda_launch.zig index f7237135973..dc57fdfccf5 100644 --- a/zig/src/families/flashnext/cuda_launch.zig +++ b/zig/src/families/flashnext/cuda_launch.zig @@ -422,12 +422,13 @@ pub const Tri = struct { /// moe._topk_rows: one program, the row's 10 experts and the shared expert. pub fn topkRows(t: Tri, logits: u64, pick: u64, wts: u64) !void { - try t.topkMany(logits, pick, wts, 1); + try t.topkMany(logits, pick, wts, 1, @import("cuda_widths.zig").default.slots()); } - /// moe._topk_rows over `rows` rows of [rows, 513] logits: picks and weights [rows, 11]. - pub fn topkMany(t: Tri, logits: u64, pick: u64, wts: u64, rows: usize) !void { - if (t.glue("_topk_rows")) |g| return g.topkMany(t.s, logits, pick, wts, rows); + /// moe._topk_rows over `rows` rows of [rows, 513] logits: picks and weights [rows, slots]; a captured set takes 11. + pub fn topkMany(t: Tri, logits: u64, pick: u64, wts: u64, rows: usize, slots: usize) !void { + if (t.glue("_topk_rows")) |g| return g.topkMany(t.s, logits, pick, wts, rows, slots); + if (slots != @import("cuda_widths.zig").default.slots()) return error.CapturedSetTopK; try t.run("_topk_rows", .{ u(rows), 1, 1 }, &.{ p("L", "*fp32", logits), p("PICK", "*i32", pick), diff --git a/zig/src/families/flashnext/cuda_mixed_experts.zig b/zig/src/families/flashnext/cuda_mixed_experts.zig index bf6efb0f1f4..ab151d7e437 100644 --- a/zig/src/families/flashnext/cuda_mixed_experts.zig +++ b/zig/src/families/flashnext/cuda_mixed_experts.zig @@ -11,6 +11,8 @@ pub const Owned = struct { rank: usize, world: usize, split_shared: bool = false, + /// The shared expert's intermediate width: its gate_proj's rows (cuda_widths.zig's supported shared widths). + shared_width: usize = wt.moe_w, pub fn free(self: *Owned) void { self.experts.free(); @@ -23,16 +25,22 @@ pub fn load(a: std.mem.Allocator, d: *cuda.Driver, store: *wt.Store, prefix: []c errdefer e.free(); var shared: [3]wt.Q4 = @splat(wt.Q4.empty(d)); errdefer for (&shared) |*p| p.free(); + var buf: [256]u8 = undefined; + const gate = try std.fmt.bufPrint(&buf, "{s}.shared_expert.gate_proj.weight", .{prefix}); + const width = (try store.tensor(gate)).dim(0); + if (!@import("cuda_widths.zig").sharedSupported(width)) { + std.log.err("flashnext: {s} has {d} rows; the supported shared expert widths are 640 and 1280", .{ gate, width }); + return error.UnexpectedTensor; + } // The shared branch participates exactly once in the sum across ranks. if (rank == 0 or split) { - var buf: [256]u8 = undefined; for ([_][]const u8{ "gate_proj", "up_proj", "down_proj" }, 0..) |name, i| { - const n = if (i == 2) wt.dims else wt.moe_w; - const k = if (i == 2) wt.moe_w else wt.dims; + const n = if (i == 2) wt.dims else width; + const k = if (i == 2) width else wt.dims; const key = try std.fmt.bufPrint(&buf, "{s}.shared_expert.{s}", .{ prefix, name }); shared[i] = if (split) try projections.loadCut(a, d, store, key, n, k, try routed.Cut.init(n, world, rank), .rows) else try projections.load(a, d, store, key, n, k); if (shared[i].native == null) return error.UnsupportedQuantization; } } - return .{ .experts = e, .shared = shared, .rank = rank, .world = world, .split_shared = split }; + return .{ .experts = e, .shared = shared, .rank = rank, .world = world, .split_shared = split, .shared_width = width }; } diff --git a/zig/src/families/flashnext/cuda_moe_exchange.zig b/zig/src/families/flashnext/cuda_moe_exchange.zig index f1ca6c5e756..c1b857e2558 100644 --- a/zig/src/families/flashnext/cuda_moe_exchange.zig +++ b/zig/src/families/flashnext/cuda_moe_exchange.zig @@ -5,7 +5,6 @@ const mtp = @import("cuda_mtp.zig"); const moe = @import("cuda_batch_moe.zig"); const dims = wt.dims; -const slots = wt.slots; const share = cuda.rank_scatter.share; /// Rows past any decode round or verify window: `world` and `n` are what both ranks' passes agree on. @@ -28,7 +27,7 @@ pub fn run(pass: anytype, c: anytype, n: usize) !void { const s = pass.s; const h = block(n); const own = share(n, 2, c.rank); - try c.sumBlock(pass.stream, s.y, h * slots * dims); + try c.sumBlock(pass.stream, s.y, h * s.slots * dims); try moe.sumSlots(pass, own[0], own[1] - own[0]); try c.gatherF32(pass.stream, s.moe_f32 + own[0] * dims * 4, s.moe_f32, h * dims); pass.pending_f32 = true; diff --git a/zig/src/families/flashnext/cuda_moe_exchange_test.zig b/zig/src/families/flashnext/cuda_moe_exchange_test.zig index 7af7371174d..efb56d6481b 100644 --- a/zig/src/families/flashnext/cuda_moe_exchange_test.zig +++ b/zig/src/families/flashnext/cuda_moe_exchange_test.zig @@ -65,7 +65,7 @@ const Fake = struct { } }; -const Bufs = struct { y: u64 = 0x1000_0000, wts: u64 = 0x2000_0000, moe_f32: u64 = 0x3000_0000 }; +const Bufs = struct { y: u64 = 0x1000_0000, wts: u64 = 0x2000_0000, moe_f32: u64 = 0x3000_0000, slots: usize = slots }; const Pass = struct { s: *const Bufs, diff --git a/zig/src/families/flashnext/cuda_moe_native.zig b/zig/src/families/flashnext/cuda_moe_native.zig index 5498da8e0ce..1146863ff90 100644 --- a/zig/src/families/flashnext/cuda_moe_native.zig +++ b/zig/src/families/flashnext/cuda_moe_native.zig @@ -10,7 +10,6 @@ const Kernels = @import("cuda_batch_kernels.zig").Kernels; const dims = wt.dims; const experts_n = wt.experts_n; -const slots = wt.slots; /// moeBlockKeep's native layer: each routed pair's fp32 row into y [pairs, dims], the shared slot's on rank 0. pub fn run(self: anytype, native: *const mixed.Owned, n: usize, pairs: usize, plan: cuda.grouped.Plan) !void { @@ -20,7 +19,7 @@ pub fn run(self: anytype, native: *const mixed.Owned, n: usize, pairs: usize, pl const e = owned.count + 1; const skip: i32 = @intCast(owned.count); const picks = if (native.world == 1) s.picks else try ownPicks(self, s.picks, s.picks_ep, pairs, owned.first, owned.count); - const y_bytes = exchange.clearedRows(native.world, n) * slots * dims * 4; + const y_bytes = exchange.clearedRows(native.world, n) * s.slots * dims * 4; if (zs.clearsY(native.world, native.rank)) try self.stream.d.check(self.stream.d.api.cuMemsetD8Async(s.y, 0, y_bytes, self.stream.handle), "cuMemsetD8Async"); const side = try shared.fork(self, native, n); switch (owned.format) { @@ -28,10 +27,10 @@ pub fn run(self: anytype, native: *const mixed.Owned, n: usize, pairs: usize, pl const pt = nvfp4_tile.size(self.k, n); try self.k.router.route(self.stream, picks, pairs, e, pt, plan); const items = cuda.grouped.maxItems(pairs, e, pt); - try nvfp4_tile.run(self.k, pt, self.stream, .up, .{ .x = s.mixed, .stride = dims, .slots = slots }, owned.view(), plan, s.moe_act, items, skip); + try nvfp4_tile.run(self.k, pt, self.stream, .up, .{ .x = s.mixed, .stride = dims, .slots = s.slots }, owned.view(), plan, s.moe_act, items, skip); try nvfp4_tile.run(self.k, pt, self.stream, .down_f32, .{ .x = s.moe_act, .stride = owned.width }, owned.view(), plan, s.y, items, skip); }, - .fp8g => try fp8(self.k, self.stream, s.picks, s.mixed, owned.view(), plan, pairs, n, s.y, s.moe_act), + .fp8g => try fp8(self.k, self.stream, s.picks, s.mixed, owned.view(), plan, pairs, n, s.y, s.moe_act, s.slots), else => return error.UnsupportedQuantization, } if (side != null) try shared.join(self, side, native, n) else try @import("cuda_shared_split.zig").run(self, native, n); @@ -53,13 +52,13 @@ fn ownPicks(self: anytype, picks: u64, out: u64, pairs: usize, first: usize, cou } /// Block-FP8 pairs (W8A16) at NVFP4's decode/prompt tile: `act` bf16, `out` fp32; the shared slot is skipped. -pub fn fp8(k: *const Kernels, stream: cuda.Stream, picks: u64, x: u64, layer: cuda.experts.Layer, plan: cuda.grouped.Plan, pairs: usize, n: usize, out: u64, act: u64) !void { +pub fn fp8(k: *const Kernels, stream: cuda.Stream, picks: u64, x: u64, layer: cuda.experts.Layer, plan: cuda.grouped.Plan, pairs: usize, n: usize, out: u64, act: u64, slot_n: usize) !void { if (layer.format != .fp8g) return error.UnsupportedQuantization; const e = experts_n + 1; const prompt = nvfp4_tile.size(k, n) != 16; const tile: usize = if (prompt) cuda.experts.promptTile(.fp8g) else 16; try k.router.route(stream, picks, pairs, e, tile, plan); const items = cuda.grouped.maxItems(pairs, e, tile); - try k.fp8.run(stream, .up, .{ .x = x, .stride = layer.dims, .slots = slots }, layer, plan, prompt, act, items, experts_n); + try k.fp8.run(stream, .up, .{ .x = x, .stride = layer.dims, .slots = slot_n }, layer, plan, prompt, act, items, experts_n); try k.fp8.run(stream, .down_f32, .{ .x = act, .stride = layer.width }, layer, plan, prompt, out, items, experts_n); } diff --git a/zig/src/families/flashnext/cuda_mtp.zig b/zig/src/families/flashnext/cuda_mtp.zig index d81114959af..e1f2fce12e0 100644 --- a/zig/src/families/flashnext/cuda_mtp.zig +++ b/zig/src/families/flashnext/cuda_mtp.zig @@ -8,6 +8,7 @@ const load = @import("cuda_prompt_load.zig"); const batch = @import("cuda_batch.zig"); const prompt = @import("cuda_prompt.zig"); const gdn = @import("cuda_gdn.zig"); +const widths = @import("cuda_widths.zig"); const dims = wt.dims; const streams = wt.streams; @@ -215,7 +216,14 @@ pub const Head = struct { draw_batch: @import("cuda_draw_batch.zig").Batch, topk_fn: cuda.Function, // fn_row_topk: a row's top_k candidates as drawRow ranks them (cuda_mtp_draw.zig) - pub fn init(gpa: std.mem.Allocator, io: std.Io, driver: *cuda.Driver, stream: *cuda.Stream, dir: []const u8) !*Head { + pub fn init( + gpa: std.mem.Allocator, + io: std.Io, + driver: *cuda.Driver, + stream: *cuda.Stream, + dir: []const u8, + main: widths.Widths, + ) !*Head { const batch_on = try @import("cuda_draw_batch.zig").enabled(); if (!cuda.kernels.available) return error.BuiltWithoutKernels; const h = try gpa.create(Head); @@ -248,6 +256,11 @@ pub const Head = struct { } store.dropStaging(); // the head's experts are on the device errdefer h.layer.free(gpa); + // the MTP layer: the main layers' top-k (config.json gives it none) and the shared width its own tensor has + if (h.layer.native_experts) |moe| if (widths.mtp(main, moe.shared_width) == null) { + std.log.err("flashnext: mtp.layers.0.mlp.shared_expert.gate_proj has {d} rows; neither the main layers' width nor the routed width", .{moe.shared_width}); + return error.UnexpectedTensor; + }; const ids = try draftIds(gpa); defer gpa.free(ids); const head_load = @import("cuda_mtp_load.zig"); diff --git a/zig/src/families/flashnext/cuda_mtp_check.zig b/zig/src/families/flashnext/cuda_mtp_check.zig index a5074333375..cbf8702e972 100644 --- a/zig/src/families/flashnext/cuda_mtp_check.zig +++ b/zig/src/families/flashnext/cuda_mtp_check.zig @@ -99,7 +99,7 @@ fn envF64(name: [:0]const u8, default: f64) f64 { pub fn check(comptime Tri: type, gpa: std.mem.Allocator, io: std.Io, driver: *cuda.Driver, stream: *cuda.Stream, tri: Tri, model_dir: []const u8, prompts: []const []const u32, count: usize) !bool { var e = try prompt.Engine.init(gpa, io, driver, stream, model_dir); defer e.deinit(); - const h = try Head.init(gpa, io, driver, stream, model_dir); + const h = try Head.init(gpa, io, driver, stream, model_dir, e.widths); defer h.deinit(); const o: Ops(Tri) = .{ .e = e, .tri = tri, .h = h }; const depth = try @import("sys").environment.read(usize, "TF_FLASHNEXT_DRAFTS", mtp.default_depth); diff --git a/zig/src/families/flashnext/cuda_projection.zig b/zig/src/families/flashnext/cuda_projection.zig index c0b96adb3b6..8e0c7d77783 100644 --- a/zig/src/families/flashnext/cuda_projection.zig +++ b/zig/src/families/flashnext/cuda_projection.zig @@ -1,4 +1,4 @@ -//! Owned affine or native lane projections; packed device views borrow these exact buffers. +//! Owned affine, native lane or block-FP8 projections; packed device views borrow these exact buffers. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -10,11 +10,17 @@ pub const Projection = struct { n: usize, k: usize, native: ?cuda.qmmf.Weight = null, + /// rows [at, at + n) of the output held as BF16 beside a block-FP8 `native` whose rows there are zero + tail: ?Tail = null, + tail_w: ?cuda.DeviceBuffer = null, + + pub const Tail = struct { native: cuda.qmmf.Weight, at: usize, n: usize }; pub fn free(self: *Projection) void { self.w.free(); self.s.free(); self.b.free(); + if (self.tail_w) |*t| t.free(); } pub fn empty(d: *const cuda.Driver) Projection { @@ -69,3 +75,65 @@ pub fn mxfp8(gpa: std.mem.Allocator, driver: *const cuda.Driver, w: core.safeten p.native = cuda.mxfp8.weight(p.w.ptr, p.s.ptr, n, k); return p; } + +/// The FP8G lane's two planes: the packed codes [padded n, k] and their per-64-input fp32 scale tiles. +pub const Planes = struct { + codes: []u8, + scales: []f32, + + pub fn deinit(self: *Planes, gpa: std.mem.Allocator) void { + gpa.free(self.codes); + gpa.free(self.scales); + self.* = undefined; + } +}; + +/// The FP8G lane's planes: `nh` block-FP8 rows, then `nt` rows of zero codes and a block scale of one. +pub fn fp8gPlanes(gpa: std.mem.Allocator, codes: []const u8, scale_inv: []const f32, nh: usize, k: usize, nt: usize) !Planes { + const fp8 = cuda.fp8; + const n = nh + nt; + const kb = k / 128; + if (nh == 0 or k % 128 != 0 or codes.len != try std.math.mul(usize, nh, k) or scale_inv.len != ((nh + 127) / 128) * kb) + return error.UnexpectedTensor; + // one scale a 128-row block: a tail row may not share its block with an FP8 row, its own rows may be partial + if (nt != 0 and nh % 128 != 0) return error.UnexpectedTensor; + const all = try gpa.alloc(u8, try std.math.mul(usize, n, k)); + defer gpa.free(all); + @memcpy(all[0 .. nh * k], codes); + @memset(all[nh * k ..], 0); + const inv = try gpa.alloc(f32, ((n + 127) / 128) * kb); + defer gpa.free(inv); + @memcpy(inv[0..scale_inv.len], scale_inv); + @memset(inv[scale_inv.len..], 1.0); + const plane = try gpa.alloc(u8, fp8.padded(n) * k); + errdefer gpa.free(plane); + fp8.packCodes(plane, all, n, k); + const scales = try gpa.alloc(f32, fp8.padded(n) * (k / fp8.group)); + errdefer gpa.free(scales); + fp8.packScales(scales, inv, n, k); + return .{ .codes = plane, .scales = scales }; +} + +/// Block-FP8 rows and an optional BF16 tail: the FP8G weight over both, and the tail's own BF16 weight. +pub fn fp8g(gpa: std.mem.Allocator, driver: *const cuda.Driver, codes: []const u8, scale_inv: []const f32, nh: usize, k: usize, tail_bf16: ?[]const u8, nt: usize) !Projection { + if (nt != 0 and tail_bf16 == null) return error.UnexpectedTensor; + var planes = try fp8gPlanes(gpa, codes, scale_inv, nh, k, nt); + defer planes.deinit(gpa); + const n = nh + nt; + var p = Projection.empty(driver); + p.w = try cuda.DeviceBuffer.fromHost(driver, planes.codes); + errdefer p.w.free(); + p.s = try cuda.DeviceBuffer.fromHost(driver, std.mem.sliceAsBytes(planes.scales)); + errdefer p.s.free(); + p.n = n; + p.k = k; + p.native = cuda.fp8.weight(p.w.ptr, p.s.ptr, n, k); + if (tail_bf16) |t| { + var edge = try dense(gpa, driver, .{ .dtype = .bf16, .rank = 2, .shape = .{ nt, k, 1, 1, 1 }, .bytes = t }); + p.tail_w = edge.w; + edge.s.free(); + edge.b.free(); + p.tail = .{ .native = edge.native.?, .at = nh, .n = nt }; + } + return p; +} diff --git a/zig/src/families/flashnext/cuda_projection_load.zig b/zig/src/families/flashnext/cuda_projection_load.zig index 90336a2d023..a847f95d6d9 100644 --- a/zig/src/families/flashnext/cuda_projection_load.zig +++ b/zig/src/families/flashnext/cuda_projection_load.zig @@ -1,4 +1,4 @@ -//! Projection loading preserves dense BF16 bits and MXFP8 codes/scales; affine layouts keep their existing packer. +//! Projection loading preserves dense BF16 bits, MXFP8 codes/scales and block-FP8 planes; affine keeps its packer. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -70,6 +70,98 @@ fn uploadMicro(a: std.mem.Allocator, d: *const cuda.Driver, value: Micro) !wt.Q4 return projection.mxfp8(a, d, .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ value.n, value.k, 1, 1, 1 }, .bytes = value.codes }, .{ .dtype = .u8, .rank = 2, .shape = .{ value.n, value.k / 32, 1, 1, 1 }, .bytes = value.scales }); } +/// Block-FP8 (e4m3 weight, fp32 weight_scale_inv per 128x128 block) parts of one projection, rows stacked in order. +pub const Block8 = struct { + n: usize, + k: usize, + codes: []u8, + sinv: []f32, + + pub fn deinit(self: *Block8, a: std.mem.Allocator) void { + a.free(self.codes); + a.free(self.sinv); + self.* = undefined; + } +}; + +/// Whether `{prefix}.weight_scale_inv` is there: the one tensor a block-FP8 projection carries and the rest do not. +pub fn isBlock8(store: anytype, prefix: []const u8) bool { + var buf: [512]u8 = undefined; + return store.has(std.fmt.bufPrint(&buf, "{s}.weight_scale_inv", .{prefix}) catch return false); +} + +/// How many leading parts of a stitched projection are block FP8, and so where a BF16 tail could start. +pub fn block8Parts(store: anytype, prefix: []const u8, names: []const []const u8) usize { + var buf: [512]u8 = undefined; + var heads: usize = 0; + while (heads < names.len and isBlock8(store, std.fmt.bufPrint(&buf, "{s}{s}", .{ prefix, names[heads] }) catch return heads)) heads += 1; + return heads; +} + +/// A projection's leading block-FP8 parts: e4m3 codes [n, k] and fp32 scales [n / 128, k / 128], stacked in order. +pub fn readBlock8(a: std.mem.Allocator, store: anytype, prefix: []const u8, names: []const []const u8, why: ?*core.modelopt.Why) !Block8 { + var buf: [512]u8 = undefined; + var n: usize = 0; + var k: usize = 0; + // the shared reader refuses any part that is not e4m3 [n, k] with a scale a whole 128-row block covers + for (names) |name| { + const w = try store.tensor(try std.fmt.bufPrint(&buf, "{s}{s}.weight", .{ prefix, name })); + if (k == 0) k = w.dim(1); + n = std.math.add(usize, n, w.dim(0)) catch return error.UnexpectedTensor; + } + const kb = k / 128; + const codes = try a.alloc(u8, std.math.mul(usize, n, k) catch return error.UnexpectedTensor); + errdefer a.free(codes); + const sinv = try a.alloc(f32, (n / 128) * kb); + errdefer a.free(sinv); + var row: usize = 0; + for (names) |name| { + defer store.release(); + const pn = (try store.tensor(try std.fmt.bufPrint(&buf, "{s}{s}.weight", .{ prefix, name }))).dim(0); + const h = try core.quant.fp8.read(store, try std.fmt.bufPrint(&buf, "{s}{s}", .{ prefix, name }), pn, k, .f32, why); + if (h.weight.bytes.len != pn * k) return error.UnexpectedTensor; + @memcpy(codes[row * k ..][0 .. pn * k], h.weight.bytes); + try core.quant.fp8.widen(h.scale_inv, sinv[(row / 128) * kb ..][0 .. (pn / 128) * kb], true); + row += pn; + } + if (row != n) return error.UnexpectedTensor; + return .{ .n = n, .k = k, .codes = codes, .sinv = sinv }; +} + +/// A projection's trailing BF16 parts [nt, k], stacked in order: the exact stored rows the tail's own matmul runs on. +pub fn readTail(a: std.mem.Allocator, store: anytype, prefix: []const u8, names: []const []const u8, k: usize, nt: usize) ![]u8 { + var buf: [512]u8 = undefined; + const bytes = std.math.mul(usize, nt, k * 2) catch return error.UnexpectedTensor; + const out = try a.alloc(u8, bytes); + errdefer a.free(out); + var at: usize = 0; + for (names) |name| { + const t = try store.tensor(try std.fmt.bufPrint(&buf, "{s}{s}.weight", .{ prefix, name })); + if (t.dtype != .bf16 or t.rank != 2 or t.dim(1) != k) return error.UnexpectedTensor; + if (t.bytes.len > bytes - at) return error.UnexpectedTensor; + @memcpy(out[at..][0..t.bytes.len], t.bytes); + at += t.bytes.len; + } + if (at != bytes) return error.UnexpectedTensor; + return out; +} + +/// A projection whose leading parts are block FP8 and whose trailing parts are BF16, as INT4-AutoRound's mixers are. +pub fn loadBlock8(a: std.mem.Allocator, d: *cuda.Driver, store: anytype, prefix: []const u8, names: []const []const u8, n: usize, k: usize) !wt.Q4 { + const heads = block8Parts(store, prefix, names); + if (heads == 0) return error.UnexpectedTensor; + var head = try readBlock8(a, store, prefix, names[0..heads], null); + defer head.deinit(a); + if (head.k != k or head.n > n) return error.UnexpectedTensor; + const nt = n - head.n; + if (nt == 0) return projection.fp8g(a, d, head.codes, head.sinv, head.n, k, null, 0); + // the scratch's tail holds wt.tail_n columns; a wider one has no buffer to be copied out of + if (nt > wt.tail_n) return error.UnexpectedTensor; + const tail = try readTail(a, store, prefix, names[heads..], k, nt); + defer a.free(tail); + return projection.fp8g(a, d, head.codes, head.sinv, head.n, k, tail, nt); +} + pub fn load(a: std.mem.Allocator, d: *cuda.Driver, store: *wt.Store, prefix: []const u8, n: usize, k: usize) !wt.Q4 { var buf: [512]u8 = undefined; const t = try store.tensor(try std.fmt.bufPrint(&buf, "{s}.weight", .{prefix})); @@ -79,6 +171,7 @@ pub fn load(a: std.mem.Allocator, d: *cuda.Driver, store: *wt.Store, prefix: []c return projection.dense(a, d, t); }, .f8_e4m3 => { + if (isBlock8(store, prefix)) return loadBlock8(a, d, store, prefix, &.{""}, n, k); var value = try readMicro(a, store, prefix); defer value.deinit(a); if (value.n != n or value.k != k) return error.UnexpectedTensor; @@ -100,6 +193,7 @@ pub fn loadStitched(a: std.mem.Allocator, d: *cuda.Driver, store: *wt.Store, pre if (names.len == 0) return error.UnexpectedTensor; var buf: [512]u8 = undefined; const first = try store.tensor(try std.fmt.bufPrint(&buf, "{s}{s}.weight", .{ prefix, names[0] })); + if (first.dtype == .f8_e4m3 and isBlock8(store, try std.fmt.bufPrint(&buf, "{s}{s}", .{ prefix, names[0] }))) return loadBlock8(a, d, store, prefix, names, n, k); if (first.dtype == .f8_e4m3) { var value = try readStitched(a, store, prefix, names); defer value.deinit(a); @@ -233,4 +327,5 @@ pub fn loadStitchedCut(a: std.mem.Allocator, d: *const cuda.Driver, store: anyty test { _ = @import("cuda_projection_load_test.zig"); + _ = @import("cuda_projection_tail_test.zig"); } diff --git a/zig/src/families/flashnext/cuda_projection_load_test.zig b/zig/src/families/flashnext/cuda_projection_load_test.zig index 432b2bbca9d..2f06ff8c925 100644 --- a/zig/src/families/flashnext/cuda_projection_load_test.zig +++ b/zig/src/families/flashnext/cuda_projection_load_test.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const core = @import("core"); const Cut = @import("cuda_modelopt_experts.zig").Cut; const source = @import("cuda_projection_load.zig"); +const projection = @import("cuda_projection.zig"); const Tensor = core.safetensors.Tensor; const Fake = struct { @@ -320,3 +321,270 @@ test "stitched cuts refuse MXFP8 and affine parts, other widths and a wrong loca past[2] = Ranges.of(&.{.{ .from = 40, .to = 64 }}); try std.testing.expectError(error.UnexpectedTensor, source.stitchCut(a, &fake, "root", &heads_cut.delta_parts, &past, s.n, k64)); } + +const block_k = 256; +const block_kb = block_k / 128; +/// The fixture's BF16 tail: more rows than wt.tail_n, so the loader's width guard can be told from a short read. +const tail_rows = 768; + +/// e4m3 codes whose binary64 values are exact: 0x38 1.0, 0x3c 1.5, 0x40 2.0, 0x34 0.75, 0xb8 -1.0. +const code_values = [_]u8{ 0x38, 0x3c, 0x40, 0x34, 0xb8 }; + +/// A block-FP8 part of the fixture: e4m3 codes [rows, block_k] and one fp32 scale a 128 x 128 block. +const Part = struct { rows: usize, codes: []u8, inv: []f32 }; + +fn fixturePart(a: std.mem.Allocator, rows: usize, seed: usize) !Part { + const codes = try a.alloc(u8, rows * block_k); + errdefer a.free(codes); + for (0..rows) |r| for (0..block_k) |c| { + codes[r * block_k + c] = code_values[(r + c + seed) % code_values.len]; + }; + const inv = try a.alloc(f32, (rows / 128) * block_kb); + for (0..rows / 128) |i| for (0..block_kb) |j| { + inv[i * block_kb + j] = @floatFromInt(i * 10 + j + 1 + seed * 3); + }; + return .{ .rows = rows, .codes = codes, .inv = inv }; +} + +fn freePart(a: std.mem.Allocator, p: *Part) void { + a.free(p.codes); + a.free(p.inv); +} + +const Bad = enum { none, weight_dtype, rows, cols, scale_shape, scale_nan, tail_dtype, tail_cols, tail_short }; + +/// One stitched projection's store: two block-FP8 parts, ".q" and ".k", and the BF16 indexer tail, with faults. +const Blocky = struct { + k: usize, + parts: [2]Part, + tail: []u8, + bad: Bad = .none, + + /// The part a name selects, and whether it is the scale tensor beside that part's weight. + fn select(name: []const u8) ?struct { i: usize, scale: bool } { + const i: usize = if (std.mem.startsWith(u8, name, "m.q.")) 0 else if (std.mem.startsWith(u8, name, "m.k.")) 1 else return null; + if (std.mem.endsWith(u8, name, ".weight_scale_inv")) return .{ .i = i, .scale = true }; + if (std.mem.endsWith(u8, name, ".weight")) return .{ .i = i, .scale = false }; + return null; + } + + /// Only a block-FP8 projection carries a scale_inv beside its weight: what selects this loader's arm. + pub fn has(self: *Blocky, name: []const u8) bool { + _ = self; + const s = select(name) orelse return false; + return s.scale; + } + + /// The checkpoint-reader adapter the shared block-FP8 reader takes (fp8.read -> get). + pub fn get(self: *Blocky, name: []const u8) !Tensor { + return self.tensor(name); + } + + /// A reading borrow's pages would go here; this store keeps its bytes in memory. + pub fn release(self: *Blocky) void { + _ = self; + } + + pub fn tensor(self: *Blocky, name: []const u8) !Tensor { + if (std.mem.startsWith(u8, name, "m.idx.weight")) { + const cols: usize = if (self.bad == .tail_cols) block_k / 2 else block_k; + const want = self.tail.len / 2; + const bytes = if (self.bad == .tail_short) self.tail[0 .. want - 1] else self.tail; + const dtype: core.safetensors.DType = if (self.bad == .tail_dtype) .f16 else .bf16; + return .{ .dtype = dtype, .rank = 2, .shape = .{ self.tail.len / (block_k * 2), cols, 1, 1, 1 }, .bytes = bytes }; + } + const s = select(name) orelse return error.MissingTensor; + const p = self.parts[s.i]; + if (!s.scale) { + const rows = if (self.bad == .rows and s.i == 0) 200 else p.rows; + const cols = if (self.bad == .cols and s.i == 0) 128 else self.k; + const dtype: core.safetensors.DType = if (self.bad == .weight_dtype and s.i == 0) .bf16 else .f8_e4m3; + return .{ .dtype = dtype, .rank = 2, .shape = .{ rows, cols, 1, 1, 1 }, .bytes = p.codes[0 .. rows * cols] }; + } + // a wrong block count, whole entries so the fake's own slice stays inside its buffer + const cols: usize = if (self.bad == .scale_shape and s.i == 0) 1 else block_kb; + const rows = p.rows / 128; + return .{ .dtype = .f32, .rank = 2, .shape = .{ rows, cols, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(p.inv[0 .. rows * cols]) }; + } +}; + +fn blocky(a: std.mem.Allocator) !Blocky { + var out: Blocky = .{ .k = block_k, .parts = undefined, .tail = &.{} }; + out.parts[0] = try fixturePart(a, 256, 0); + errdefer freePart(a, &out.parts[0]); + out.parts[1] = try fixturePart(a, 128, 1); + errdefer freePart(a, &out.parts[1]); + out.tail = try a.alloc(u8, tail_rows * block_k * 2); + for (0..out.tail.len / 2) |i| std.mem.writeInt(u16, out.tail[i * 2 ..][0..2], @truncate(i * 37 + 3), .little); + return out; +} + +fn freeBlocky(a: std.mem.Allocator, b: *Blocky) void { + for (&b.parts) |*p| freePart(a, p); + a.free(b.tail); +} + +test "block FP8: a projection's FP8 parts and its BF16 tail are the stored bytes the binary64 reference reads" { + const a = std.testing.allocator; + var fake = try blocky(a); + defer freeBlocky(a, &fake); + try std.testing.expectEqual(@as(usize, 2), source.block8Parts(&fake, "m", &.{ ".q", ".k", ".idx" })); + try std.testing.expectEqual(@as(usize, 0), source.block8Parts(&fake, "m", &.{ ".idx", ".q" })); + var head = try source.readBlock8(a, &fake, "m", &.{ ".q", ".k" }, null); + defer head.deinit(a); + try std.testing.expectEqual(@as(usize, 384), head.n); + try std.testing.expectEqual(block_k, head.k); + try std.testing.expectEqualSlices(u8, fake.parts[0].codes, head.codes[0 .. 256 * block_k]); + try std.testing.expectEqualSlices(u8, fake.parts[1].codes, head.codes[256 * block_k ..]); + try std.testing.expectEqualSlices(f32, fake.parts[0].inv, head.sinv[0..4]); + try std.testing.expectEqualSlices(f32, fake.parts[1].inv, head.sinv[4..]); + const tail = try source.readTail(a, &fake, "m", &.{".idx"}, block_k, tail_rows); + defer a.free(tail); + try std.testing.expectEqualSlices(u8, fake.tail, tail); + // the scratch holds the widest tail a block-FP8 projection carries: the attention indexer's own rows + try std.testing.expectEqual(@as(usize, 640), @import("cuda_prompt_wt.zig").tail_n); + try std.testing.expect(@import("cuda_prompt_wt.zig").tail_n <= @import("cuda_prompt_wt.zig").proj_n); + + // the lane's planes: the packed codes and per-64-input scale tiles of those stored rows, then the tail's zeros + const n = 384 + tail_rows; + const rows = try a.alloc(u8, n * block_k); + defer a.free(rows); + @memcpy(rows[0..head.codes.len], head.codes); + @memset(rows[head.codes.len..], 0); + const inv = try a.alloc(f32, (n / 128) * block_kb); + defer a.free(inv); + @memcpy(inv[0..head.sinv.len], head.sinv); + @memset(inv[head.sinv.len..], 1.0); + const want_codes = try a.alloc(u8, cuda.fp8.padded(n) * block_k); + defer a.free(want_codes); + cuda.fp8.packCodes(want_codes, rows, n, block_k); + const want_scales = try a.alloc(f32, cuda.fp8.padded(n) * (block_k / cuda.fp8.group)); + defer a.free(want_scales); + cuda.fp8.packScales(want_scales, inv, n, block_k); + var planes = try projection.fp8gPlanes(a, head.codes, head.sinv, head.n, block_k, tail_rows); + defer planes.deinit(a); + try std.testing.expectEqualSlices(u8, want_codes, planes.codes); + try std.testing.expectEqualSlices(f32, want_scales, planes.scales); + + // the reference of the checkpoint's own tensors, code x its block scale, exact in binary64 + const ref = try a.alloc(f64, 256 * block_k); + defer a.free(ref); + try core.quant.fp8.reference(.{ + .weight = .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ 256, block_k, 1, 1, 1 }, .bytes = fake.parts[0].codes }, + .scale_inv = .{ .dtype = .f32, .rank = 2, .shape = .{ 2, block_kb, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(fake.parts[0].inv) }, + }, ref); + try std.testing.expectEqual(@as(f64, 1.0), ref[0]); // 1.0 x 1 + try std.testing.expectEqual(@as(f64, 1.5), ref[1]); // 1.5 x 1 + try std.testing.expectEqual(@as(f64, 1.5), ref[128]); // 0.75 x 2 + try std.testing.expectEqual(@as(f64, 8.25), ref[128 * block_k]); // 0.75 x 11 + try std.testing.expectEqual(@as(f64, 18.0), ref[128 * block_k + 128]); // 1.5 x 12 + + // a tail row on the lane is a zero code times a scale of one: its binary64 contribution is exactly +0 + const zero_codes = try a.alloc(u8, 128 * block_k); + defer a.free(zero_codes); + @memset(zero_codes, 0); + const one_scale = try a.alloc(f32, block_kb); + defer a.free(one_scale); + @memset(one_scale, 1.0); + const tail_ref = try a.alloc(f64, zero_codes.len); + defer a.free(tail_ref); + try core.quant.fp8.reference(.{ + .weight = .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ 128, block_k, 1, 1, 1 }, .bytes = zero_codes }, + .scale_inv = .{ .dtype = .f32, .rank = 2, .shape = .{ 1, block_kb, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(one_scale) }, + }, tail_ref); + for (tail_ref) |v| try std.testing.expectEqual(@as(u64, 0), @as(u64, @bitCast(v))); + for (inv[head.sinv.len..]) |s| try std.testing.expectEqual(@as(f32, 1.0), s); +} + +/// A store holding one MXFP8 projection (e4m3 weight, u8 group-32 weight_scale) or its affine form (u32 words). +const MicroStore = struct { + dtype: core.safetensors.DType = .f8_e4m3, + scratch: [64 * 256]u8 = undefined, + + /// An MXFP8 or affine projection carries group-32 `weight_scale`, never a 128 x 128 `weight_scale_inv`. + pub fn has(self: *MicroStore, name: []const u8) bool { + _ = self; + return std.mem.endsWith(u8, name, ".weight_scale"); + } + + pub fn tensor(self: *MicroStore, name: []const u8) !Tensor { + @memset(&self.scratch, 0x5a); + if (std.mem.endsWith(u8, name, ".weight_scale")) return .{ .dtype = .u8, .rank = 2, .shape = .{ 64, 8, 1, 1, 1 }, .bytes = self.scratch[0 .. 64 * 8] }; + if (!std.mem.endsWith(u8, name, ".weight")) return error.MissingTensor; + const affine = self.dtype == .u32; + const cols: usize = if (affine) 32 else 256; + const words: usize = if (affine) 4 else 1; + const len = 64 * cols * words; + return .{ .dtype = self.dtype, .rank = 2, .shape = .{ 64, cols, 1, 1, 1 }, .bytes = self.scratch[0..len] }; + } +}; + +test "block FP8: MXFP8 and affine projections are not block FP8 and take the reader they took before" { + const a = std.testing.allocator; + var fake: MicroStore = .{}; + try std.testing.expect(!source.isBlock8(&fake, "m.q")); + var value = try source.readMicro(a, &fake, "m.q"); + defer value.deinit(a); + try std.testing.expectEqual(@as(usize, 64), value.n); + try std.testing.expectEqual(@as(usize, 256), value.k); + try std.testing.expectEqual(@as(usize, 64 * 256), value.codes.len); + try std.testing.expectEqual(@as(usize, 64 * 8), value.scales.len); + fake.dtype = .u32; + try std.testing.expect(!source.isBlock8(&fake, "m.q")); + try std.testing.expectError(error.UnexpectedTensor, source.readMicro(a, &fake, "m.q")); +} + +test "block FP8: the loader refuses the shapes and the planes it cannot splice, before any device call" { + const a = std.testing.allocator; + var fake = try blocky(a); + defer freeBlocky(a, &fake); + var why: core.modelopt.Why = .{}; + for ([_]Bad{ .weight_dtype, .rows, .cols, .scale_shape }) |bad| { + fake.bad = bad; + try std.testing.expectError(error.UnexpectedTensor, source.readBlock8(a, &fake, "m", &.{ ".q", ".k" }, &why)); + } + fake.bad = .scale_nan; + fake.parts[0].inv[0] = std.math.nan(f32); + try std.testing.expectError(error.UnsupportedQuantization, source.readBlock8(a, &fake, "m", &.{ ".q", ".k" }, &why)); + fake.bad = .none; + fake.parts[0].inv[0] = 1.0; + { + const d: *cuda.Driver = undefined; + for ([_]usize{ 0, 383, 641 }) |n| try std.testing.expectError(error.UnexpectedTensor, source.loadBlock8(a, d, &fake, "m", &.{ ".q", ".k" }, n, block_k)); + try std.testing.expectError(error.UnexpectedTensor, source.loadBlock8(a, d, &fake, "m", &.{ ".q", ".k" }, 640, block_k / 2)); + try std.testing.expectError(error.UnexpectedTensor, source.loadBlock8(a, d, &fake, "m", &.{".idx"}, 256, block_k)); + // a tail the scratch cannot hold is refused before it is read, though this store could serve it whole + try std.testing.expectError(error.UnexpectedTensor, source.loadBlock8(a, d, &fake, "m", &.{ ".q", ".k", ".idx" }, 384 + tail_rows, block_k)); + } + // the dtype and the count decide at the width the tail is read at; a short tensor is caught by the count + fake.bad = .tail_dtype; + try std.testing.expectError(error.UnexpectedTensor, source.readTail(a, &fake, "m", &.{".idx"}, block_k, tail_rows)); + fake.bad = .tail_cols; + try std.testing.expectError(error.UnexpectedTensor, source.readTail(a, &fake, "m", &.{".idx"}, block_k, 256)); + fake.bad = .tail_short; + try std.testing.expectError(error.UnexpectedTensor, source.readTail(a, &fake, "m", &.{".idx"}, block_k, tail_rows)); + fake.bad = .none; + try std.testing.expectError(error.UnexpectedTensor, source.readTail(a, &fake, "m", &.{".idx"}, block_k, 512)); + // the plane builder's own guards: whole 128-row blocks, a k of scale blocks, and lengths that agree + try std.testing.expectError(error.UnexpectedTensor, projection.fp8gPlanes(a, fake.parts[0].codes, fake.parts[0].inv, 0, block_k, 0)); + try std.testing.expectError(error.UnexpectedTensor, projection.fp8gPlanes(a, fake.parts[0].codes, fake.parts[0].inv, 256, 192, 0)); + try std.testing.expectError(error.UnexpectedTensor, projection.fp8gPlanes(a, fake.parts[0].codes[1..], fake.parts[0].inv, 256, block_k, 0)); + try std.testing.expectError(error.UnexpectedTensor, projection.fp8gPlanes(a, fake.parts[0].codes, fake.parts[0].inv[1..], 256, block_k, 0)); + // 192 rows cannot lead a 128-row tail: the last head block would carry the tail's rows, and its scales are whole + try std.testing.expectError(error.UnexpectedTensor, projection.fp8gPlanes(a, fake.parts[0].codes[0 .. 192 * block_k], fake.parts[0].inv[0..4], 192, block_k, 128)); +} + +fn blockTrial(a: std.mem.Allocator) !void { + var fake = try blocky(a); + defer freeBlocky(a, &fake); + var head = try source.readBlock8(a, &fake, "m", &.{ ".q", ".k" }, null); + defer head.deinit(a); + const tail = try source.readTail(a, &fake, "m", &.{".idx"}, block_k, tail_rows); + a.free(tail); + var planes = try projection.fp8gPlanes(a, head.codes, head.sinv, head.n, block_k, tail_rows); + planes.deinit(a); +} + +test "block FP8: every partial allocation on the way to the planes is freed" { + try std.testing.checkAllAllocationFailures(std.testing.allocator, blockTrial, .{}); +} diff --git a/zig/src/families/flashnext/cuda_projection_tail_test.zig b/zig/src/families/flashnext/cuda_projection_tail_test.zig new file mode 100644 index 00000000000..acfe8124e72 --- /dev/null +++ b/zig/src/families/flashnext/cuda_projection_tail_test.zig @@ -0,0 +1,159 @@ +//! The block-FP8 splicer at INT4-AutoRound's DeltaNet in-projection: 16,384 FP8 rows and a 96-row BF16 tail. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const source = @import("cuda_projection_load.zig"); +const projection = @import("cuda_projection.zig"); +const parts = @import("heads_cut.zig").delta_parts; +const Tensor = core.safetensors.Tensor; + +/// The checkpoint's k of 2,560 scaled down to two 128-input blocks. +const k: usize = 256; +/// in_proj_qkv, in_proj_z, in_proj_b and in_proj_a rows, as the checkpoint stores them. +const rows = [_]usize{ 10240, 6144, 48, 48 }; +const nh = rows[0] + rows[1]; +const nt = rows[2] + rows[3]; +const n = nh + nt; + +/// 0x38 1.0, 0x3c 1.5, 0x40 2.0, 0x34 0.75, 0xb8 -1.0: e4m3 codes with exact binary64 values. +const code_values = [_]u8{ 0x38, 0x3c, 0x40, 0x34, 0xb8 }; + +/// One block-FP8 part of the fixture: e4m3 codes [rows, k] and one fp32 scale a 128 x 128 block. +const Part = struct { rows: usize, codes: []u8, inv: []f32 }; + +fn partOf(a: std.mem.Allocator, count: usize, seed: usize) !Part { + const codes = try a.alloc(u8, count * k); + errdefer a.free(codes); + for (0..count) |r| for (0..k) |c| { + codes[r * k + c] = code_values[(r + c + seed) % code_values.len]; + }; + const inv = try a.alloc(f32, (count / 128) * (k / 128)); + for (inv, 0..) |*s, i| s.* = @floatFromInt(i + 1 + seed); + return .{ .rows = count, .codes = codes, .inv = inv }; +} + +fn freePart(a: std.mem.Allocator, p: *Part) void { + a.free(p.codes); + a.free(p.inv); +} + +/// The checkpoint's four in-projection parts under one prefix: two block FP8 and two BF16 of 48 rows. +const Mixer = struct { + block: [2]Part, + tail: [2][]u8, + + /// The part a name selects, and whether it is the scale tensor beside that part's weight. + fn slot(name: []const u8) ?struct { i: usize, scale: bool } { + for (parts, 0..) |p, i| { + var buf: [64]u8 = undefined; + const stem = std.fmt.bufPrint(&buf, "m{s}", .{p}) catch return null; + if (!std.mem.startsWith(u8, name, stem)) continue; + if (std.mem.eql(u8, name[stem.len..], ".weight")) return .{ .i = i, .scale = false }; + if (std.mem.eql(u8, name[stem.len..], ".weight_scale_inv")) return .{ .i = i, .scale = true }; + } + return null; + } + + /// Only the block-FP8 parts carry a scale_inv beside their weight: what selects this loader's arm. + pub fn has(self: *Mixer, name: []const u8) bool { + _ = self; + const s = slot(name) orelse return false; + return s.scale and s.i < 2; + } + + /// The checkpoint-reader adapter the shared block-FP8 reader takes (fp8.read -> get). + pub fn get(self: *Mixer, name: []const u8) !Tensor { + return self.tensor(name); + } + + /// A reading borrow's pages would go here; this store keeps its bytes in memory. + pub fn release(self: *Mixer) void { + _ = self; + } + + pub fn tensor(self: *Mixer, name: []const u8) !Tensor { + const s = slot(name) orelse return error.MissingTensor; + if (s.i >= 2) { + if (s.scale) return error.MissingTensor; + const t = self.tail[s.i - 2]; + return .{ .dtype = .bf16, .rank = 2, .shape = .{ t.len / (k * 2), k, 1, 1, 1 }, .bytes = t }; + } + const p = self.block[s.i]; + if (s.scale) return .{ .dtype = .f32, .rank = 2, .shape = .{ p.rows / 128, k / 128, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(p.inv) }; + return .{ .dtype = .f8_e4m3, .rank = 2, .shape = .{ p.rows, k, 1, 1, 1 }, .bytes = p.codes }; + } + + pub fn deinit(self: *Mixer, a: std.mem.Allocator) void { + for (&self.block) |*p| freePart(a, p); + for (&self.tail) |t| a.free(t); + } +}; + +fn mixer(a: std.mem.Allocator) !Mixer { + var out: Mixer = .{ .block = undefined, .tail = undefined }; + out.block[0] = try partOf(a, rows[0], 0); + errdefer freePart(a, &out.block[0]); + out.block[1] = try partOf(a, rows[1], 1); + errdefer freePart(a, &out.block[1]); + for (&out.tail, rows[2..]) |*t, count| { + t.* = try a.alloc(u8, count * k * 2); + errdefer a.free(t.*); + } + for (&out.tail, rows[2..], 0..) |t, count, i| for (0..count * k) |v| { + std.mem.writeInt(u16, t[v * 2 ..][0..2], @truncate(v * 37 + 3 + i), .little); + }; + return out; +} + +test "block FP8: a 96-row BF16 tail after 16,384 FP8 rows is spliced, not refused" { + const a = std.testing.allocator; + var m = try mixer(a); + defer m.deinit(a); + try std.testing.expectEqual(@as(usize, 2), source.block8Parts(&m, "m", &parts)); + var head = try source.readBlock8(a, &m, "m", parts[0..2], null); + defer head.deinit(a); + try std.testing.expectEqual(nh, head.n); + try std.testing.expectEqual(k, head.k); + try std.testing.expectEqualSlices(u8, m.block[0].codes, head.codes[0 .. rows[0] * k]); + try std.testing.expectEqualSlices(u8, m.block[1].codes, head.codes[rows[0] * k ..]); + try std.testing.expectEqualSlices(f32, m.block[0].inv, head.sinv[0 .. (rows[0] / 128) * (k / 128)]); + try std.testing.expectEqualSlices(f32, m.block[1].inv, head.sinv[(rows[0] / 128) * (k / 128) ..]); + const tail = try source.readTail(a, &m, "m", parts[2..], k, nt); + defer a.free(tail); + try std.testing.expectEqual(nt * k * 2, tail.len); + try std.testing.expectEqualSlices(u8, m.tail[0], tail[0 .. rows[2] * k * 2]); + try std.testing.expectEqualSlices(u8, m.tail[1], tail[rows[2] * k * 2 ..]); + // the load's own plane builder at the checkpoint's rows: accepted, and past the head zero codes and scale one + var planes = try projection.fp8gPlanes(a, head.codes, head.sinv, head.n, k, nt); + defer planes.deinit(a); + try std.testing.expectEqual(cuda.fp8.padded(n) * k, planes.codes.len); + try std.testing.expectEqual(cuda.fp8.padded(n) * (k / cuda.fp8.group), planes.scales.len); + for (planes.codes[nh * k ..]) |b| try std.testing.expectEqual(@as(u8, 0), b); + for (planes.scales[(nh / 64) * (k / cuda.fp8.group) * 64 ..]) |s| try std.testing.expectEqual(@as(f32, 1.0), s); + // no FP8 row moves: the head alone builds the planes those rows held + var alone = try projection.fp8gPlanes(a, head.codes, head.sinv, head.n, k, 0); + defer alone.deinit(a); + try std.testing.expectEqualSlices(u8, alone.codes, planes.codes[0..alone.codes.len]); + try std.testing.expectEqualSlices(f32, alone.scales, planes.scales[0..alone.scales.len]); + // the per-part expectation: the packers over the stored head bytes, then the tail's zero rows + const all = try a.alloc(u8, n * k); + defer a.free(all); + @memcpy(all[0 .. nh * k], head.codes); + @memset(all[nh * k ..], 0); + const inv = try a.alloc(f32, ((n + 127) / 128) * (k / 128)); + defer a.free(inv); + @memcpy(inv[0..head.sinv.len], head.sinv); + @memset(inv[head.sinv.len..], 1.0); + const want = try a.alloc(u8, cuda.fp8.padded(n) * k); + defer a.free(want); + cuda.fp8.packCodes(want, all, n, k); + try std.testing.expectEqualSlices(u8, want, planes.codes); + const want_s = try a.alloc(f32, cuda.fp8.padded(n) * (k / cuda.fp8.group)); + defer a.free(want_s); + cuda.fp8.packScales(want_s, inv, n, k); + try std.testing.expectEqualSlices(f32, want_s, planes.scales); + // the lane's weight serves the projection's own rows; the 129th block's 32 rows past them are packing only + const w = cuda.fp8.weight(0, 0, n, k); + try std.testing.expectEqual(@as(u32, 16480), w.n); + try std.testing.expectEqual(@as(u32, 16512), w.npad); +} diff --git a/zig/src/families/flashnext/cuda_prompt.zig b/zig/src/families/flashnext/cuda_prompt.zig index 7d7fd7dd626..d31ab0ec3ec 100644 --- a/zig/src/families/flashnext/cuda_prompt.zig +++ b/zig/src/families/flashnext/cuda_prompt.zig @@ -17,7 +17,6 @@ const streams = weights.streams; const wide = weights.wide; const vocab = weights.vocab; const experts_n = weights.experts_n; -const slots = weights.slots; const moe_w = weights.moe_w; const proj_n = weights.proj_n; const out_k = weights.out_k; @@ -133,6 +132,8 @@ pub const Engine = struct { pockets: pocket.Pockets = .{}, /// During a round of taught and untaught streams: its rows' pocket scales (0 on an untaught row); 0: none. taught_rows: u64 = 0, + /// The routing and shared widths config.json selects (cuda_widths.zig); the scratch is sized and laid out by them. + widths: @import("cuda_widths.zig").Widths = @import("cuda_widths.zig").default, pub fn init(gpa: std.mem.Allocator, io: std.Io, driver: *cuda.Driver, stream: *cuda.Stream, model_dir: []const u8) !*Engine { return initRank(gpa, io, driver, stream, model_dir, 1, 0); } @@ -160,6 +161,7 @@ pub const Engine = struct { errdefer gpa.free(e.model_dir); e.store = try Store.open(gpa, io, e.model_dir); errdefer e.store.deinit(); + e.widths = try @import("cuda_config.zig").widthsIn(gpa, io, e.model_dir); try e.store.detectNorms(); const weight = try e.store.tensor(embed.weight_name); if (weight.dtype == .bf16) { @@ -201,6 +203,10 @@ pub const Engine = struct { var pk: load.Pocket = .{ .gate = rows[0..cap], .up = rows[cap..][0..cap], .down = rows[2 * cap ..][0..cap] }; e.layers[i] = try load.loadLayerRank(gpa, driver, stream, &e.store, pack_fn, i, world, rank, &pk); e.n_layers += 1; + if (e.layers[i].native_experts) |ne| if (ne.shared_width != e.widths.shared) { + std.log.err("flashnext: layer {d}'s shared expert has {d} rows; config.json's shared_expert_intermediate_size is {d}", .{ i, ne.shared_width, e.widths.shared }); + return error.UnexpectedTensor; + }; std.log.info("flashnext: rank {d}/{d} loaded layer {d}/{d}", .{ rank + 1, world, i + 1, layers_n }); if (pk.n == 0) continue; const used = pocket.usedOf(pk.up, pk.n); @@ -264,7 +270,7 @@ pub const Engine = struct { const e: *Engine = @ptrCast(@alignCast(ctx)); var pk = e.pocketOf(layer) orelse return; pk.scale = e.taught_rows; - try e.pocketOps().?.pocketRows(pk, .{ .x = x, .ids = ids, .wts = wts }, out, true, rows, dims, slots - 1); + try e.pocketOps().?.pocketRows(pk, .{ .x = x, .ids = ids, .wts = wts }, out, true, rows, dims, e.widths.top_k); } /// The resident weights a pass reads, with the taught layers' pockets. @@ -380,7 +386,7 @@ pub const Engine = struct { } // head_local: the draft head's lanes on one GPU, a pass's rows split; native_part only where the lane reduces const parts = @import("cuda_batch_state.zig"); - const z: parts.Sizes = .{ .head_rows = if (e.collective != null) @max(rows, parts.head_rows_one) else parts.head_rows_one, .lane_reduce = !e.batch_k.native_lane.clusters }; + const z: parts.Sizes = .{ .head_rows = if (e.collective != null) @max(rows, parts.head_rows_one) else parts.head_rows_one, .lane_reduce = !e.batch_k.native_lane.clusters, .slots = e.widths.slots(), .shared = e.widths.shared }; e.batch_s = try batch.Scratch.alloc(e.gpa, e.driver, e.stream.*, rows, z); return &e.batch_s.?; } diff --git a/zig/src/families/flashnext/cuda_prompt_step.zig b/zig/src/families/flashnext/cuda_prompt_step.zig index ddef6e6fdd9..10bd121843b 100644 --- a/zig/src/families/flashnext/cuda_prompt_step.zig +++ b/zig/src/families/flashnext/cuda_prompt_step.zig @@ -195,7 +195,7 @@ pub fn writeback(tri: anytype, s: *Scratch, h: u64, mode: usize, inj: u64, y: u6 if (mode == 0) { try tri.hcWriteback(h, h, s.pss.ptr, dummy, "*bf16", dummy, dummy, "*bf16", dummy, "*bf16", dims, 1, dims, streams, 0, 1, 1, 1); } else if (mode == 2) { - try tri.hcWriteback(h, h, s.pss.ptr, dummy, "*bf16", inj, y, "*fp32", wts, "*fp32", dims, 1, dims, streams, 2, 10, 11, 1); + try tri.hcWriteback(h, h, s.pss.ptr, dummy, "*bf16", inj, y, "*fp32", wts, "*fp32", dims, 1, dims, streams, 2, slots - 1, slots, 1); } else if (mode == 4) { try tri.hcWriteback(h, h, s.pss.ptr, s.part.ptr, "*fp32", inj, dummy, "*bf16", dummy, "*bf16", dims, 1, dims, streams, 4, 1, 1, out_sk); } else return error.UnexpectedTensor; diff --git a/zig/src/families/flashnext/cuda_prompt_wt.zig b/zig/src/families/flashnext/cuda_prompt_wt.zig index d94dec71780..7290fad476b 100644 --- a/zig/src/families/flashnext/cuda_prompt_wt.zig +++ b/zig/src/families/flashnext/cuda_prompt_wt.zig @@ -28,6 +28,8 @@ pub const index_heads: usize = 4; pub const index_dim: usize = 128; pub const half: usize = 32; pub const proj_n: usize = 13952; +/// The attention indexer's own projection rows: the widest BF16 tail a block-FP8 projection carries. +pub const tail_n: usize = (index_heads + 1) * index_dim; pub const out_k: usize = 6144; /// Chunks of 512 keys a row's attention reads at most: 2,048 selected keys plus a tail, or 2,051 dense keys. pub const nch: usize = 5; diff --git a/zig/src/families/flashnext/cuda_scratch_sizes.zig b/zig/src/families/flashnext/cuda_scratch_sizes.zig index 315655b7a56..19e5be2974d 100644 --- a/zig/src/families/flashnext/cuda_scratch_sizes.zig +++ b/zig/src/families/flashnext/cuda_scratch_sizes.zig @@ -8,8 +8,8 @@ const att_rows = @import("cuda_batch_state.zig").att_rows; /// head_local's rows on one GPU: the draft head's lanes (<= 16) times its ids; a split head needs a pass's rows. pub const head_rows_one: usize = 32; -/// head_local's rows, and whether the lane reduces K slices through native_part (with clusters it never does). -pub const Sizes = struct { head_rows: usize = head_rows_one, lane_reduce: bool = true }; +/// head_local's rows, the lane's K-slice reduce, a row's expert slots and the widest shared expert (cuda_widths.zig). +pub const Sizes = struct { head_rows: usize = head_rows_one, lane_reduce: bool = true, slots: usize = wt.slots, shared: usize = wt.moe_w }; /// hc_part's rows of (low + 4) floats: hc_sk slices below 64 rows (legacy kernel), <= 8 below 256 (lane), one beyond. pub fn hcPartRows(cap: usize) usize { diff --git a/zig/src/families/flashnext/cuda_shared_split.zig b/zig/src/families/flashnext/cuda_shared_split.zig index 33b4c1ee42b..ca16ae2ace9 100644 --- a/zig/src/families/flashnext/cuda_shared_split.zig +++ b/zig/src/families/flashnext/cuda_shared_split.zig @@ -8,7 +8,7 @@ pub fn run(self: anytype, native: *const mixed.Owned, n: usize) !void { const s = self.s; const dims = wt.dims; const glue = self.tri.own orelse return error.NativeGlueRequired; - const width = if (native.split_shared) wt.moe_w / 2 else wt.moe_w; + const width = if (native.split_shared) native.shared_width / 2 else native.shared_width; try self.k.native_lane.matmul(self.stream, s.mixed, dims, n, native.shared[0].native.?, s.shared_gate, s.native_part); try self.k.native_lane.matmul(self.stream, s.mixed, dims, n, native.shared[1].native.?, s.shared_up, s.native_part); try glue.sharedSwiGLU(self.stream, s.shared_gate, s.shared_up, s.shared_act, n, width); @@ -16,13 +16,13 @@ pub fn run(self: anytype, native: *const mixed.Owned, n: usize) !void { if (native.split_shared) { const c = self.m.collective orelse return error.TensorParallelUnavailable; try c.gather(self.stream, input, s.rank_gather, n * width); - // one row: the ranks' gathered blocks [2, 1, width] are already the row [1, moe_w] the down projection reads - if (n > 1) for (0..2) |rank| try ops.copyCols(self.k, self.stream, s.rank_gather + rank * n * width * 2, width, s.rank_input + rank * width * 2, wt.moe_w, width, n); + // one row: the ranks' gathered blocks [2, 1, width] are the row [1, shared_width] the down projection reads + if (n > 1) for (0..2) |rank| try ops.copyCols(self.k, self.stream, s.rank_gather + rank * n * width * 2, width, s.rank_input + rank * width * 2, native.shared_width, width, n); input = if (n == 1) s.rank_gather else s.rank_input; } // the whole expert's down goes straight into its slot (cuda_batch_side.down), as on the side stream if (!native.split_shared) return @import("cuda_batch_side.zig").down(self, self.stream, input, native, n); - try self.k.native_lane.matmulF32(self.stream, input, wt.moe_w, n, native.shared[2].native.?, s.shared_out, s.native_part); + try self.k.native_lane.matmulF32(self.stream, input, native.shared_width, n, native.shared[2].native.?, s.shared_out, s.native_part); // Every routed slot and the peer's output columns stay at the zeros set before the expert launches. - try ops.copyCols(self.k, self.stream, s.shared_out, dims, s.y + (wt.slots - 1) * dims * 4 + native.rank * dims * 2, wt.slots * dims * 2, dims, n); + try ops.copyCols(self.k, self.stream, s.shared_out, dims, s.y + (s.slots - 1) * dims * 4 + native.rank * dims * 2, s.slots * dims * 2, dims, n); } diff --git a/zig/src/families/flashnext/cuda_split_lane_test.zig b/zig/src/families/flashnext/cuda_split_lane_test.zig index 417a47a8c0b..ceba659bf89 100644 --- a/zig/src/families/flashnext/cuda_split_lane_test.zig +++ b/zig/src/families/flashnext/cuda_split_lane_test.zig @@ -111,6 +111,7 @@ const Rig = struct { r.k.native_lane.prompt = null; r.s = undefined; r.s.cap = 256; + r.s.slots = wt.slots; r.s.part = part_at; r.s.native_part = native_part_at; r.s.dummy = 0x99; @@ -280,6 +281,7 @@ test "shared expert composition keeps whole direct slots and split full-K output var native: @import("cuda_mixed_experts.zig").Owned = undefined; native.rank = rank; native.split_shared = split; + native.shared_width = wt.moe_w; const width: usize = if (split) wt.moe_w / 2 else wt.moe_w; const columns: usize = if (split) dims / 2 else dims; for (0..3) |i| native.shared[i].native = cuda.modelopt.bf16Weight(0x2000, if (i == 2) columns else width, if (i == 2) wt.moe_w else dims); @@ -332,6 +334,7 @@ test "shared expert composition keeps whole direct slots and split full-K output var native: @import("cuda_mixed_experts.zig").Owned = undefined; native.rank = 0; native.split_shared = false; + native.shared_width = wt.moe_w; for (0..3) |i| native.shared[i].native = cuda.modelopt.bf16Weight(0x2000, if (i == 2) dims else wt.moe_w, if (i == 2) wt.moe_w else dims); native.shared[2].native.?.npad += 1; var self: Self = .{ .k = &r.k, .s = &r.s, .m = r.pass(64, true).m, .stream = .{ .d = &r.d, .handle = null }, .tri = .{ .own = &glue } }; diff --git a/zig/src/families/flashnext/cuda_widths.zig b/zig/src/families/flashnext/cuda_widths.zig new file mode 100644 index 00000000000..9e74dc9050b --- /dev/null +++ b/zig/src/families/flashnext/cuda_widths.zig @@ -0,0 +1,109 @@ +//! The routing width (experts a token takes) and the shared expert's width, chosen on load from config.json. +const std = @import("std"); +const wt = @import("cuda_prompt_wt.zig"); + +/// One supported shape: the routed experts a token takes and the shared expert's intermediate width. +pub const Widths = struct { + top_k: usize, + shared: usize, + + /// A row's slots in the expert outputs and their weights: the routed experts, then the shared expert. + pub fn slots(w: Widths) usize { + return w.top_k + 1; + } + + pub fn isDefault(w: Widths) bool { + return w.top_k == default.top_k and w.shared == default.shared; + } +}; + +/// The shape the cuda_prompt_wt.zig constants hold: top-10 routing and a 640-wide shared expert. +pub const default: Widths = .{ .top_k = wt.slots - 1, .shared = wt.moe_w }; + +/// Every shape the CUDA path serves: the default, and top-5 routing with a 1280-wide shared expert. +pub const supported = [_]Widths{ default, .{ .top_k = 5, .shared = 2 * wt.moe_w } }; + +/// A selection's result: the supported shape, or the name of the config field that has no supported value. +pub const Selected = union(enum) { widths: Widths, field: []const u8 }; + +/// The supported shape of `num_experts_per_tok` and `shared_expert_intermediate_size` (less `learned` pocket neurons). +pub fn select(top_k: ?i64, shared: ?i64, learned: i64) Selected { + for (supported) |w| { + if (top_k != @as(i64, @intCast(w.top_k))) continue; + if (shared != @as(i64, @intCast(w.shared)) + learned) return .{ .field = "shared_expert_intermediate_size" }; + return .{ .widths = w }; + } + return .{ .field = "num_experts_per_tok" }; +} + +/// Whether a shared expert of `rows` rows has a supported width (its gate_proj's rows). +pub fn sharedSupported(rows: usize) bool { + for (supported) |w| if (w.shared == rows) return true; + return false; +} + +/// The MTP layer's widths: the main layers' top-k, and its shared expert's rows if they are the main or routed width. +pub fn mtp(main: Widths, shared_rows: usize) ?Widths { + if (shared_rows != main.shared and shared_rows != wt.moe_w) return null; + return .{ .top_k = main.top_k, .shared = shared_rows }; +} + +/// Whether a captured kernel set can serve the shape: its `_topk_rows` is built for the default only. +pub fn capturedServes(w: Widths) bool { + return w.isDefault(); +} + +test "the default shape is the constants' and a top-5 checkpoint selects a 1280-wide shared expert" { + try std.testing.expectEqual(@as(usize, 11), default.slots()); + try std.testing.expectEqual(Selected{ .widths = default }, select(10, 640, 0)); + const five = select(5, 1280, 0).widths; + try std.testing.expectEqual(Widths{ .top_k = 5, .shared = 1280 }, five); + try std.testing.expectEqual(@as(usize, 6), five.slots()); + try std.testing.expect(!five.isDefault()); + try std.testing.expectEqual(Selected{ .widths = default }, select(10, 640 + 64, 64)); +} + +test "a width outside the supported list is refused by its field's name" { + const Case = struct { top_k: ?i64, shared: ?i64, field: []const u8 }; + for ([_]Case{ + .{ .top_k = 7, .shared = 640, .field = "num_experts_per_tok" }, + .{ .top_k = null, .shared = 640, .field = "num_experts_per_tok" }, + .{ .top_k = 5, .shared = 640, .field = "shared_expert_intermediate_size" }, + .{ .top_k = 10, .shared = 1280, .field = "shared_expert_intermediate_size" }, + .{ .top_k = 5, .shared = null, .field = "shared_expert_intermediate_size" }, + }) |c| try std.testing.expectEqualStrings(c.field, select(c.top_k, c.shared, 0).field); + try std.testing.expect(sharedSupported(640) and sharedSupported(1280)); + try std.testing.expect(!sharedSupported(960) and !sharedSupported(704)); +} + +test "the MTP layer routes at the main layers' top-k with its own shared width, and another width is refused" { + const five: Widths = .{ .top_k = 5, .shared = 1280 }; + try std.testing.expectEqual(Widths{ .top_k = 5, .shared = 640 }, mtp(five, 640).?); + try std.testing.expectEqual(five, mtp(five, 1280).?); + try std.testing.expectEqual(default, mtp(default, 640).?); + try std.testing.expectEqual(@as(?Widths, null), mtp(five, 960)); + try std.testing.expectEqual(@as(?Widths, null), mtp(default, 1280)); +} + +test "a captured kernel set serves the default shape only" { + try std.testing.expect(capturedServes(default)); + try std.testing.expect(!capturedServes(supported[1])); +} + +test "the scratch is sized by the shape: a wider shared expert's three buffers, fewer slots' pairs" { + const Scratch = @import("cuda_batch_state.zig").Scratch; + const cap = 64; + const base = Scratch.bytes(cap, .{ .slots = default.slots(), .shared = default.shared }); + try std.testing.expectEqual(Scratch.bytes(cap, .{}), base); + try std.testing.expectEqual(base + cap * (1280 - 640) * 2 * 3, Scratch.bytes(cap, .{ .slots = default.slots(), .shared = 1280 })); + try std.testing.expect(Scratch.bytes(cap, .{ .slots = supported[1].slots(), .shared = default.shared }) < base); +} + +test "the MTP head takes the widths the engine read, so config.json has one reader of the shape" { + const head = @embedFile("cuda_mtp.zig"); + try std.testing.expect(std.mem.indexOf(u8, head, "main: widths.Widths,") != null); + try std.testing.expect(std.mem.indexOf(u8, head, "widths.mtp(main, moe.shared_width)") != null); + try std.testing.expect(std.mem.indexOf(u8, head, "widthsIn") == null); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_lanes_load.zig"), "Head.init(gpa, io, driver, &own.stream, dir, e.widths)") != null); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_mtp_check.zig"), "Head.init(gpa, io, driver, stream, model_dir, e.widths)") != null); +} diff --git a/zig/tests/cuda/flashnext_exchange_tests.zig b/zig/tests/cuda/flashnext_exchange_tests.zig index 79a381a908a..46b5df50c0f 100644 --- a/zig/tests/cuda/flashnext_exchange_tests.zig +++ b/zig/tests/cuda/flashnext_exchange_tests.zig @@ -77,7 +77,7 @@ fn planted(gpu: check.Gpu, c: *Collective, stream: cuda.Stream, rank: usize) !vo } const Kernels = struct { moe_sum: cuda.Function }; -const Bufs = struct { y: u64, wts: u64, moe_f32: u64 }; +const Bufs = struct { y: u64, wts: u64, moe_f32: u64, slots: usize = slots }; const Pass = struct { s: *const Bufs, k: Kernels, stream: cuda.Stream, pending_f32: bool = false }; /// A writeback's outputs over the pass's rows and the spare one, poisoned so a row no launch writes shows. diff --git a/zig/tests/cuda/flashnext_fp8_experts_tests.zig b/zig/tests/cuda/flashnext_fp8_experts_tests.zig index 8ec27578b41..c7f4b0740d1 100644 --- a/zig/tests/cuda/flashnext_fp8_experts_tests.zig +++ b/zig/tests/cuda/flashnext_fp8_experts_tests.zig @@ -184,7 +184,7 @@ pub fn run(gpu: check.Gpu) !void { // every byte 0xff: a pair the call writes changes, the shared slot's must not const act = try r.out(pairs * NI * 2); const y = try r.out(pairs * D * 4); - try flash.moe_native.fp8(&k, r.s, try r.dev(std.mem.sliceAsBytes(picks)), dx, layer, plan, pairs, rows, y, act); + try flash.moe_native.fp8(&k, r.s, try r.dev(std.mem.sliceAsBytes(picks)), dx, layer, plan, pairs, rows, y, act, slots); const got_act = try r.back(u16, act, pairs * NI); const got_y = try r.back(f32, y, pairs * D); for (picks, 0..) |e, p| if (e == experts) { diff --git a/zig/tests/cuda/flashnext_mtp_parity_tests.zig b/zig/tests/cuda/flashnext_mtp_parity_tests.zig index 7566754b431..7b7f62d62b9 100644 --- a/zig/tests/cuda/flashnext_mtp_parity_tests.zig +++ b/zig/tests/cuda/flashnext_mtp_parity_tests.zig @@ -65,7 +65,7 @@ pub fn run(gpu: check.Gpu, dir: []const u8, ids_path: []const u8) !void { const tri: flash.Tri = .{ .s = stream, .own = &glue }; const e = try prompt.Engine.init(gpu.gpa, gpu.io, @constCast(gpu.d), &stream, dir); defer e.deinit(); - const h = try mtp.Head.init(gpu.gpa, gpu.io, @constCast(gpu.d), &stream, dir); + const h = try mtp.Head.init(gpu.gpa, gpu.io, @constCast(gpu.d), &stream, dir, e.widths); defer h.deinit(); const ops: mtp.Ops(flash.Tri) = .{ .e = e, .tri = tri, .h = h }; const ids = try gpu.gpa.alloc(u32, @min(base.items.len, 64)); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ae5d06a0eb5..aaf02232314 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -115,34 +115,34 @@ zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0b zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw zig/src/cuda/vit.zig 0a9200b161e331cf3f5937ff5dcc5c65bcb15e3de8127c277f6a31595d2e5296 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw -zig/src/families/flashnext/cuda_batch.zig f1c5ab1478497ab2c0abdf77776dfed36fa9092579d4306e4320a32cfadf6910 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset) -zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged +zig/src/families/flashnext/cuda_batch.zig be7df0d7465d2bd1b2ce5c7703965d3d12cf372073723080d9911280351e4cc4 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); #3368 (top-k, expert tiles and write-backs take the scratch's slot count; default-shape replies unchanged); #3368 (a block-FP8 projection's BF16 tail rows are computed by a second BF16 matmul and copied into their columns; a checkpoint without weight_scale_inv takes the path it took before) +zig/src/families/flashnext/cuda_batch_state.zig 13315f860327d1fb7cd9987369fd4eba026671d90320fbc11e1af4fc149707ab raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; #3368 (the scratch sized by the checkpoint's slot count and shared width; default-shape replies unchanged); #3368 (the scratch holds a block-FP8 projection's BF16 tail rows; default-shape replies unchanged) zig/src/families/flashnext/cuda_collective.zig bf475ffb46b3440fcad280f46e34de25cd22b79ed96a0b587d0869e7451d3519 raw adds sumBlock, the in-place FP32 reduce-scatter with sum's peer check, deadline and abort; no served change on its own zig/src/families/flashnext/cuda_compare_main.zig ade014dfec88f0b386076cdc093ea20710d7bf36c33ff566ca2caf472064695b raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) -zig/src/families/flashnext/cuda_config.zig 19366ee591270c719fa6f710af0efd4d5a55cfc3e30c923f5ed08771b5c14001 raw +zig/src/families/flashnext/cuda_config.zig c401701861cc3c5a26b86ae9763dfde257a594db66206d7a6577729878454e21 raw #3368 (num_experts_per_tok and shared_expert_intermediate_size select a supported shape, any other refused by name; default-shape replies unchanged) zig/src/families/flashnext/cuda_draft_affine.zig 2ec22bec1a38a6d2cc7e16a65d41deeb452d1a679661351a473652b5f39f2da8 raw zig/src/families/flashnext/cuda_embed.zig f52cee06a9bf820554b5443e9278be7bedf3381ff6d2529902b40c6699de4518 raw zig/src/families/flashnext/cuda_embed_main.zig 2b596788cccd420368fe803676e8ad45a4f0bf7a115a6cd8cbde9151cbf1e597 raw zig/src/families/flashnext/cuda_gdn.zig bc952357f4d6c076542b419b0ee71bbdce89715f0223ab31b4abf821fc2bee62 raw -zig/src/families/flashnext/cuda_glue.zig 0bd837ea17d1bd0a7a0820dc0ee99c4da90113c15d62b3fac31bd7af47a0ecb1 raw +zig/src/families/flashnext/cuda_glue.zig 69b571d2e770f321feb808b8615980e6e204bee120543cf3e04eac56122d8bed raw #3368 (topkMany takes the slot count; default-shape replies unchanged) zig/src/families/flashnext/cuda_hc.zig 01f897ac65d6edd2cd6ac76d97cb4d96619c25ffa85bd619d6d76f4f465cda9a raw zig/src/families/flashnext/cuda_head.zig 734cc1ccea8e99ce9a061273a2dd3042f32e4848b622b5de616aa4b6f546bdd4 raw #3749: TF_FLASHNEXT_SHARD_HEAD read through platform/environment.zig, blank as unset zig/src/families/flashnext/cuda_images.zig ef78a0eb8403a73da2d19bd7ed2aa4b2349a191f408060da79bee3963cd56ff2 raw #3164 (a resumed prompt sends only the images past its kept state) zig/src/families/flashnext/cuda_images_test.zig 4278e5241f6c7e0e710e9a8ddf0482855db158eeee2463200a2c2de32c9dadd7 raw #3164 (resumed image rows tested) zig/src/families/flashnext/cuda_lanes.zig 9c7e764298beab6c239064d0b151729763a374d19e20edb2a94025eda9053ea2 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change), this change (the page pool opens with the load's device and io, for its arena mapped as pages are used; a new paged stream's first prompt step waits while the arena's thread maps its pieces; paging off: unchanged), #2917: one launch description and rank flags change this source; #3164 (resumed image rows passed to the tower), #3219 zig/src/families/flashnext/cuda_lanes_admission_test.zig a87b5320d8cda1f95d254c2148c849005c2158b70afb73da3e32b627e6d2f13d raw -zig/src/families/flashnext/cuda_lanes_load.zig 3911082a7e95c1ffdcf8f6662d2b7b8127112c66794065f2df00bf95fc638fcf raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged) +zig/src/families/flashnext/cuda_lanes_load.zig f01592ba793bebe2354e18536fbd246a773854662cb3917767dd77b6a0253029 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3368 (a captured kernel set with another shape refused by name; the head load takes the engine's widths; default-shape replies unchanged) zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw -zig/src/families/flashnext/cuda_launch.zig f056079d88e9295455bf44bed7ed4053e55fdb8579cfdb392c31a4c3af18e73c raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests +zig/src/families/flashnext/cuda_launch.zig 5a70da9c486932f5812c567d5f8e02b38a1bc25e35dd7cdbc5cdcafab90ae84f raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests; #3368 (topkMany takes the slot count, a captured set serves the default shape only; default-shape replies unchanged) zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw zig/src/families/flashnext/cuda_media_test.zig 4292f8f7c8f8bf4efd0dfaaa5a6c63e11568f85534127a0ce9feb0ab0be05120 raw zig/src/families/flashnext/cuda_mix.zig 248a2a86b3f377531f5b713c408ba99f73604510f4afe34ffae52615d5863c2c raw -zig/src/families/flashnext/cuda_mixed_experts.zig d0362f591e98c2d13581ae48fb75fb7391e41558e08119c6e21e3b34c004e503 raw +zig/src/families/flashnext/cuda_mixed_experts.zig 39ed77ec900b3caa859202c3a81994af53528fb9045b2e69ecb29544ac9a6f3f raw #3368 (the shared expert's width read from its gate_proj rows, widths other than 640 and 1280 refused by name; default-shape replies unchanged) zig/src/families/flashnext/cuda_mlp.zig 8224a28003487487e69eb669be11eaafafdb1ce0bc4c5e57024cef0a6a29e66f raw zig/src/families/flashnext/cuda_modelopt_experts.zig de779975629770b33ad5c0ebf9aa6e334f7a98f173a452d2b7c33b50a08d968e raw zig/src/families/flashnext/cuda_moe.zig 87ba75343c1d228800ed9fcc6d933f1175df172c008e14a8c7a64ff7011bed44 raw -zig/src/families/flashnext/cuda_mtp.zig 63235190fa55742d8819a1b612e998e2c64560b733d05aa5d7b1bd7bfc67f4fa raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run) -zig/src/families/flashnext/cuda_mtp_check.zig 35d9d0ad51171ca2d70a0458f90fe6a04dd5f759fd9f005593c9d1189fb7846d raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) +zig/src/families/flashnext/cuda_mtp.zig 24acb2f6e09eb1e7fbe856ded8de2a9d783590e3dd19464dd837d1914932cda8 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run); #3368 (the MTP layer's shared width must be the main layers' or the routed width, refused by name otherwise; the head takes the engine's widths, so config.json has one reader; default-shape replies unchanged) +zig/src/families/flashnext/cuda_mtp_check.zig 12f99edce811a3c1b3398f57d3ff4b4bfd34b5ddd91d8c9fab61d61f63eaa9f5 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning); #3368 (the drafted check passes the engine's widths to the head; the default shape's tokens unchanged) zig/src/families/flashnext/cuda_mtp_draft.zig 41628480a1071c4a58a229f5e8b42e26fcd030a046ca6796d2dcb2fedb8daf28 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader) zig/src/families/flashnext/cuda_mtp_load.zig d205877fe6d9d6b7b24a0ae061e8fc59a947fdcb1911d38e9f788af2468816c2 raw main 3a56d4eb92 (the draft head's mode read through platform/environment.zig: unset or blank keeps affine4, bf16 keeps the stored rows; kernels and launch counts unchanged) zig/src/families/flashnext/cuda_mtp_ops.zig c6e07580378538c0131fc687003d7559bca8b2318373c1f889ef1a07423ffa3c raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927 @@ -150,14 +150,15 @@ zig/src/families/flashnext/cuda_norms.zig c6ca7f9c1a9049c0f9d512fe2a38c2672a2e96 zig/src/families/flashnext/cuda_ple.zig 417abb05f6cf212c09042bbbd695f313666b13639a81229d9fc6b26e5026b6a2 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning); the shared pass gathers its lanes in one pool call (Split and part reachable from cuda_ple_gather_lanes.zig); every row is the per-stream call's zig/src/families/flashnext/cuda_ple_check.zig e8b7cac1e0d3718f106482f6cff7375c0063e1757c46814bd40da435c83ba8ed raw zig/src/families/flashnext/cuda_ple_nvfp4_test.zig 742bef48f8ddbf7257c18ad78911d519d8a49a2d9fce5885df7377875bf8008c raw -zig/src/families/flashnext/cuda_projection.zig 42e553d337ee5b2acd2146018a4db96bc471a5cc7bc2a87f567ace934b1b40d5 raw -zig/src/families/flashnext/cuda_projection_load.zig 335fb41717d28673c3d58e01627e61d37d5e14cf40722335677dc2d994c73916 raw -zig/src/families/flashnext/cuda_projection_load_test.zig bcbd6ed2753c863916a2163d1cf72544429c776365702e860f52cd22449354a1 raw -zig/src/families/flashnext/cuda_prompt.zig 829c7614d2a8aa4858da5e5d44be67528cc6f07bd9ad9782c492ab41e3575a26 raw TF_FLASHNEXT_FUSED_SPLIT read at engine init; sets only its own native_lane +zig/src/families/flashnext/cuda_projection.zig 9bc7804320f35911b99bb3a821e8f868065fc47af485d21f1ed1a0ff5af5f121 raw #3368 (a projection whose leading parts are block FP8 and whose trailing part is BF16: its FP8G planes and the tail's own BF16 weight; a tail that does not fill a 128-row block splices where the head ends on a block boundary; no checkpoint served today carries weight_scale_inv on these projections) +zig/src/families/flashnext/cuda_projection_load.zig 9bf18f2a9b6ae1d781f164be79968a33933a6e77422bd2cd11eaa845cd00cd92 raw #3368 (the arm a weight_scale_inv selects: block-FP8 parts read through core.quant.fp8, stacked, with a BF16 tail; MXFP8 and affine projections keep the reader they had; its test block reaches the checkpoint-shape tail test) +zig/src/families/flashnext/cuda_projection_load_test.zig d7ce9a94616cc266332ff7369ac725af878eb6ffc0ace3c471290ddf0640ec4d raw #3368 (the block-FP8 loader's tests: hand-built stored planes against the fp8 packers, the binary64 reference, the BF16 tail, and the refusals) +zig/src/families/flashnext/cuda_projection_tail_test.zig c67f3f269d863fd2258dc1e96b4058e2419bcd2bde0a275c8147a2164e825555 raw #3368 (the splicer at INT4-AutoRound's DeltaNet in-projection: 16,384 block-FP8 rows and a 96-row BF16 tail, whose planes are the stored head bytes and the packers' own) +zig/src/families/flashnext/cuda_prompt.zig 824683e42bc214ad26d3b92f2b0fca98f0fd8704edf7f2993cc137fd665e1101 raw TF_FLASHNEXT_FUSED_SPLIT read at engine init; sets only its own native_lane; #3368 (the widths config.json selects size the scratch, a layer's shared rows checked against them; default-shape replies unchanged) zig/src/families/flashnext/cuda_prompt_load.zig 334d68cfca85c15c9d986d0c6b4f8f2a38569309b21bdac6d365935d73c115cd raw zig/src/families/flashnext/cuda_prompt_main.zig 2543cd166dc80cd97b1ca1ce930a6150f9d36b52ee231744606f83bf54f0669d raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) -zig/src/families/flashnext/cuda_prompt_step.zig e04030fb4a4fdb8780704a1bc0b5ba4b786159ab08a927fe32a636a893129d0c raw -zig/src/families/flashnext/cuda_prompt_wt.zig 712eecd6796349dbd0cb0aa1c17465082a27c383c7b849410b252fd74907f709 raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged#3413 (an MLX affine read-out refuses TF_FLASHNEXT_READOUT_FUSED=1 by name; unchanged when unset) +zig/src/families/flashnext/cuda_prompt_step.zig df47388a65fd1b79d91418cde75857cc00bde38dd543e82689eabd71a72368fa raw #3368 (the MLX row write-back's 10 and 11 named by the default slot count; its arguments unchanged) +zig/src/families/flashnext/cuda_prompt_wt.zig 970700ec60bc546b1e642e9c552e180f2e7470a15222b50230b641fec043744d raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged#3413 (an MLX affine read-out refuses TF_FLASHNEXT_READOUT_FUSED=1 by name; unchanged when unset); #3368 (tail_n, the attention indexer's own rows: the widest BF16 tail a block-FP8 projection carries) zig/src/families/flashnext/cuda_qmm.zig 6d035feb053691cc9750a369c86a5463d41ed942764ad85b861bb628c106dccf raw zig/src/families/flashnext/cuda_rank_engine.zig 575ebbf4656d8a064a9e1945527a3a12a54a2879f56d2dbfe0f2e51d3014d102 raw zig/src/families/flashnext/cuda_rank_media.zig e5c268c8cf257934bb49fe401ba6213ea8b108258bbfd4d06edb990d568c3c2b raw