From ae8c811580e5ea63522afd8cddc72d0071e84a29 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:49:05 +0000 Subject: [PATCH 1/2] flash next metal: the scale index is the default, prompt gathers and grouped experts read it, routed arrays are freed TF_FLASHNEXT_SCALE_INDEX is now on by default on GPUs without tensor units. The loader indexes every 4-bit group-32 expert projection once at load, on up to eight threads. The routed gate, up and down projections, which only expert kernels read, release their stored scales and biases and keep the index and table in those slots; the shared projections keep theirs beside the index, since kernels outside the expert set read them direct. The prompt gathers (32, 64 and 128-row tiles and the fused gate/up) and the grouped expert kernels now read each group's pair through the index, as the per-row expert kernels already did: the same two values into the same sums, so replies keep their tokens. An index is keyed by its projection's codes buffer, and a kernel takes the indexed form only for a projection that has one. A tensor with more pairs than a 16-bit index holds turns the index off with a warning, as before. The indexed gathers and the indexed grouped launches register with the kernel contract as bit-preserving replacements of the direct reads, each with a planted control and launch records. Refs #2751 --- docs/environment.md | 2 +- docs/recipes/qwen3.8-flash-next.md | 11 +- zig/flashnext_host.zig | 1 + .../core/contract/prompt_index_records.zig | 15 ++ zig/src/core/contract/registry_joins.zig | 1 + zig/src/families/flashnext/engine_load.zig | 13 +- zig/src/families/flashnext/experts4.zig | 33 +++ .../families/flashnext/grouped_fixture.zig | 48 +++-- zig/src/families/flashnext/gx.zig | 13 +- .../flashnext/prompt_index_fixture.zig | 204 ++++++++++++++++++ .../flashnext/prompt_index_source.zig | 34 +++ zig/src/families/flashnext/prompt_w.zig | 46 ++-- zig/src/families/flashnext/replay_run.zig | 2 +- zig/src/families/flashnext/scale_index.zig | 125 ++++++++--- zig/src/families/flashnext/variants.zig | 7 +- zig/src/platform/environment.zig | 2 +- zig/src/tensorfold.zig | 1 + .../contract/metal_flashnext_grouped.zig | 10 +- .../contract/metal_flashnext_prompt_index.zig | 97 +++++++++ zig/tests/contract/metal_limits.zig | 10 +- zig/tests/contract/metal_main.zig | 18 +- 21 files changed, 603 insertions(+), 90 deletions(-) create mode 100644 zig/src/core/contract/prompt_index_records.zig create mode 100644 zig/src/families/flashnext/prompt_index_fixture.zig create mode 100644 zig/src/families/flashnext/prompt_index_source.zig create mode 100644 zig/tests/contract/metal_flashnext_prompt_index.zig diff --git a/docs/environment.md b/docs/environment.md index ef2b9e47c8b..e5b9b4e3544 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -50,7 +50,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | -| `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; `1` has the 4-bit expert kernels read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values with fewer weight bytes; default 0 | +| `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | | `TF_QWEN27_SLOT_RESUME` | Qwen3.8-27B on Metal: exactly `0` or `1`; `0` stops slot 0 resuming a later prompt; unset or blank keeps it on | | `TF_QWEN27_METAL_KV_PAGES` | Qwen3.8-27B on Metal: exactly `0` or `1`; `1` puts keys and values in core-pool pages (refused on Macs with tensor units); unset or blank is `0` | diff --git a/docs/recipes/qwen3.8-flash-next.md b/docs/recipes/qwen3.8-flash-next.md index 5aeacfa3660..e0bc830e067 100644 --- a/docs/recipes/qwen3.8-flash-next.md +++ b/docs/recipes/qwen3.8-flash-next.md @@ -58,11 +58,12 @@ the lane matmul; M1 through M4 use the per-row projection and hyper-connection k restore recurrent state, n-gram history and attention state, including incomplete pooled blocks. The load-time row check disables drafting when windows do not reproduce serial steps. -`TF_FLASHNEXT_SCALE_INDEX=1` (off by default; M1 through M4, 4-bit experts in groups of 32) has the expert kernels read -each group's scale and bias through a 16-bit index into its tensor's table of distinct pairs, built at load. The -kernels get the same two values from 10% fewer weight bytes, so every reply keeps its tokens. Prompt passes still read -the stored scales and biases, so the index is held beside them. The setting does nothing with tensor units, -`--ssd-experts` or speed-up mode, and a tensor with more than 65,536 distinct pairs turns it off with a warning. +On M1 through M4, expert projections stored at 4 bits in groups of 32 are read through a scale index: at load each +tensor's (scale, bias) pairs become a table and a 16-bit index a group, and the decode, grouped and prompt-gather +expert kernels read each group's pair through it. They get the same two values from 10% fewer weight bytes, so every +reply keeps its tokens, and the routed experts' stored scales and biases are released once indexed. +`TF_FLASHNEXT_SCALE_INDEX=0` keeps and reads the stored arrays instead. The index is not built with tensor units or +`--ssd-experts`, nor for 6-bit packs, and a tensor with more than 65,536 distinct pairs turns it off with a warning. On M1 through M4, a decode window of five rows or more runs its 4-bit experts grouped by expert: rows that picked the same expert share its launch, so a copy or repeat stretch reads each expert's weights once instead of once a diff --git a/zig/flashnext_host.zig b/zig/flashnext_host.zig index 01c153ccd96..0ad1612e341 100644 --- a/zig/flashnext_host.zig +++ b/zig/flashnext_host.zig @@ -7,6 +7,7 @@ test { _ = @import("src/families/flashnext/rows_w.zig"); _ = @import("src/families/flashnext/experts4.zig"); _ = @import("src/families/flashnext/scale_pairs.zig"); + _ = @import("src/families/flashnext/prompt_index_source.zig"); _ = @import("src/families/flashnext/tree.zig"); _ = @import("src/families/flashnext/gate.zig"); _ = @import("src/families/flashnext/gx.zig"); diff --git a/zig/src/core/contract/prompt_index_records.zig b/zig/src/core/contract/prompt_index_records.zig new file mode 100644 index 00000000000..1aa95c7b15d --- /dev/null +++ b/zig/src/core/contract/prompt_index_records.zig @@ -0,0 +1,15 @@ +//! The indexed prompt gathers: the 128-thread groups the patched text reserves, and the gathers' dequantized tiles. +const M = @import("limits.zig").MetalLaunch; +const tile = @import("fsr_records.zig").gather_memory; +pub const metal = [_]M{ + .{ .name = "flashnext prompt index tf_gather_qmmw_nax_32", .threads = 128, .tg_memory = tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_qmmw_nax_64", .threads = 128, .tg_memory = tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_qmmw_nax_128", .threads = 128, .tg_memory = tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_guw_nax_32", .threads = 128, .tg_memory = 2 * tile, .reserved = 128 }, + .{ .name = "flashnext prompt index tf_gather_guw_nax_64", .threads = 128, .tg_memory = 2 * tile, .reserved = 128 }, + .{ .name = "flashnext grouped index gx_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "flashnext grouped index gx_list", .threads = 512, .tg_memory = 7488, .reserved = 512 }, + .{ .name = "flashnext grouped index gx_gateup", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "flashnext grouped index gx_down_one", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "flashnext grouped index gx_down_tile", .threads = 64, .tg_memory = 1280, .reserved = 64 }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 86eb07d031d..110164ff9cd 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -63,6 +63,7 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("glm_rows_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("grouped_records.zig").metal ++ + @import("prompt_index_records.zig").metal ++ @import("hc_activation_records.zig").metal ++ @import("qwen4_records.zig").metal ++ @import("lfm2_records.zig").records ++ diff --git a/zig/src/families/flashnext/engine_load.zig b/zig/src/families/flashnext/engine_load.zig index 793859136f6..5cb22e3cc8d 100644 --- a/zig/src/families/flashnext/engine_load.zig +++ b/zig/src/families/flashnext/engine_load.zig @@ -206,7 +206,7 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { } const m = try arena.create(Model); m.* = .{ .r = r, .cap = r.window.capacity, .layers = undefined, .mix = undefined, .head = undefined, .embed = undefined, .ple = undefined, .t = undefined }; - r.sb_index = try platform.environment.read(bool, "TF_FLASHNEXT_SCALE_INDEX", false) and r.fsr == null and r.tp == null and !r.device.tensorUnits(); + r.sb_index = try platform.environment.read(bool, "TF_FLASHNEXT_SCALE_INDEX", true) and r.fsr == null and !r.device.tensorUnits(); for (0..LAYERS) |i| { const linear = i % 4 != 3; var L: Layer = .{ .ahc = try hcOf(r, "L{d}.ahc", .{i}), .mhc = try hcOf(r, "L{d}.mhc", .{i}), .linear = linear, .proj = undefined, .out = undefined, .router = try r.loadf("L{d}.moe.router", .{i}), .ex = undefined }; @@ -235,7 +235,6 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { } } if (r.xpack) try r.repack(&L.ex); - if (r.sb_index) try @import("scale_index.zig").addAll(r, &L.ex); m.layers[i] = L; } m.mix = try hcOf(r, "mix", .{}); @@ -333,7 +332,6 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { } } if (r.xpack) try r.repack(&ex); - if (r.sb_index) try @import("scale_index.zig").addAll(r, &ex); m.mtp = .{ .ahc = try hcOf(r, "mtp.ahc", .{}), .mhc = try hcOf(r, "mtp.mhc", .{}), @@ -386,6 +384,15 @@ fn finishLoad(context: Construction, r: *Run) !*Engine { e.r = r; e.m = m; + if (r.sb_index) { // before the prompt kernels compile: they read the routed experts through the index too + var widths = try @import("widths.zig").Widths.init(arena, &cfg); + defer widths.deinit(); + const ws = try @import("engine_widths.zig").read(&cfg, &widths, r.ngram); + var sets: [LAYERS + 1]@import("scale_index.zig").Set = undefined; + for (&m.layers, 0..) |*L, i| sets[i] = .{ .ex = &L.ex, .xw = ws.layers[i] }; + sets[LAYERS] = .{ .ex = &m.mtp.ex, .xw = ws.mtp }; + try @import("scale_index.zig").build(r, &sets); + } e.pr = try arena.create(Prompt); e.pr.* = try Prompt.init(r, pack_dir, r.xnew_header); const uniform = try @import("engine_widths.zig").apply(arena, &cfg, index.object.get("weight_map").?.object, e.pr, m); diff --git a/zig/src/families/flashnext/experts4.zig b/zig/src/families/flashnext/experts4.zig index 5a79ae2f261..ab6dc064d8d 100644 --- a/zig/src/families/flashnext/experts4.zig +++ b/zig/src/families/flashnext/experts4.zig @@ -117,6 +117,29 @@ pub fn indexed(a: std.mem.Allocator, text: []const u8, consts: []const Const) ![ return out; } +/// The grouped tile kernel's reads (fn_gx.metal): its scale row is the index row, its bias pointer the table. +const tile_reads = [_][2][]const u8{ + .{ "const device bfloat* db = (shared ? SDB : DB) + so;", "const device bfloat* db = shared ? SDB : DB;" }, + .{ "const float sc = float(ds[c / 2]), bi = float(db[c / 2]);", "const uint ti = uint(((const device ushort*)ds)[c / 2]) * 2u; const float sc = float(db[ti]), bi = float(db[ti + 1]);" }, +}; + +/// fn_gx.metal reading each scale and bias through the index and the table, as `indexed` has the recorded kernels. +pub fn indexedGrouped(a: std.mem.Allocator, text: []const u8) ![]const u8 { + var out = text; + var hits: usize = 0; + for (index_reads) |r| { + hits += std.mem.count(u8, out, r[0]); + out = try std.mem.replaceOwned(u8, a, out, r[0], r[1]); + } + for (tile_reads) |r| { + if (std.mem.count(u8, out, r[0]) != 1) return error.KernelPatch; + out = try std.mem.replaceOwned(u8, a, out, r[0], r[1]); + } + if (hits != 4) return error.KernelPatch; + for ([_][]const u8{ "Sp[at])", "float(S[at])", "float(db[c / 2])" }) |direct| if (std.mem.indexOf(u8, out, direct) != null) return error.KernelPatch; + return out; +} + const calls = [2][2][]const u8{ .{ "down_rows(SDW, SDS, SDB, size_t(d0), x, lane, out)", "down_rows_bal(SDW, SDS, SDB, size_t(d0), x, lane, out)" }, .{ "down_rows(DW, DS, DB, size_t(PICK[r * TOPK + k]) * D + d0, x, lane, out)", "down_rows_bal(DW, DS, DB, size_t(PICK[r * TOPK + k]) * D + d0, x, lane, out)" }, @@ -217,3 +240,13 @@ test "the recorded 4/32 expert gate/up takes a row count from buffer 17, once; t } try std.testing.expectEqual(@as(usize, 1), seen); } + +test "the grouped kernels read every scale and bias through the index once patched" { + const ks = @import("kernel_sources"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const out = try indexedGrouped(arena.allocator(), ks.flashnext_gx); + const casts = "(const device ushort*)"; // five index reads beside the casts the kernels already have + try std.testing.expectEqual(std.mem.count(u8, ks.flashnext_gx, casts) + 5, std.mem.count(u8, out, casts)); + try std.testing.expectError(error.KernelPatch, indexedGrouped(arena.allocator(), out)); +} diff --git a/zig/src/families/flashnext/grouped_fixture.zig b/zig/src/families/flashnext/grouped_fixture.zig index 7cb745546bb..51e0bee03cc 100644 --- a/zig/src/families/flashnext/grouped_fixture.zig +++ b/zig/src/families/flashnext/grouped_fixture.zig @@ -4,6 +4,8 @@ const mtl = @import("metal"); const variants = @import("variants.zig"); const names = @import("fsr_contract_source.zig"); const gx = @import("gx.zig"); +const pairs = @import("scale_pairs.zig"); +const ks = @import("kernel_sources"); const Buf = @import("replay.zig").Buf; pub const d = 2560; @@ -23,6 +25,11 @@ pub fn text(a: std.mem.Allocator, gate: bool) ![]const u8 { return variants.source(a, try names.recorded(file), &at4, true, false, gate, false); } +/// fn_gx.metal as the loader compiles it; `indexed` with every scale and bias read through the index. +pub fn groupedText(a: std.mem.Allocator, indexed: bool) ![]const u8 { + return if (indexed) @import("experts4.zig").indexedGrouped(a, ks.flashnext_gx) else ks.flashnext_gx; +} + /// Groups of 32 weights in projection j: gate, up, shared gate, shared up, down, shared down. fn groups(j: usize) usize { const routed: usize = if (j == 0 or j == 1 or j == 4) held else 1; @@ -36,9 +43,10 @@ pub const Fixture = struct { queue: mtl.Queue, rows: usize, w: [18]Ref, // each projection's weight, scales and biases + ix: [6][2]Ref, // each projection's index and table io: [7]Ref, // input rows, logits, row count, then act, picks, weights and y direct: [2]mtl.Pipeline, // the recorded gate/up and down - grouped: gx.Gx, + grouped: [2]gx.Gx, // reading scales and biases direct, and through the index libraries: std.ArrayList(mtl.Library) = .empty, pipelines: std.ArrayList(mtl.Pipeline) = .empty, buffers: std.ArrayList(Ref) = .empty, @@ -49,10 +57,12 @@ pub const Fixture = struct { pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, rows: usize, seed: u64, nonfinite: bool) !*Fixture { if (rows == 0 or rows > gx.rmax) return error.GroupedFixtureShape; const p = try a.create(Fixture); - p.* = .{ .memory = .init(a), .a = undefined, .queue = queue, .rows = rows, .w = undefined, .io = undefined, .direct = undefined, .grouped = undefined }; + p.* = .{ .memory = .init(a), .a = undefined, .queue = queue, .rows = rows, .w = undefined, .ix = undefined, .io = undefined, .direct = undefined, .grouped = undefined }; errdefer p.deinit(a); p.a = p.memory.allocator(); var random: std.Random.DefaultPrng = .init(seed); + const table = try p.a.create([pairs.most]u32); + const seen = try p.a.create([pairs.slots]u32); for (0..6) |j| { const n = groups(j); const codes = try p.a.alloc(u8, n * 16); @@ -69,6 +79,9 @@ pub const Fixture = struct { p.w[j * 3] = try p.make(device, codes); p.w[j * 3 + 1] = try p.make(device, std.mem.sliceAsBytes(s)); p.w[j * 3 + 2] = try p.make(device, std.mem.sliceAsBytes(b)); + const index = try p.a.alloc(u16, n); + const count = try pairs.index(s, b, index, table, seen); + p.ix[j] = .{ try p.make(device, std.mem.sliceAsBytes(index)), try p.make(device, std.mem.sliceAsBytes(try p.a.dupe(u32, table[0..count]))) }; } const h = try p.a.alloc(u16, rows * d); for (h, 0..) |*v, i| v.* = bf16(@as(f32, @floatFromInt((i * 7 + seed) % 23)) / 64 - 0.125); @@ -92,15 +105,17 @@ pub const Fixture = struct { p.direct[k] = try mtl.Pipeline.init(device, lib, try std.fmt.allocPrintSentinel(p.a, "{s}", .{if (gate) names.gate else names.down}, 0), false); try p.pipelines.append(p.a, p.direct[k]); } - const lib = try gx.library(device); - try p.libraries.append(p.a, lib); - for (gx.functions, &p.grouped.pipes) |name, *pipe| { - pipe.* = try mtl.Pipeline.init(device, lib, name, false); - try p.pipelines.append(p.a, pipe.*); - } p.list = try device.buffer(gx.list_bytes, mtl.ResourceOptions.shared); - p.grouped.buf = p.list.?; - p.grouped.min_rows = 1; + for ([_]bool{ false, true }, &p.grouped) |indexed, *g| { + const lib = try gx.library(p.a, device, indexed); + try p.libraries.append(p.a, lib); + for (gx.functions, &g.pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + try p.pipelines.append(p.a, pipe.*); + } + g.buf = p.list.?; + g.min_rows = 1; + } return p; } @@ -142,16 +157,21 @@ pub const Fixture = struct { return .{ .b = ref.buffer, .off = 64 }; } - /// Act, picks, weights and y after the recorded launches, or after gx.zig's when `by_expert`. - pub fn run(p: *Fixture, by_expert: bool) ![]const u8 { + /// Act, picks, weights and y after the recorded launches, or gx.zig's when `by_expert` (`indexed`: on the index). + pub fn run(p: *Fixture, by_expert: bool, indexed: bool) ![]const u8 { for (p.io[3..]) |ref| @memset(p.bytes(ref), 0); const cb = p.queue.commandBuffer(); const e = cb.compute(.serial); if (by_expert) { var w: [18]Buf = undefined; for (p.w, &w) |ref, *out| out.* = buf(ref); - if (p.wrong_scales) std.mem.swap(Buf, &w[1], &w[4]); // the control: gate and up scales change places - p.grouped.launch(e, false, buf(p.io[0]), buf(p.io[1]), w, buf(p.io[3]), buf(p.io[4]), buf(p.io[5]), buf(p.io[2]), buf(p.io[6]), p.rows); + if (indexed) for (p.ix, 0..) |pair, j| { + w[j * 3 + 1] = buf(pair[0]); + w[j * 3 + 2] = buf(pair[1]); + }; + const slot: usize = if (indexed) 2 else 1; // the control: gate and up scales (indexed: their tables) change places + if (p.wrong_scales) std.mem.swap(Buf, &w[slot], &w[slot + 3]); + p.grouped[@intFromBool(indexed)].launch(e, false, buf(p.io[0]), buf(p.io[1]), w, buf(p.io[3]), buf(p.io[4]), buf(p.io[5]), buf(p.io[2]), buf(p.io[6]), p.rows); } else { e.setPipeline(p.direct[0]); bind(e, 0, p.io[0]); diff --git a/zig/src/families/flashnext/gx.zig b/zig/src/families/flashnext/gx.zig index 3def2dc4819..16b63a2a67a 100644 --- a/zig/src/families/flashnext/gx.zig +++ b/zig/src/families/flashnext/gx.zig @@ -24,7 +24,9 @@ pub const Gx = struct { /// The routed and shared experts for `rows` rows (at most rmax; the kernels read the count from `rows_buf`). pub fn encode(g: *const Gx, r: *Run, x: Buf, lg: Buf, e: [18]Buf, act: Buf, pick: Buf, wts: Buf, rows_buf: Buf, y: Buf, rows: usize) void { if (r.skip & (1 << 2) != 0) return; - g.launch(r.enc, !r.serial, x, lg, e, act, pick, wts, rows_buf, y, rows); + var bound = e; + if (r.sb_index) @import("scale_index.zig").bind(r, &bound, true, true) catch return; // init checked each set + g.launch(r.enc, !r.serial, x, lg, bound, act, pick, wts, rows_buf, y, rows); } /// The five launches on `enc`; `barriers` for a concurrent encoder, where each waits for the one it reads. @@ -63,14 +65,15 @@ pub fn applies(w: variants.Experts) bool { return std.mem.eql(usize, &w.gu, &four) and std.mem.eql(usize, &w.down, &four); } -/// fn_gx.metal compiled as the loader compiles it. -pub fn library(device: mtl.Device) !mtl.Library { - return mtl.Library.fromSource(device, ks.flashnext_gx, mtl.CompileOptions.mlx()); +/// fn_gx.metal compiled as the loader compiles it; `indexed` reads scales and biases through scale_index's tables. +pub fn library(a: std.mem.Allocator, device: mtl.Device, indexed: bool) !mtl.Library { + const text = if (indexed) try @import("experts4.zig").indexedGrouped(a, ks.flashnext_gx) else ks.flashnext_gx; + return mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); } /// The grouped kernels for windows of `min_rows` rows or more (at most rmax). pub fn init(r: *Run, min_rows: usize) !*Gx { - const lib = try r.ownResource(try library(r.device)); + const lib = try r.ownResource(try library(r.arena, r.device, r.sb_index)); const g = try r.arena.create(Gx); var pipes: [functions.len]mtl.Pipeline = undefined; for (functions, &pipes) |name, *p| p.* = try r.ownResource(try mtl.Pipeline.init(r.device, lib, name, false)); diff --git a/zig/src/families/flashnext/prompt_index_fixture.zig b/zig/src/families/flashnext/prompt_index_fixture.zig new file mode 100644 index 00000000000..3d3d8b0b78d --- /dev/null +++ b/zig/src/families/flashnext/prompt_index_fixture.zig @@ -0,0 +1,204 @@ +//! The 4/32 prompt gathers reading scales and biases direct and through scale_pairs' index, on the same stored bytes. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +const qmmw_source = @import("../../core/qmmw_source.zig"); +const index_source = @import("prompt_index_source.zig"); +const pairs = @import("scale_pairs.zig"); + +pub const d = 2560; +pub const inner = 640; +pub const experts = 8; +/// The gathers by tile size, then the fused gate/up gathers. +pub const functions = [_][:0]const u8{ "tf_gather_qmmw_nax_32", "tf_gather_qmmw_nax_64", "tf_gather_qmmw_nax_128", "tf_gather_guw_nax_32", "tf_gather_guw_nax_64" }; +const tiles = [_]usize{ 32, 64, 128, 32, 64 }; + +pub const Ref = struct { buffer: mtl.Buffer, size: usize }; + +/// qmmw_nax.metal at 4/32 before nax.h is inlined; `indexed` as the loader patches it for the gathers. +pub fn text(a: std.mem.Allocator, indexed: bool) ![]const u8 { + return qmmw_source.source(a, if (indexed) try index_source.patch(a, ks.flashnext_qmmw) else ks.flashnext_qmmw, 4, 32); +} + +/// Projection j's outputs and inputs: gate and up [inner, d], down [d, inner]. +fn shape(j: usize) [2]usize { + return if (j < 2) .{ inner, d } else .{ d, inner }; +} + +pub const Fixture = struct { + memory: std.heap.ArenaAllocator, + a: std.mem.Allocator, + queue: mtl.Queue, + rows: usize, + w: [9]Ref, // gate, up and down: weight, scales and biases + ix: [3][2]Ref, // each projection's index and table + io: [3]Ref, // input rows [rows, d], activation rows [rows, inner], each expert's first row + out: [8]Ref, // gate by 32, 64 and 128-row tiles, gate/up by 32 and 64, down by 32, 64 and 128 + pipes: [2][functions.len]mtl.Pipeline, // direct, indexed + libraries: std.ArrayList(mtl.Library) = .empty, + pipelines: std.ArrayList(mtl.Pipeline) = .empty, + buffers: std.ArrayList(Ref) = .empty, + stored: std.ArrayList([]const u8) = .empty, + wrong_entry: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, rows: usize, seed: u64, nonfinite: bool) !*Fixture { + if (rows < experts or rows > 512) return error.PromptIndexFixtureShape; + const p = try a.create(Fixture); + p.* = .{ .memory = .init(a), .a = undefined, .queue = queue, .rows = rows, .w = undefined, .ix = undefined, .io = undefined, .out = undefined, .pipes = undefined }; + errdefer p.deinit(a); + p.a = p.memory.allocator(); + var random: std.Random.DefaultPrng = .init(seed); + const table = try p.a.create([pairs.most]u32); + const seen = try p.a.create([pairs.slots]u32); + for (0..3) |j| { + const n = experts * shape(j)[0] * (shape(j)[1] / 32); + const codes = try p.a.alloc(u8, n * 16); + random.random().bytes(codes); + const s = try p.a.alloc(u16, n); + const b = try p.a.alloc(u16, n); + for (s, b, 0..) |*sv, *bv, i| { + sv.* = bf16(@as(f32, @floatFromInt(1 + (i * 13 + seed + j) % 97)) / 4096); + bv.* = bf16(-@as(f32, @floatFromInt((i * 5 + seed) % 31)) / 4096); + } + if (nonfinite) for ([_]u16{ 0x7fc0, 0x7f80, 0xff80 }, 0..) |v, i| { + s[i * (n / 3)] = v; + }; + const index = try p.a.alloc(u16, n); + const count = try pairs.index(s, b, index, table, seen); + p.w[j * 3] = try p.make(device, codes); + p.w[j * 3 + 1] = try p.make(device, std.mem.sliceAsBytes(s)); + p.w[j * 3 + 2] = try p.make(device, std.mem.sliceAsBytes(b)); + p.ix[j] = .{ try p.make(device, std.mem.sliceAsBytes(index)), try p.make(device, std.mem.sliceAsBytes(try p.a.dupe(u32, table[0..count]))) }; + } + const x = try p.a.alloc(u16, rows * d); + for (x, 0..) |*v, i| v.* = bf16(@as(f32, @floatFromInt((i * 7 + seed) % 23)) / 64 - 0.125); + const act = try p.a.alloc(u16, rows * inner); + for (act, 0..) |*v, i| v.* = bf16(@as(f32, @floatFromInt((i * 11 + seed) % 19)) / 32 - 0.25); + // every expert's first row: expert 0 always has rows, one expert has none, the last takes what is left + const first = try p.a.alloc(i32, experts); + var at: usize = 0; + for (first, 0..) |*v, e| { + v.* = @intCast(at); + const share = if (e == 3) 0 else 1 + (e * 5 + seed) % (2 * rows / experts); + at = @min(rows, at + share); + } + p.io[0] = try p.make(device, std.mem.sliceAsBytes(x)); + p.io[1] = try p.make(device, std.mem.sliceAsBytes(act)); + p.io[2] = try p.make(device, std.mem.sliceAsBytes(first)); + for (&p.out, 0..) |*o, k| { + const width: usize = if (k < 5) inner else d; + o.* = try p.make(device, try p.a.alloc(u8, rows * width * 2)); + } + for ([_]bool{ false, true }, 0..) |indexed, k| { + const lib = try mtl.Library.fromSource(device, try frags.sourceMode(device, p.a, try text(p.a, indexed), false), mtl.CompileOptions.mlx()); + try p.libraries.append(p.a, lib); + for (functions, &p.pipes[k]) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + try p.pipelines.append(p.a, pipe.*); + } + } + return p; + } + + fn bf16(x: f32) u16 { + const bits: u32 = @bitCast(x); + return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + } + + /// A guarded device buffer holding `data`, which the fixture keeps to prove the kernels left it alone. + fn make(p: *Fixture, device: mtl.Device, data: []const u8) !Ref { + const b = try device.buffer(data.len + 128, mtl.ResourceOptions.shared); + errdefer b.deinit(); + @memset(b.contents()[0 .. data.len + 128], 0xa5); + const ref: Ref = .{ .buffer = b, .size = data.len }; + @memcpy(p.bytes(ref), data); + try p.buffers.append(p.a, ref); + try p.stored.append(p.a, data); + return ref; + } + + pub fn deinit(p: *Fixture, a: std.mem.Allocator) void { + for (p.buffers.items) |b| b.buffer.deinit(); + for (p.pipelines.items) |pipe| pipe.deinit(); + for (p.libraries.items) |lib| lib.deinit(); + p.memory.deinit(); + a.destroy(p); + } + + pub fn bytes(_: *const Fixture, ref: Ref) []u8 { + return ref.buffer.contents()[64..][0..ref.size]; + } + + fn bind(e: mtl.ComputeEncoder, at: usize, ref: Ref) void { + e.setBuffer(ref.buffer, 64, at); + } + + /// Projection j's weight, scales and biases as a launch binds them: the index and table when `indexed`. + fn weights(p: *const Fixture, j: usize, indexed: bool) [3]Ref { + return if (indexed) .{ p.w[j * 3], p.ix[j][0], p.ix[j][1] } else .{ p.w[j * 3], p.w[j * 3 + 1], p.w[j * 3 + 2] }; + } + + /// Every gather's output in `out`'s order, as Prompt.gather and gatherGU launch them. + pub fn run(p: *Fixture, indexed: bool) ![]const u8 { + for (p.out) |ref| @memset(p.bytes(ref), 0); + if (indexed and p.wrong_entry) p.swapPairs(); + defer if (indexed and p.wrong_entry) p.swapPairs(); + const cb = p.queue.commandBuffer(); + const e = cb.compute(.serial); + for (p.out, 0..) |y, k| { + const which = if (k < 5) k else k - 5; // the down gathers reuse the three plain gathers + const fused = k == 3 or k == 4; + const n: usize = if (k < 5) inner else d; + const inputs_k: usize = if (k < 5) d else inner; + const prm = [4]i32{ @intCast(p.rows), @intCast(n), @intCast(inputs_k), experts }; + e.setPipeline(p.pipes[@intFromBool(indexed)][which]); + bind(e, 0, p.io[if (k < 5) 0 else 1]); + var at: usize = 1; + for (p.weights(if (k < 5) 0 else 2, indexed)) |ref| { + bind(e, at, ref); + at += 1; + } + if (fused) for (p.weights(1, indexed)) |ref| { + bind(e, at, ref); + at += 1; + }; + bind(e, at, p.io[2]); + e.setBytes(std.mem.asBytes(&prm), at + 1); + bind(e, at + 2, y); + e.dispatchThreads(mtl.Size.of(((n + 63) / 64) * 128, p.rows / tiles[which] + experts, 1), mtl.Size.of(128, 1, 1)); + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.PromptIndexFixtureGpuFailure; + var all: std.ArrayList(u8) = .empty; + for (p.out) |ref| try all.appendSlice(p.a, p.bytes(ref)); + return all.items; + } + + /// The control: the gate's first two table pairs change places. + fn swapPairs(p: *Fixture) void { + const table = p.bytes(p.ix[0][1]); + var pair: [4]u8 = undefined; + @memcpy(&pair, table[0..4]); + @memcpy(table[0..4], table[4..8]); + @memcpy(table[4..8], &pair); + } + + /// Every input the kernels read, in one slice. + pub fn inputs(p: *Fixture, a: std.mem.Allocator, out: *std.ArrayList(u8)) !void { + for (p.buffers.items[0 .. p.buffers.items.len - p.out.len]) |ref| try out.appendSlice(a, p.bytes(ref)); + } + + /// Guards whole and every input as stored. + pub fn intact(p: *Fixture) bool { + for (p.buffers.items, p.stored.items, 0..) |b, data, i| { + const all = b.buffer.contents()[0 .. b.size + 128]; + for (all[0..64]) |v| if (v != 0xa5) return false; + for (all[64 + b.size ..]) |v| if (v != 0xa5) return false; + if (i + p.out.len < p.buffers.items.len and !std.mem.eql(u8, p.bytes(b), data)) return false; + } + return true; + } +}; diff --git a/zig/src/families/flashnext/prompt_index_source.zig b/zig/src/families/flashnext/prompt_index_source.zig new file mode 100644 index 00000000000..eab8c7cd957 --- /dev/null +++ b/zig/src/families/flashnext/prompt_index_source.zig @@ -0,0 +1,34 @@ +//! qmmw_nax.metal's expert gathers reading scales and biases through scale_index's index and table. +const std = @import("std"); + +/// Each read of the two K loops and each gather's row pointers: the scale row is the index row, the bias the table. +const reads = [_][2][]const u8{ + .{ " T sc = srow[hk / WG], bi = brow[hk / WG];\n", " const device ushort* ixrow = (const device ushort*)srow;\n uint si = uint(ixrow[hk / WG]) * 2u;\n T sc = brow[si], bi = brow[si + 1];\n" }, + .{ " sc = srow[(hk + k + 64) / WG];\n bi = brow[(hk + k + 64) / WG];\n", " si = uint(ixrow[(hk + k + 64) / WG]) * 2u;\n sc = brow[si];\n bi = brow[si + 1];\n" }, + .{ " T gs = sg[hk / WG], gbi = bg[hk / WG], us = su[hk / WG], ubi = bu[hk / WG];\n", " const device ushort* ixg = (const device ushort*)sg;\n const device ushort* ixu = (const device ushort*)su;\n uint gi = uint(ixg[hk / WG]) * 2u, ui = uint(ixu[hk / WG]) * 2u;\n T gs = bg[gi], gbi = bg[gi + 1], us = bu[ui], ubi = bu[ui + 1];\n" }, + .{ " gs = sg[g];\n gbi = bg[g];\n us = su[g];\n ubi = bu[g];\n", " gi = uint(ixg[g]) * 2u;\n ui = uint(ixu[g]) * 2u;\n gs = bg[gi];\n gbi = bg[gi + 1];\n us = bu[ui];\n ubi = bu[ui + 1];\n" }, + .{ "W + wrow * WPR + WB * (t % 2), S + wrow * KG, B + wrow * KG, 0, tile, tn, uint(t),", "W + wrow * WPR + WB * (t % 2), S + wrow * KG, B, 0, tile, tn, uint(t)," }, + .{ "WG_ + wrow * WPR + WB * (t % 2), SG + wrow * KG, BG + wrow * KG,", "WG_ + wrow * WPR + WB * (t % 2), SG + wrow * KG, BG," }, + .{ "WU + wrow * WPR + WB * (t % 2), SU + wrow * KG, BU + wrow * KG, tile_g, tile_u, tn,", "WU + wrow * WPR + WB * (t % 2), SU + wrow * KG, BU, tile_g, tile_u, tn," }, + .{ "[[kernel]] void tf_gather_qmmw_nax_##BM(", "[[max_total_threads_per_threadgroup(128)]] [[kernel]] void tf_gather_qmmw_nax_##BM(" }, + .{ "[[kernel]] void tf_gather_guw_nax_##BM(", "[[max_total_threads_per_threadgroup(128)]] [[kernel]] void tf_gather_guw_nax_##BM(" }, +}; + +/// `text` for the gather kernels alone: the dense kernels share the patched loops, so they keep the unpatched text. +pub fn patch(a: std.mem.Allocator, text: []const u8) ![]const u8 { + var out = text; + for (reads) |r| { + if (std.mem.count(u8, out, r[0]) != 1) return error.KernelPatch; + out = try std.mem.replaceOwned(u8, a, out, r[0], r[1]); + } + return out; +} + +test "every scale and bias read of the prompt gathers goes through the index once patched" { + const ks = @import("kernel_sources"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const out = try patch(arena.allocator(), ks.flashnext_qmmw); + for ([_][]const u8{ "srow[", "sg[", "su[", "brow[hk", "bg[hk", "bu[hk", "bg[g]", "bu[g]" }) |direct| try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, out, direct)); + try std.testing.expectError(error.KernelPatch, patch(arena.allocator(), out)); +} diff --git a/zig/src/families/flashnext/prompt_w.zig b/zig/src/families/flashnext/prompt_w.zig index 0db704c2e49..300fac5be17 100644 --- a/zig/src/families/flashnext/prompt_w.zig +++ b/zig/src/families/flashnext/prompt_w.zig @@ -1,5 +1,6 @@ //! Prompt products at any MLX width: qmmw_nax compiled per (bits, group), and which weights take which width. const std = @import("std"); +const scale_index = @import("scale_index.zig"); const mtl = @import("metal"); pub const ks = @import("kernel_sources"); const frags = @import("../../core/frags.zig"); @@ -11,7 +12,9 @@ const Model = replay.Model; const variants = @import("variants.zig"); /// One width's kernels: dense, split-K, sorted-expert gathers (32, 64, 128 rows) and fused gate/up (32, 64 rows). -pub const Pipes = struct { qmm: mtl.Pipeline, splitk: mtl.Pipeline, gather: [3]mtl.Pipeline, gu: [2]mtl.Pipeline }; +pub const Pipes = struct { qmm: mtl.Pipeline, splitk: mtl.Pipeline, gather: [3]mtl.Pipeline, gu: [2]mtl.Pipeline, ix: ?Gathers = null }; +/// One library's gathers by tile size; `Pipes.ix` holds the ones that read scales and biases through the index. +pub const Gathers = struct { gather: [3]mtl.Pipeline, gu: [2]mtl.Pipeline }; /// A fused member: its rows and width, in member order. pub const Part = struct { rows: usize, bits: u8, group: u16 }; @@ -56,24 +59,31 @@ fn key(b: Buf) Key { return .{ .id = @intFromPtr(b.b.id), .off = b.off }; } -/// qmmw_nax at `bits`/`group` with nax.h inlined for this GPU. -pub fn compile(r: *Run, bits: u8, group: u16) !Pipes { - const body = if (r.window.ssd_experts != null) try @import("fsr_prompt_source.zig").patch(r.arena, ks.flashnext_qmmw, true) else ks.flashnext_qmmw; - const text = try frags.source(r.device, r.arena, try @import("../../core/qmmw_source.zig").source(r.arena, body, bits, group)); - const lib = try r.ownResource(try mtl.Library.fromSource(r.device, text, mtl.CompileOptions.mlx())); - const p = struct { - fn of(rr: *Run, l: mtl.Library, name: [:0]const u8) !mtl.Pipeline { - return rr.ownResource(try mtl.Pipeline.init(rr.device, l, name, false)); - } - }; +fn pipeline(r: *Run, lib: mtl.Library, name: [:0]const u8) !mtl.Pipeline { + return r.ownResource(try mtl.Pipeline.init(r.device, lib, name, false)); +} + +fn gathers(r: *Run, lib: mtl.Library) !Gathers { return .{ - .qmm = try p.of(r, lib, "tf_qmmw_t_nax"), - .splitk = try p.of(r, lib, "tf_qmmw_splitk_nax"), - .gather = .{ try p.of(r, lib, "tf_gather_qmmw_nax_32"), try p.of(r, lib, "tf_gather_qmmw_nax_64"), try p.of(r, lib, "tf_gather_qmmw_nax_128") }, - .gu = .{ try p.of(r, lib, "tf_gather_guw_nax_32"), try p.of(r, lib, "tf_gather_guw_nax_64") }, + .gather = .{ try pipeline(r, lib, "tf_gather_qmmw_nax_32"), try pipeline(r, lib, "tf_gather_qmmw_nax_64"), try pipeline(r, lib, "tf_gather_qmmw_nax_128") }, + .gu = .{ try pipeline(r, lib, "tf_gather_guw_nax_32"), try pipeline(r, lib, "tf_gather_guw_nax_64") }, }; } +fn library(r: *Run, body: []const u8, bits: u8, group: u16) !mtl.Library { + const text = try frags.source(r.device, r.arena, try @import("../../core/qmmw_source.zig").source(r.arena, body, bits, group)); + return r.ownResource(try mtl.Library.fromSource(r.device, text, mtl.CompileOptions.mlx())); +} + +/// qmmw_nax at `bits`/`group` with nax.h inlined for this GPU; with the scale index, 4/32 gathers read through it. +pub fn compile(r: *Run, bits: u8, group: u16) !Pipes { + const body = if (r.window.ssd_experts != null) try @import("fsr_prompt_source.zig").patch(r.arena, ks.flashnext_qmmw, true) else ks.flashnext_qmmw; + const lib = try library(r, body, bits, group); + const g = try gathers(r, lib); + const ix: ?Gathers = if (r.sb_index and bits == 4 and group == 32) try gathers(r, try library(r, try @import("prompt_index_source.zig").patch(r.arena, body), bits, group)) else null; + return .{ .qmm = try pipeline(r, lib, "tf_qmmw_t_nax"), .splitk = try pipeline(r, lib, "tf_qmmw_splitk_nax"), .gather = g.gather, .gu = g.gu, .ix = ix }; +} + fn need(w: *Wide, r: *Run, bits: u8, group: u16) !void { const k = @as(u32, bits) << 16 | group; if (!w.pipes.contains(k)) try w.pipes.put(r.arena, k, try compile(r, bits, group)); @@ -168,7 +178,8 @@ fn launch(p: *Prompt, pipe: mtl.Pipeline, w: [3]Buf, x: Buf, k: usize, n: usize, /// The sorted-expert gather at the weight's width: tiles of 32, 64 or 128 rows as Prompt.gather picks them. pub fn gather(p: *Prompt, pipes: Pipes, bm: usize, x: Buf, w: []const Buf, k: usize, n: usize, pairs: usize, y: Buf) void { - p.bind(pipes.gather[if (bm == 128) 2 else if (bm == 64) 1 else 0], &.{ x, w[0], w[1], w[2], p.b.off }); + const set = if (pipes.ix != null and p.r.sbix.contains(scale_index.keyOf(w[0]))) pipes.ix.?.gather else pipes.gather; + p.bind(set[if (bm == 128) 2 else if (bm == 64) 1 else 0], &.{ x, w[0], w[1], w[2], p.b.off }); const prm = [4]i32{ @intCast(pairs), @intCast(n), @intCast(k), 512 }; p.r.enc.setBytes(std.mem.asBytes(&prm), 5); p.r.enc.setBuffer(y.b, y.off, 6); @@ -178,7 +189,8 @@ pub fn gather(p: *Prompt, pipes: Pipes, bm: usize, x: Buf, w: []const Buf, k: us /// The fused gate/up gather at the weights' width. pub fn gatherGU(p: *Prompt, pipes: Pipes, bm: usize, x: Buf, wg: []const Buf, wu: []const Buf, k: usize, n: usize, pairs: usize, y: Buf) void { - p.bind(pipes.gu[if (bm == 64) 1 else 0], &.{ x, wg[0], wg[1], wg[2], wu[0], wu[1], wu[2], p.b.off }); + const set = if (pipes.ix != null and p.r.sbix.contains(scale_index.keyOf(wg[0]))) pipes.ix.?.gu else pipes.gu; + p.bind(set[if (bm == 64) 1 else 0], &.{ x, wg[0], wg[1], wg[2], wu[0], wu[1], wu[2], p.b.off }); const prm = [4]i32{ @intCast(pairs), @intCast(n), @intCast(k), 512 }; p.r.enc.setBytes(std.mem.asBytes(&prm), 8); p.r.enc.setBuffer(y.b, y.off, 9); diff --git a/zig/src/families/flashnext/replay_run.zig b/zig/src/families/flashnext/replay_run.zig index 41da35de4f6..0b7914b472f 100644 --- a/zig/src/families/flashnext/replay_run.zig +++ b/zig/src/families/flashnext/replay_run.zig @@ -73,7 +73,7 @@ pub const Run = struct { dense: bool = false, dense_target: bool = false, skip: u32 = 0, - sb_index: bool = false, // TF_FLASHNEXT_SCALE_INDEX: the 4/32 expert kernels read scales and biases through scale_index's tables + sb_index: bool = false, // the 4/32 expert kernels read scales and biases through scale_index (TF_FLASHNEXT_SCALE_INDEX=0: off) sbix: std.AutoHashMapUnmanaged(@import("scale_index.zig").Key, [2]Buf) = .empty, sb_pairs: usize = 0, // the most distinct pairs any indexed tensor has hcskip: u32 = 0, // FZ_HCSKIP: hyper-connection knock-outs by kernel (1 norms, 2 downs, 4 ups) diff --git a/zig/src/families/flashnext/scale_index.zig b/zig/src/families/flashnext/scale_index.zig index 58748b28814..988e5d32d4d 100644 --- a/zig/src/families/flashnext/scale_index.zig +++ b/zig/src/families/flashnext/scale_index.zig @@ -1,44 +1,113 @@ -//! TF_FLASHNEXT_SCALE_INDEX: an expert projection's scales and biases as device index and table buffers (scale_pairs). +//! TF_FLASHNEXT_SCALE_INDEX: the 4/32 expert projections' scales and biases as index and table buffers (scale_pairs). const std = @import("std"); const replay = @import("replay.zig"); +const variants = @import("variants.zig"); +const experts4 = @import("experts4.zig"); +const pairs = @import("scale_pairs.zig"); const Run = replay.Run; const Buf = replay.Buf; -const pairs = @import("scale_pairs.zig"); -/// A scales buffer's identity: the map from it to its index and table. +/// A projection's codes buffer: the key of its index and table. pub const Key = struct { id: @FieldType(@FieldType(Buf, "b"), "id"), off: usize }; -pub fn keyOf(b: Buf) Key { - return .{ .id = b.b.id, .off = b.off }; +pub fn keyOf(codes: Buf) Key { + return .{ .id = codes.b.id, .off = codes.off }; } -/// The index and table buffers of the scales `s` and biases `b` (whole buffers of bf16), kept under `s`'s key. -pub fn add(r: *Run, s: Buf, b: Buf) !void { - const groups = (s.b.length() - s.off) / 2; +/// The projections only expert kernels read (routed gate, up, down): their stored scales and biases are released. +pub fn routed(j: usize) bool { + return j == 0 or j == 1 or j == 4; +} + +/// An expert set (weight, scales, biases a projection) and its widths; null widths are the recorded 6/32. +pub const Set = struct { ex: *[18]Buf, xw: ?variants.Experts }; + +const Job = struct { ex: *[18]Buf, j: usize, ix: Buf, table: []u32 = &.{}, state: enum { waiting, done, too_many, failed } = .waiting }; + +const max_workers = 8; + +/// Jobs taken in turn: each projection's pairs indexed into its buffer, its table kept on the host for the caller. +fn work(jobs: []Job, next: *std.atomic.Value(usize)) void { const gpa = std.heap.page_allocator; - const table = try gpa.create([pairs.most]u32); + const table = gpa.create([pairs.most]u32) catch return; defer gpa.destroy(table); - const seen = try gpa.create([pairs.slots]u32); + const seen = gpa.create([pairs.slots]u32) catch return; defer gpa.destroy(seen); - const ix = try r.buffer(groups * 2); - const sp: [*]align(1) const u16 = @ptrCast(s.b.contents() + s.off); - const bp: [*]align(1) const u16 = @ptrCast(b.b.contents() + b.off); - const ip: [*]align(1) u16 = @ptrCast(ix.contents()); - const n = try pairs.index(sp[0..groups], bp[0..groups], ip[0..groups], table, seen); - const t = try r.buffer(n * 4); - @memcpy(t.contents()[0 .. n * 4], std.mem.sliceAsBytes(table[0..n])); - try r.sbix.put(r.arena, keyOf(s), .{ .{ .b = ix }, .{ .b = t } }); - r.sb_pairs = @max(r.sb_pairs, n); + while (true) { + const at = next.fetchAdd(1, .monotonic); + if (at >= jobs.len) return; + const job = &jobs[at]; + const s = job.ex[job.j * 3 + 1]; + const b = job.ex[job.j * 3 + 2]; + const groups = (s.b.length() - s.off) / 2; + const sp: [*]align(1) const u16 = @ptrCast(s.b.contents() + s.off); + const bp: [*]align(1) const u16 = @ptrCast(b.b.contents() + b.off); + const ip: [*]align(1) u16 = @ptrCast(job.ix.b.contents()); + const n = pairs.index(sp[0..groups], bp[0..groups], ip[0..groups], table, seen) catch { + job.state = .too_many; + continue; + }; + job.table = gpa.dupe(u32, table[0..n]) catch { + job.state = .failed; + continue; + }; + job.state = .done; + } } -/// Every projection of an expert set (weight, scales, biases a projection) indexed; a table past 16 bits turns it off. -pub fn addAll(r: *Run, ex: *const [18]Buf) !void { - for (0..6) |j| add(r, ex[j * 3 + 1], ex[j * 3 + 2]) catch |err| switch (err) { - error.TooManyPairs => { - std.log.warn("TF_FLASHNEXT_SCALE_INDEX: a tensor has more than {d} scale and bias pairs; the index is off", .{pairs.most}); - r.sb_index = false; - return; - }, - else => return err, +/// Every 4/32 gate/up and down group of `sets` indexed, routed arrays released and their slots given index and table. +pub fn build(r: *Run, sets: []const Set) !void { + const gpa = std.heap.page_allocator; + var jobs: std.ArrayList(Job) = .empty; + defer jobs.deinit(gpa); + defer for (jobs.items) |job| if (job.table.len != 0) gpa.free(job.table); + for (sets) |set| { + const w = set.xw orelse continue; + var c: [4]variants.Const = undefined; + for ([_][2]usize{ .{ 0, 4 }, .{ 4, 6 } }, [_][4]usize{ w.gu, w.down }) |span, width| { + if (!experts4.q4(variants.four(&c, width))) continue; + for (span[0]..span[1]) |j| { + const s = set.ex[j * 3 + 1]; + try jobs.append(gpa, .{ .ex = set.ex, .j = j, .ix = .{ .b = try r.buffer(s.b.length() - s.off) } }); + } + } + } + if (jobs.items.len == 0) { + r.sb_index = false; + return; + } + var next: std.atomic.Value(usize) = .init(0); + var threads: [max_workers]?std.Thread = @splat(null); + const workers = @min(max_workers, std.Thread.getCpuCount() catch 1, jobs.items.len); + for (threads[1..workers]) |*t| t.* = std.Thread.spawn(.{}, work, .{ jobs.items, &next }) catch null; + work(jobs.items, &next); + for (threads) |t| if (t) |thread| thread.join(); + for (jobs.items) |job| if (job.state != .done) { + for (jobs.items) |made| r.release(made.ix.b); + r.sb_index = false; + if (job.state != .too_many) return error.OutOfMemory; + std.log.warn("TF_FLASHNEXT_SCALE_INDEX: a tensor has more than {d} scale and bias pairs; the index is off", .{pairs.most}); + return; }; + for (jobs.items) |job| { + const table = try r.buffer(job.table.len * 4); + @memcpy(table.contents()[0 .. job.table.len * 4], std.mem.sliceAsBytes(job.table)); + try r.sbix.put(r.arena, keyOf(job.ex[job.j * 3]), .{ job.ix, .{ .b = table } }); + r.sb_pairs = @max(r.sb_pairs, job.table.len); + if (!routed(job.j)) continue; + r.release(job.ex[job.j * 3 + 1].b); + r.release(job.ex[job.j * 3 + 2].b); + job.ex[job.j * 3 + 1] = job.ix; + job.ex[job.j * 3 + 2] = .{ .b = table }; + } +} + +/// `e` as the indexed kernels take it: the shared projections' index and table in their scales' and biases' slots. +pub fn bind(r: *const Run, e: *[18]Buf, gate_up: bool, down: bool) !void { + for (0..6) |j| { + if (routed(j) or !(if (j < 4) gate_up else down)) continue; + const p = r.sbix.get(keyOf(e[j * 3])) orelse return error.NoScaleIndex; + e[j * 3 + 1] = p[0]; + e[j * 3 + 2] = p[1]; + } } diff --git a/zig/src/families/flashnext/variants.zig b/zig/src/families/flashnext/variants.zig index 6b494951315..d01c4a67482 100644 --- a/zig/src/families/flashnext/variants.zig +++ b/zig/src/families/flashnext/variants.zig @@ -93,12 +93,7 @@ pub fn experts(r: *Run, gu_role: []const u8, down_role: []const u8, x: Buf, lg: var e = e_direct; var cg: [4]Const = undefined; var cd: [4]Const = undefined; - if (r.sb_index) for (0..6) |j| { // a 4/32 kernel's projections: index and table in the scales' and biases' slots - if (!experts4.q4(if (j < 4) four(&cg, w.gu) else four(&cd, w.down))) continue; - const p = r.sbix.get(@import("scale_index.zig").keyOf(e[j * 3 + 1])) orelse return error.NoScaleIndex; - e[j * 3 + 1] = p[0]; - e[j * 3 + 2] = p[1]; - }; + if (r.sb_index) try @import("scale_index.zig").bind(r, &e, experts4.q4(four(&cg, w.gu)), experts4.q4(four(&cd, w.down))); if (r.fsr) |stream| if (stream.pool != null) stream.bind(r, 18, 19, 0); r.enc.setBuffer(rows_buf.b, rows_buf.off, 17); // the 4/32 gate/up's row count (experts4.gated) try callAs(r, gu_role, r.rows, &.{ x, lg, e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11] }, &.{ act, pick, wts }, four(&cg, w.gu)); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 70947aa0674..952a13ef47f 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -64,7 +64,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, - .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's 4-bit expert kernels read scales and biases through a 16-bit index)" }, + .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0: Flash Next's 4-bit expert kernels read the stored scales and biases, not their 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 stops slot 0 resuming a later prompt; unset or blank keeps it on)" }, diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index bd718c70aad..f04095143b0 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -49,6 +49,7 @@ pub const flashnext_fsr_fixture = @import("families/flashnext/fsr_gpu_fixture.zi pub const flashnext_fsr_contract = @import("families/flashnext/fsr_contract_source.zig"); pub const flashnext_scale_index_fixture = @import("families/flashnext/scale_index_fixture.zig"); pub const flashnext_grouped_fixture = @import("families/flashnext/grouped_fixture.zig"); +pub const flashnext_prompt_index_fixture = @import("families/flashnext/prompt_index_fixture.zig"); pub const flashnext_replay = @import("families/flashnext/replay.zig"); pub const flashnext_rows = @import("families/flashnext/rows_load.zig"); pub const flashnext_sample = @import("families/flashnext/host_sample.zig"); diff --git a/zig/tests/contract/metal_flashnext_grouped.zig b/zig/tests/contract/metal_flashnext_grouped.zig index 0bf34fb48d6..54b32d6e4ff 100644 --- a/zig/tests/contract/metal_flashnext_grouped.zig +++ b/zig/tests/contract/metal_flashnext_grouped.zig @@ -13,6 +13,7 @@ pub const Probe = struct { device: mtl.Device, queue: mtl.Queue, control: bool = false, + indexed: bool = false, fixture: ?*Fixture = null, actual: []const u8 = &.{}, baseline: []const u8 = &.{}, @@ -22,7 +23,8 @@ pub const Probe = struct { if (p.fixture) |fixture| fixture.deinit(p.a); p.inputs_.deinit(p.a); } - pub fn name(control: bool) []const u8 { + pub fn name(control: bool, indexed: bool) []const u8 { + if (indexed) return if (control) "control: Flash Next grouped experts through the scale index, gate and up tables swapped" else "Flash Next q4 experts grouped by expert through the scale index"; return if (control) "control: Flash Next grouped experts, gate and up scales swapped" else "Flash Next q4 experts grouped by expert"; } fn depth(_: c.Shape) usize { @@ -30,7 +32,7 @@ pub const Probe = struct { } pub fn kernel(p: *Probe) g.Kernel { return .{ .ctx = p, .control = if (p.control) .shapes else null, .spec = .{ - .name = name(p.control), + .name = name(p.control, p.indexed), .accum = .none, .depth = depth, .out = .raw, @@ -59,9 +61,9 @@ pub const Probe = struct { const p = of(ctx); const fixture = p.fixture.?; fixture.wrong_scales = false; - p.baseline = try fixture.run(false); + p.baseline = try fixture.run(false, false); fixture.wrong_scales = p.control; - p.actual = try fixture.run(true); + p.actual = try fixture.run(true, p.indexed); } fn output(ctx: *anyopaque) ![]const u8 { return of(ctx).actual; diff --git a/zig/tests/contract/metal_flashnext_prompt_index.zig b/zig/tests/contract/metal_flashnext_prompt_index.zig new file mode 100644 index 00000000000..e6e11820eef --- /dev/null +++ b/zig/tests/contract/metal_flashnext_prompt_index.zig @@ -0,0 +1,97 @@ +//! Bit-preserving read contract: the indexed 4/32 prompt gathers against the same gathers reading scales direct. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const fx = tf.flashnext_prompt_index_fixture; +const Fixture = fx.Fixture; + +pub const Probe = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + control: bool = false, + fixture: ?*Fixture = null, + actual: []const u8 = &.{}, + baseline: []const u8 = &.{}, + inputs_: std.ArrayList(u8) = .empty, + + pub fn deinit(p: *Probe) void { + if (p.fixture) |fixture| fixture.deinit(p.a); + p.inputs_.deinit(p.a); + } + pub fn name(control: bool) []const u8 { + return if (control) "control: Flash Next q4 prompt gather index, two table pairs swapped" else "Flash Next q4 prompt gathers through the scale index"; + } + fn depth(_: c.Shape) usize { + return 0; + } + pub fn kernel(p: *Probe) g.Kernel { + return .{ .ctx = p, .control = if (p.control) .shapes else null, .spec = .{ + .name = name(p.control), + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = "the 4/32 prompt gathers (32, 64 and 128-row tiles, fused gate/up) reading each group's scale and bias direct, on the same stored bytes and rows", + .nan = .{ .stated = "every output bit of the direct kernels, non-finite scales included, is retained" }, + .served = &.{ .{ .rows = 40, .n = fx.inner, .k = fx.d }, .{ .rows = 97, .n = fx.inner, .k = fx.d }, .{ .rows = 200, .n = fx.inner, .k = fx.d } }, + .sums = .{ .why = "the index changes where two operands are read, not a sum; the direct kernels' sums are not requalified here" }, + }, .vt = &vt }; + } + fn of(ctx: *anyopaque) *Probe { + return @ptrCast(@alignCast(ctx)); + } + fn prepare(ctx: *anyopaque, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const p = of(ctx); + if (shape.rows < fx.experts or shape.rows > 512 or shape.n != fx.inner or shape.k != fx.d) return false; + if (p.fixture) |fixture| { + fixture.deinit(p.a); + p.fixture = null; + } + p.fixture = try Fixture.init(p.a, p.device, p.queue, shape.rows, seed, fill == .nonfinite); + p.actual = &.{}; + p.baseline = &.{}; + return true; + } + fn run(ctx: *anyopaque) !void { + const p = of(ctx); + const fixture = p.fixture.?; + fixture.wrong_entry = false; + p.baseline = try fixture.run(false); + fixture.wrong_entry = p.control; + p.actual = try fixture.run(true); + } + fn output(ctx: *anyopaque) ![]const u8 { + return of(ctx).actual; + } + fn inputs(ctx: *anyopaque) ![]const u8 { + const p = of(ctx); + p.inputs_.clearRetainingCapacity(); + try p.fixture.?.inputs(p.a, &p.inputs_); + return p.inputs_.items; + } + fn intact(ctx: *anyopaque) !bool { + return of(ctx).fixture.?.intact(); + } + fn overlap(_: *anyopaque) bool { + return false; + } + fn count(ctx: *anyopaque) usize { + return of(ctx).actual.len; + } + fn reference(_: *anyopaque, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + fn check(ctx: *anyopaque, _: g.Gate) !?[]const u8 { + const p = of(ctx); + if (!std.mem.eql(u8, p.actual, p.baseline)) return "the indexed read changed the direct gathers' output bits"; + return null; + } + fn replaced(ctx: *anyopaque) ![]const u8 { + return of(ctx).baseline; + } + const vt: g.VTable = .{ .prepare = prepare, .run = run, .output = output, .inputs = inputs, .intact = intact, .overlap = overlap, .count = count, .reference = reference, .check = check, .replaced = replaced }; +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 6a40334f9ad..dd38d01f48d 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -141,7 +141,15 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp } if (std.mem.startsWith(u8, d.name, "flashnext grouped ")) { if (!assemble) return undefined; - return .{ .decl = d, .function = fun, .here = sources.flashnext_gx, .pre_m5 = sources.flashnext_gx }; + const body = try tf.flashnext_grouped_fixture.groupedText(a, std.mem.startsWith(u8, d.name, "flashnext grouped index ")); + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; + } + if (std.mem.startsWith(u8, d.name, "flashnext prompt index ")) { + if (!assemble) return undefined; + const body = try tf.flashnext_prompt_index_fixture.text(a, true); + const pre = try preM5(a, "", body); + const here = if (device.tensorUnits()) try std.mem.replaceOwned(u8, a, body, "#include \"../nax.h\"", sources.nax) else pre; + return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; } if (std.mem.startsWith(u8, d.name, "flashnext FSR ")) { if (!assemble) return undefined; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index bfa25dc9318..6f856da5a3d 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -470,14 +470,24 @@ pub fn main(init: std.process.Init) !u8 { defer attention_pv.deinit(); try attention_pv.collect(a, device, queue, &kernels, o.only); const flash_grouped = @import("metal_flashnext_grouped.zig"); - var grouped_probes: [2]flash_grouped.Probe = undefined; + var grouped_probes: [4]flash_grouped.Probe = undefined; var grouped_made: usize = 0; defer for (grouped_probes[0..grouped_made]) |*probe| probe.deinit(); - for ([_]bool{ false, true }) |control| { - if (!wanted(o, flash_grouped.Probe.name(control))) continue; - grouped_probes[grouped_made] = .{ .a = a, .device = device, .queue = queue, .control = control }; + for ([_]bool{ false, true }) |indexed| for ([_]bool{ false, true }) |control| { + if (!wanted(o, flash_grouped.Probe.name(control, indexed))) continue; + grouped_probes[grouped_made] = .{ .a = a, .device = device, .queue = queue, .control = control, .indexed = indexed }; grouped_made += 1; try kernels.append(a, grouped_probes[grouped_made - 1].kernel()); + }; + const flash_prompt_index = @import("metal_flashnext_prompt_index.zig"); + var prompt_index_probes: [2]flash_prompt_index.Probe = undefined; + var prompt_index_made: usize = 0; + defer for (prompt_index_probes[0..prompt_index_made]) |*probe| probe.deinit(); + for ([_]bool{ false, true }) |control| { + if (!wanted(o, flash_prompt_index.Probe.name(control))) continue; + prompt_index_probes[prompt_index_made] = .{ .a = a, .device = device, .queue = queue, .control = control }; + prompt_index_made += 1; + try kernels.append(a, prompt_index_probes[prompt_index_made - 1].kernel()); } const weight_only = @import("metal_weight_only.zig"); const weight_source = try weight_only.text(a); From 751e50b73c2e3016587d3cb8768232d7f34e2474 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:40:06 +0000 Subject: [PATCH 2/2] changelog and ledger: Flash Next's scale index by default (#2805) --- CHANGELOG.md | 19 +++++++++++++++++++ docs/optimization-ledger.md | 9 ++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aae7458ef6f..fcfdc3fde12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: a grammar over 512 KiB is refused with HTTP 400 before it is compiled, so one oversized schema can no longer hold the grammar compiler for a minute (#3038). +- Flash Next on Metal (M1 through M4): the scale index is now the default for 4-bit experts in groups of 32, and `TF_FLASHNEXT_SCALE_INDEX=0` turns it off. Prompt passes and grouped decode windows read each group's scale and bias through the index too, and the routed experts' stored scales and biases are released once indexed; every kernel gets the same values, so replies keep their tokens. On an M3 Ultra with the MLX 4-bit checkpoint, memory in use once loaded falls from 129.6 to 122.5 GiB, drafted decode on one stream is 2.0% to 4.2% faster (prose 138.6 to 142.0 tok/s, a copy-heavy edit 282.0 to 293.8), four streams are 2.6% faster (203.1 to 208.3 tok/s) and a cold prompt's first token arrives about 1% sooner; load takes about 0.7 s longer (#2805, part of #2751). + +- HIP on gfx1151: the routed prompt tile runs an expert of at most 8 rows in K-parallel passes inside the same launch, with the matrix path's bytes; with Qwen3.6-35B-A3B on a Radeon 8060S, served cold prompts of 64 to 256 tokens are 11% to 22% faster (1.5% at 1,024), and logits and served tokens equal main's. Other cards' tables leave it off (#2878, fixes #2795). Thanks to @AbrahamCete. + +- Qwen3.8-27B on XPU: the target's and the DFlash2 drafter's RoPE tables come from core's exact helper, so they hold the reference's fp32 words; 15 of 32 and 18 of 64 values move by 1 ulp (#2000, part of #1852). + +- Tests: `zig build test-lane-explore-host` explores the lane host's schedules from a seed (arrivals, cancels at every stage, the backend's room for live lanes and memory pressure) around a fake target, so ordering bugs show up without hand-picked orders (#3233). + +- Qwen3.5 on CUDA: `qwen3_5` and `qwen3_5_moe` declare warm turns, so the server prefills a follow-up's prompt in the background and the next turn resumes past the previous reply, with replies unchanged (#2824). Thanks to @devopsfortunato. + +- Server: tool-call markup quoted in Markdown inline code spans and fenced code blocks stays prose, in whole replies and in streaming, instead of opening, hiding or running as a live tool call (#3588). Thanks to @gilby. + +- Lanes: shared draft pricing prices a chain-cut, unmeasured tail by the rule's rates instead of as a measured zero, and the cache's cut marker survives allocation errors (#2979). Thanks to @devopsfortunato. + +- Docs: the Nemotron 3.5 Lightning recipe gains a "Native HIP on a Strix Halo iGPU" section with its configuration, memory footprint, throughput, prefill and exactness checks, and the intro lists HIP beside Metal and CUDA (#3560). Thanks to @gilby. + +- Qwen3.5-2B on Metal: the engine declares `warm_turns` from its prompt cache, so a follow-up that re-renders earlier rows resumes the reply instead of prefilling the whole conversation again (#3457). Thanks to @EugeneClaw. + - Kolibri-1: the tree-attention cache offsets are signed, so a server with default flags no longer panics with an integer overflow on its first request when a cache sits below the origin (#3561). Thanks to @jschmied. - H3 on Metal: `Model.load` reads every transformer shard ahead of its mappings and fails the load on a missing or short shard; `TF_LOAD_PREFETCH` sets the reader count and `0` turns read-ahead off (#2999). Thanks to @plotarmordev. diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index c15a893a1ab..967a44cc099 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -76,7 +76,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 25. TP ranks | done H[#655] | done C[#1771] H[#817] | done [#855] | yes | done¹ | | 26. Pipeline | open [#2115] | yes | yes | yes | yes | | 27. Profiles | done [#1944] | done [#1944] | done [#1959] | done [#1944] | done [#2061] | -| 28. Scale index | ? | open M[#2760] | ? | ? | ? | +| 28. Scale index | ? | done M[#2760], open M[#2805] | ? | ? | ? | | 29. DSpine | done C[#2633] | no (no drafter) | no (no drafter) | no (no drafter) | no (no drafter) | | Optimization | kol1 | spk25 | dory | mm3 | dsv41 | @@ -469,8 +469,10 @@ below; these are estimates for planning a port, not results. 28. **Scale index.** An affine checkpoint stores a bf16 scale and bias beside every group's codes, a fifth of the bytes at 4 bits in groups of 32, and a tensor holds few distinct pairs. A 16-bit index a group into the tensor's table of pairs gives a kernel the same two values from fewer bytes. Flash Next's 4-bit expert kernels read it on - Macs before tensor units behind `TF_FLASHNEXT_SCALE_INDEX` ([#2760], plan in [#2751]); the prompt gathers and the - dense rows still read the stored arrays. `?` cells: the same count has not been run on those checkpoints. + Macs before tensor units ([#2760], plan in [#2751]); its prompt gathers and grouped expert kernels read it too, + the routed experts' stored arrays are released and it is the default, `TF_FLASHNEXT_SCALE_INDEX=0` turning it + off ([#2805]). The dense rows still read the stored arrays. `?` cells: the same count has not been run on those + checkpoints. 29. **DSpine drafter.** Tencent's DSpine-b16 for Qwen3.8-27B, opt-in by `--drafter` with its folder, never the default. It reuses DFlash2's taps and tap ring and adds a code bridge and an exact-sender table. @@ -628,3 +630,4 @@ below; these are estimates for planning a port, not results. [#2784]: https://github.com/ashhart/TensorFold/pull/2784 [#2764]: https://github.com/ashhart/TensorFold/issues/2764 [#2977]: https://github.com/ashhart/TensorFold/pull/2977 +[#2805]: https://github.com/ashhart/TensorFold/pull/2805