diff --git a/docs/environment-names.md b/docs/environment-names.md index f3bf61ae905..48285f26556 100644 --- a/docs/environment-names.md +++ b/docs/environment-names.md @@ -113,6 +113,7 @@ reports the setting's own value, does not count as logging. | `FZ_ROUND_TIMES` | release, tool, test | logs | | `FZ_SETTLE_SYNC` | release, tool, test | other | | `FZ_SKIP` | release, tool, test | other | +| `FZ_TFQ3_SERIAL_ROUTE` | release, tool, test | other | | `FZ_TREE` | release, tool, test | other | | `FZ_VERIFY_OVERLAP` | release, tool, test | other | | `GEMMA_DRAFT_BF16` | release, tool, test | other | diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index e7dae7049e8..473aeb8eb0d 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -89,6 +89,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 38. Greedy readback | ? | ? | ? | ? | ? | | 39. Drafted rows share the walk | open H[#4673] | ? | ? | ? | ? | | 40. Mapped host embeddings | yes | ? | ? | ? | ? | +| 42. Parallel routing | ? | open M[#5471] | ? | ? | ? | | Optimization | kol1 | spk25 | dory | mm3 | dsv41 | | --- | --- | --- | --- | --- | --- | @@ -132,6 +133,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 38. Greedy readback | ? | ? | ? | ? | ? | | 39. Drafted rows share the walk | ? | ? | ? | ? | ? | | 40. Mapped host embeddings | ? | ? | ? | ? | ? | +| 42. Parallel routing | ? | ? | ? | ? | ? | | Optimization | lfm2m | lfm3 | qwen4 | ling | | --- | --- | --- | --- | --- | @@ -176,6 +178,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 39. Drafted rows share the walk | ? | ? | ? | ? | | 40. CPU KDA heads | n/a | n/a | n/a | done CPU, exact independent heads (Refs #1247) | | 41. Mapped host embeddings | ? | ? | ? | ? | +| 42. Parallel routing | ? | ? | ? | ? | q3.5 `qwen3_5` (C, M, H, X), fnext `flashnext` (C, M, H), glm `glm` (C, M), gem4 `gemma4` (C, M, X), nemo `nemotron` (C, M, H, X), kol1 `kolibri1` (C), spk25 `spark25` (C, M), @@ -225,6 +228,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 38. Greedy readback | ? | ? | ? | ? | | 39. Drafted rows share the walk | ? | ? | ? | ? | | 40. Mapped host embeddings | ? | ? | ? | ? | +| 42. Parallel routing | ? | ? | ? | ? | | Optimization | gdsa | kimi | qwen3 | snloop | | --- | --- | --- | --- | --- | @@ -268,6 +272,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 38. Greedy readback | ? | ? | ? | ? | | 39. Drafted rows share the walk | ? | ? | ? | ? | | 40. Mapped host embeddings | ? | ? | ? | ? | +| 42. Parallel routing | ? | ? | ? | ? | q27 `qwen27` (M: Qwen3.8-27B and Qwen3.5-MoE), lfm2 `lfm2` (C: LFM2-VL, scores decisions and writes no text), llama `llama` (M), step5 `step5` (M), gdsa `glm_dsa` (M), kimi `kimi_k3` (M, native serving on [#2221]), @@ -324,6 +329,7 @@ below; these are estimates for planning a port, not results. | 37. Text metadata uploads | none | none | none | CUDA qwen3_5: −0.037 % median paired gain (separate absolute medians 15.2475 → 15.2418 tok/s) | | 38. Greedy readback | none | none | none | CUDA dots.mocr: +1.200 % median paired gain (separate absolute medians 64.6319 → 65.4191 tok/s) | | 39. Drafted rows share the walk | none | medium | none | HIP qwen3_5: decode at one stream with drafts at 131K-258K, score half +1.0–5.1 %, values' half +0.4–6.9 % more | +| 42. Parallel routing | none | low | none | Metal Flash Next TFQ3 (every Apple GPU runs it; measured on an M3 Ultra, published TFQ3 checkpoint): drafted decode +8.0 % against main, one row level, tokens equal | ## The optimizations @@ -684,6 +690,16 @@ below; these are estimates for planning a port, not results. | qwen3_5 (35B-A3B) | score half +0.96 % to +3.27 % decode at one stream with drafts at 131,072 and 258,048 kept tokens; the values' half +3.86 % to +6.94 % on top of it; `"draft": false` and four streams without drafts level; tokens equal | [#4673] and [#3811], gfx1151 | | qwen3_5 (27B) | score half +2.59 % to +5.11 %; the values' half +0.43 % to +4.91 % on top of it; the same checks | [#4673] and [#3811], gfx1151 | +42. **Parallel routing.** Flash Next TFQ3 on Metal (M1-M5: the decode dispatch has no tensor-unit branch) routed a + decode window of 2 to 16 rows in one 32-thread group, one row after another, and one lane then built the + deduplicated expert lists alone. Each row now routes in the rotation kernel's spare group, in parallel, and one + thread a slot builds the same lists (`fn_pw_dedup_par`). Picks, weights and lists are the same bytes, so tokens do + not change; one-row decode keeps its path ([#5471]). + + | Family | Gain (measured) | Where | + | --- | --- | --- | + | fnext (TFQ3) | against main 2d15aae, published TFQ3 checkpoint: drafted decode -1.88 ms a round (-6.8 %), +8.0 % tok/s, A-B-B-A, faster in both pairs; one row (`--no-drafts`) level; tokens equal | [#5471], M3 Ultra | + [#458]: https://github.com/ashhart/TensorFold/pull/458 [#468]: https://github.com/ashhart/TensorFold/pull/468 [#519]: https://github.com/ashhart/TensorFold/pull/519 @@ -851,3 +867,4 @@ below; these are estimates for planning a port, not results. [#3811]: https://github.com/ashhart/TensorFold/issues/3811 [#4673]: https://github.com/ashhart/TensorFold/pull/4673 [#4932]: https://github.com/ashhart/TensorFold/pull/4932 +[#5471]: https://github.com/ashhart/TensorFold/issues/5471 diff --git a/zig/build/flashnext_checks.zig b/zig/build/flashnext_checks.zig index 1f628e9ea84..07e9adcdd31 100644 --- a/zig/build/flashnext_checks.zig +++ b/zig/build/flashnext_checks.zig @@ -21,5 +21,14 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } }, }) }); - b.step("test-flashnext-tfq3", "Flash Next TFQ3 format, Metal kernels, B=1==B=4 parity, and prefill accuracy").dependOn(&b.addRunArtifact(tfq3_test).step); + const route_test = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/flashnext_tfq3_route_test.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } }, + }) }); + const step = b.step("test-flashnext-tfq3", "Flash Next TFQ3 format, Metal kernels, B=1==B=4 parity, routing, and prefill accuracy"); + step.dependOn(&b.addRunArtifact(tfq3_test).step); + step.dependOn(&b.addRunArtifact(route_test).step); } diff --git a/zig/kernels/metal/flashnext_tfq3/common.metal b/zig/kernels/metal/flashnext_tfq3/common.metal index 149fa8b1e30..0b01fe61615 100644 --- a/zig/kernels/metal/flashnext_tfq3/common.metal +++ b/zig/kernels/metal/flashnext_tfq3/common.metal @@ -149,6 +149,46 @@ inline void fn_route_row( } } +// fn_pw_route_dedup's lists bit for bit, a thread a slot: first-seen experts in slot order, members in slot order +[[max_total_threads_per_threadgroup(160)]] +[[kernel]] void fn_pw_dedup_par( + const device uint* pick [[buffer(0)]], + const constant int* rows_buf [[buffer(1)]], + device int* uids [[buffer(2)]], + device int* umem [[buffer(3)]], + device int* ucount [[buffer(4)]], + constant FnPwDims& d [[buffer(5)]], + ushort s [[thread_index_in_threadgroup]] +) { + threadgroup uint pk[160]; + threadgroup uchar opens[160]; + const int R = metal::min(int(d.rows), rows_buf[0]); + const int S = metal::min(metal::max(R, 0) * 10, 160); + const int i = int(s); + if (i < S) pk[i] = pick[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + bool open = false; + if (i < S) { + open = true; + for (int t = 0; t < i; ++t) if (pk[t] == pk[i]) { open = false; break; } + opens[i] = open ? uchar(1) : uchar(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (open) { + int u = 0; + for (int t = 0; t < i; ++t) u += int(opens[t]); + uids[u] = int(pk[i]); + int m = 0; + for (int t = i; t < S && m < 16; ++t) if (pk[t] == pk[i]) umem[u * 16 + m++] = t; + for (; m < 16; ++m) umem[u * 16 + m] = -1; + } + if (i == 0) { + int nu = 0; + for (int t = 0; t < S; ++t) nu += int(opens[t]); + ucount[0] = nu; + } +} + [[kernel]] void fn_pw_fwht_x_fwd( const device bfloat* X [[buffer(0)]], device half* X_rot [[buffer(1)]], @@ -162,7 +202,9 @@ inline void fn_route_row( ) { int R = metal::min(int(d.rows), rows_buf[0]); if (gid.x == 20u) { - if (gid.y == 0u && R > 0 && (d.flags & 2u) != 0u) fn_route_row(logits, pick, wts, lane); + // flags 2: row 0 alone (B=1); flags 4: every live row, in parallel, ahead of fn_pw_dedup_par (B=2..16) + const bool route = int(gid.y) < R && (((d.flags & 2u) != 0u && gid.y == 0u) || (d.flags & 4u) != 0u); + if (route) fn_route_row(logits + ulong(gid.y) * 513ul, pick + ulong(gid.y) * 10ul, wts + ulong(gid.y) * 10ul, lane); return; } uint row = gid.y; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 9213e46e311..322ae62dbd1 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -81,6 +81,7 @@ pub const cuda_pending = @import("mhc_cuda_records.zig").cuda ++ @import("qwen_w @import("registry_media.zig").cuda_pending ++ @import("h3_image_cuda_records.zig").records; pub const metal_before = @import("fsr_records.zig").metal ++ + @import("tfq3_records.zig").metal ++ @import("scale_index_records.zig").metal ++ @import("lfm3_records.zig").metal; pub const all_metal = @import("penalties_records.zig").records ++ diff --git a/zig/src/core/contract/tfq3_records.zig b/zig/src/core/contract/tfq3_records.zig index 89a6ec20f90..39882dd00b1 100644 --- a/zig/src/core/contract/tfq3_records.zig +++ b/zig/src/core/contract/tfq3_records.zig @@ -1,6 +1,11 @@ -//! TFQ3 launch geometry and nvcc 13.0's usage on sm_80/86/89/120/121, measured on a GB10; later compilers stay pending. +//! TFQ3 launch geometry: nvcc 13.0's usage on sm_80/86/89/120/121 (GB10; later compilers pending) and Metal's. const std = @import("std"); const reg = @import("registry.zig"); +const M = @import("limits.zig").MetalLaunch; +/// Flash Next's parallel dedup: 160 threads reserved in its source; M1 and M2 compile it for 160. +pub const metal = [_]M{ + .{ .name = "flashnext tfq3 fn_pw_dedup_par", .threads = 160, .tg_memory = 160 * 4 + 160, .reserved = 160, .m1 = 160, .m2 = 160 }, +}; const U = @FieldType(reg.CudaRecord, "usage"); const measured = [_]struct { []const u8, U }{ .{ "tf_tfq3_fwht_x", .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, diff --git a/zig/src/families/flashnext/tfq3.zig b/zig/src/families/flashnext/tfq3.zig index 6cb432661c8..e9a7a7d3e02 100644 --- a/zig/src/families/flashnext/tfq3.zig +++ b/zig/src/families/flashnext/tfq3.zig @@ -178,6 +178,7 @@ pub fn loadMtp( pub const Pipe = enum(usize) { route_dedup, + dedup_par, fwht_x_fwd, fwht_glu_fwht, fwht_y_inv, @@ -226,6 +227,7 @@ pub const Pipes = struct { ucount_buf: mtl.Buffer, owns_bufs: bool, hash: u64, + serial_route: bool = false, // FZ_TFQ3_SERIAL_ROUTE: B=2..16 windows through route_dedup, not fwht_x + dedup_par pub inline fn get(p: *const Pipes, k: Pipe) mtl.Pipeline { return p.list[@backingInt(k)]; @@ -283,6 +285,7 @@ pub const Pipes = struct { .ucount_buf = b_ucount, .owns_bufs = held == null, .hash = h.final(), + .serial_route = platform.c.getenv("FZ_TFQ3_SERIAL_ROUTE") != null, }; } diff --git a/zig/src/families/flashnext/tfq3_dispatch.zig b/zig/src/families/flashnext/tfq3_dispatch.zig index 9375008e777..76da49c6505 100644 --- a/zig/src/families/flashnext/tfq3_dispatch.zig +++ b/zig/src/families/flashnext/tfq3_dispatch.zig @@ -48,7 +48,7 @@ pub fn moeDecode( .sh_gu_group = sh[1], .sh_dn_bits = sh[2], .sh_dn_group = sh[3], - .flags = if (rows == 1) 2 else 0, + .flags = if (rows == 1) 2 else if (p.serial_route) 0 else 4, // 4: fwht_x_fwd routes every live row }; e.setPipeline(p.get(.fwht_x_fwd)); @@ -59,7 +59,7 @@ pub fn moeDecode( e.setBuffer(lg.b, lg.off, 4); e.setBuffer(pick.b, pick.off, 5); e.setBuffer(wts.b, wts.off, 6); - e.dispatchGroups(mtl.Size.of(if (rows == 1) 21 else 20, rows, 1), mtl.Size.of(32, 1, 1)); + e.dispatchGroups(mtl.Size.of(if (rows == 1 or !p.serial_route) 21 else 20, rows, 1), mtl.Size.of(32, 1, 1)); barrier(r); if (rows == 1) { @@ -103,16 +103,27 @@ pub fn moeDecode( e.dispatchGroups(mtl.Size.of(80, 14, 1), mtl.Size.of(64, 1, 1)); barrier(r); } else { - e.setPipeline(p.get(.route_dedup)); - e.setBuffer(lg.b, lg.off, 0); - e.setBuffer(rows_buf.b, rows_buf.off, 1); - e.setBuffer(pick.b, pick.off, 2); - e.setBuffer(wts.b, wts.off, 3); - e.setBuffer(p.uids_buf, 0, 4); - e.setBuffer(p.umem_buf, 0, 5); - e.setBuffer(p.ucount_buf, 0, 6); - e.setValue(d, 7); - e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32, 1, 1)); + if (p.serial_route) { + e.setPipeline(p.get(.route_dedup)); + e.setBuffer(lg.b, lg.off, 0); + e.setBuffer(rows_buf.b, rows_buf.off, 1); + e.setBuffer(pick.b, pick.off, 2); + e.setBuffer(wts.b, wts.off, 3); + e.setBuffer(p.uids_buf, 0, 4); + e.setBuffer(p.umem_buf, 0, 5); + e.setBuffer(p.ucount_buf, 0, 6); + e.setValue(d, 7); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32, 1, 1)); + } else { // fwht_x_fwd's group 20 routed every live row; the lists as route_dedup writes them, in parallel + e.setPipeline(p.get(.dedup_par)); + e.setBuffer(pick.b, pick.off, 0); + e.setBuffer(rows_buf.b, rows_buf.off, 1); + e.setBuffer(p.uids_buf, 0, 2); + e.setBuffer(p.umem_buf, 0, 3); + e.setBuffer(p.ucount_buf, 0, 4); + e.setValue(d, 5); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(tfq3.max_decode_slots, 1, 1)); + } barrier(r); e.setPipeline(if (tl.has_5b) p.get(.dec_gu_dedup_543) else p.get(.dec_gu_dedup_43)); diff --git a/zig/tests/contract/metal_family_limits.zig b/zig/tests/contract/metal_family_limits.zig index 0f582ab7e2c..4f46958d6d2 100644 --- a/zig/tests/contract/metal_family_limits.zig +++ b/zig/tests/contract/metal_family_limits.zig @@ -64,6 +64,11 @@ pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, const body = try tf.lfm2_moe.source.prompt(device, a, true); return .{ .decl = d, .function = fun, .here = body, .pre_m5 = "" }; } + if (std.mem.startsWith(u8, d.name, "flashnext tfq3 ")) { + if (!assemble) return @as(Launch, undefined); + const tfq3 = tf.flashnext_replay.tfq3; + return .{ .decl = d, .function = fun, .here = try tfq3.buildSource(a, device.tensorUnits()), .pre_m5 = try tfq3.buildSource(a, false) }; + } if (std.mem.startsWith(u8, d.name, "tree round picks ")) { if (!assemble) return @as(Launch, undefined); return .{ .decl = d, .function = fun, .here = sources.core_tree_round, .pre_m5 = sources.core_tree_round }; diff --git a/zig/tests/contract/metal_flashnext_tfq3_dedup.zig b/zig/tests/contract/metal_flashnext_tfq3_dedup.zig new file mode 100644 index 00000000000..402665a9f1e --- /dev/null +++ b/zig/tests/contract/metal_flashnext_tfq3_dedup.zig @@ -0,0 +1,248 @@ +//! Flash Next TFQ3 fn_pw_dedup_par against fn_pw_route_dedup's expert lists, on the picks route_dedup made. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const tfq3 = tf.flashnext_replay.tfq3; + +const topk = tfq3.topk; +const slots = tfq3.max_decode_slots; +const experts = tfq3.num_experts; +/// Router logits a row as route_dedup reads them: the experts and the shared expert's gate. +const stride = 513; +/// Both kernels' outputs start as this byte: 0xff would read as the -1 a list's tail holds. +const poison = 0xa5; + +/// The shipped kernel, or a planted control: an edit of its source that some served window must catch. +pub const Control = enum { none, expert_order, no_tail, window_rows, first_member, past_window }; + +const Edit = struct { from: []const u8, to: []const u8 }; + +fn edit(control: Control) ?Edit { + return switch (control) { + .none => null, + .expert_order => .{ .from = "t < i; ++t) u += int(opens[t]);", .to = "t < i; ++t) u += int(opens[t] != 0 && pk[t] < pk[i]);" }, + .no_tail => .{ .from = "for (; m < 16; ++m) umem[u * 16 + m] = -1;", .to = "" }, + .window_rows => .{ .from = "const int S = metal::min(metal::max(R, 0) * 10, 160);", .to = "const int S = int(d.rows) * 10;" }, + .first_member => .{ .from = "if (pk[t] == pk[i]) umem[u * 16 + m++] = t;", .to = "if (pk[t] == pk[i] && t == i) umem[u * 16 + m++] = t;" }, + .past_window => .{ .from = "const int R = metal::min(int(d.rows), rows_buf[0]);", .to = "const int R = rows_buf[0];" }, + }; +} + +pub fn name(control: Control) []const u8 { + return switch (control) { + .none => "flashnext tfq3 fn_pw_dedup_par", + .expert_order => "control: flashnext tfq3 fn_pw_dedup_par, lists in expert order", + .no_tail => "control: flashnext tfq3 fn_pw_dedup_par, no -1 tail", + .window_rows => "control: flashnext tfq3 fn_pw_dedup_par, window rows, not live rows", + .first_member => "control: flashnext tfq3 fn_pw_dedup_par, members past the first dropped", + .past_window => "control: flashnext tfq3 fn_pw_dedup_par, live rows past the window kept", + }; +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// The gate a planted control must turn red; null for the shipped kernel. +pub fn gate(control: Control) ?g.Gate { + return if (control == .none) null else .shapes; +} + +pub fn spec(control: Control) c.Spec { + return .{ + .name = name(control), + .accum = .none, + .depth = noSums, + .out = .raw, + .replaces = "fn_pw_route_dedup's uids, umem and ucount on the same picks", + .nan = .{ .stated = "it reads expert ids only; route_dedup skips NaN logits and ranks infinities, and its lists of those picks are matched byte for byte" }, + .served = &served, + .sums = .{ .why = "no sums: it compares and moves expert ids" }, + }; +} + +/// rows: the decode window (d.rows); n: picks a row; k: live rows (rows_buf): the window, one short, 1, 0 and 3 past. +const served = blk: { + var out: [74]c.Shape = undefined; + out[0] = .{ .rows = 16, .n = topk, .k = 16 }; + var i: usize = 1; + for (2..16) |b| { + out[i] = .{ .rows = b, .n = topk, .k = b }; + i += 1; + } + for (2..17) |b| { + out[i] = .{ .rows = b, .n = topk, .k = b - 1 }; + i += 1; + } + for (2..17) |b| for ([_]usize{ 1, 0 }) |live| { + if (live == b - 1) continue; + out[i] = .{ .rows = b, .n = topk, .k = live }; + i += 1; + }; + for (2..17) |b| { + out[i] = .{ .rows = b, .n = topk, .k = b + 3 }; + i += 1; + } + if (i != out.len) @compileError("served shapes miscounted"); + break :blk out; +}; + +pub const Dedup = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + control: Control, + route: mtl.Pipeline, + par: mtl.Pipeline, + dims: tfq3.Dims = undefined, + rows: rig_.Ref = undefined, + pick: rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + base: std.ArrayList(u8) = .empty, + planted: usize = 0, + msg: [200]u8 = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: Control) !Dedup { + const src = try tfq3.buildSource(a, device.tensorUnits()); + defer a.free(src); + const text = if (edit(control)) |e| blk: { + if (std.mem.count(u8, src, e.from) != 1) return error.ControlEditNotFound; + break :blk try std.mem.replaceOwned(u8, a, src, e.from, e.to); + } else src; + defer if (text.ptr != src.ptr) a.free(text); + // Every edit is inside fn_pw_dedup_par, so route_dedup from the same library is the shipped one. + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const route = try mtl.Pipeline.init(device, lib, "fn_pw_route_dedup", false); + errdefer route.deinit(); + const par = try mtl.Pipeline.init(device, lib, "fn_pw_dedup_par", false); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .control = control, .route = route, .par = par }; + } + + pub fn deinit(p: *Dedup) void { + p.rig.deinit(); + p.base.deinit(p.a); + p.route.deinit(); + p.par.deinit(); + } + + pub fn kernel(p: *Dedup) g.Kernel { + return .{ .ctx = p, .vt = &vt, .control = gate(p.control), .spec = spec(p.control) }; + } + + const vt = g.hooks(Dedup); + + /// The route suite's logits (each window meets all five patterns); route_dedup makes the picks and the lists. + pub fn prepare(p: *Dedup, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > tfq3.max_decode_rows or shape.n != topk) return false; + p.rig.reset(); + p.base.clearRetainingCapacity(); + const window = shape.rows; + const live = @min(window, shape.k); + const lg = try p.a.alloc(f32, tfq3.max_decode_rows * stride); + defer p.a.free(lg); + var prng = std.Random.DefaultPrng.init(seed); + const rand = prng.random(); + for (lg) |*v| v.* = (rand.float(f32) - 0.5) * 2.0; + for (0..window) |r| { + const row = lg[r * stride ..][0..stride]; + switch (pattern(window, shape.k)) { + 0 => {}, // independent rows: few shared experts + 1 => for (0..12) |k| { // every row's top experts one set, in a different order a row + row[(k * 37 + 5) % experts] = 9.0 - @as(f32, @floatFromInt((k + r) % 12)) * 0.25; + }, + 2 => for (0..topk) |k| { // ties broken by expert id + row[(k * 51 + r * 3) % experts] = 7.5; + }, + 3 => for (0..topk) |k| { // rows in pairs: row r shares its picks with row r ^ 1 + row[((r >> 1) * 29 + k * 7) % experts] = 8.0 + @as(f32, @floatFromInt(k)) * 0.125; + }, + else => { // three finite logits: the rest of the top 10 repeats an id + @memset(row, -std.math.inf(f32)); + for (0..3) |k| row[(k * 97 + r * 11) % experts] = 1.0 + @as(f32, @floatFromInt(k)); + }, + } + } + p.planted = 0; + if (fill == .nonfinite) { + // Each row's would-be first pick turns NaN (row 0, 2) or -Inf (row 1); rows 1 and 2 gain a +Inf. + const nan = std.math.nan(f32); + const inf = std.math.inf(f32); + const put = [_]struct { f32, ?usize }{ .{ nan, null }, .{ -inf, 40 }, .{ nan, 300 } }; + for (put, 0..) |x, r| if (r < window) { + const row = lg[r * stride ..][0..experts]; + row[std.mem.indexOfMax(f32, row)] = x[0]; + if (x[1]) |at| row[at] = inf; + if (r < live) p.planted += 1; + }; + } + p.dims = .{ .rows = @intCast(window), .slots = @intCast(window * topk), .topk = topk, .experts = experts, .flags = 4 }; + const live_i: i32 = @intCast(shape.k); + p.rows = try p.rig.input(std.mem.asBytes(&live_i)); + const logits = try p.rig.scratch(lg.len * 4); + @memcpy(p.rig.bytes(logits, lg.len * 4), std.mem.sliceAsBytes(lg)); + var made: [5]rig_.Ref = undefined; + const lens = [5]usize{ slots * 4, slots * 4, slots * 4, slots * 16 * 4, 4 }; + for (&made, lens) |*r, n| { + r.* = try p.rig.scratch(n); + @memset(p.rig.bytes(r.*, n), poison); + } + const pass = p.rig.begin(); + pass.e.setPipeline(p.route); + pass.e.setBuffer(logits.buf, logits.off, 0); + pass.e.setBuffer(p.rows.buf, p.rows.off, 1); + for (made, 0..) |r, j| pass.e.setBuffer(r.buf, r.off, 2 + j); + pass.e.setValue(p.dims, 7); + pass.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32, 1, 1)); + try p.rig.finish(pass); + for (made[2..], lens[2..]) |r, n| try p.base.appendSlice(p.a, p.rig.bytes(r, n)); + p.pick = try p.rig.input(p.rig.bytes(made[0], lens[0])); + for (&p.outs, lens[2..]) |*r, n| { + r.* = try p.rig.output(n); + @memset(p.rig.bytes(r.*, n), poison); + } + return true; + } + + /// 0 to 4 by the live count's place among a window's served counts, turned by the window. + fn pattern(window: usize, k: usize) usize { + const place: usize = if (k == window) 0 else if (k + 1 == window) 1 else if (k == 1) 2 else if (k == 0) 3 else 4; + return (place + window) % 5; + } + + pub fn run(p: *Dedup) !void { + const pass = p.rig.begin(); + pass.e.setPipeline(p.par); + pass.e.setBuffer(p.pick.buf, p.pick.off, 0); + pass.e.setBuffer(p.rows.buf, p.rows.off, 1); + for (p.outs, 0..) |r, j| pass.e.setBuffer(r.buf, r.off, 2 + j); + pass.e.setValue(p.dims, 5); + pass.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(slots, 1, 1)); + try p.rig.finish(pass); + } + + pub fn count(_: *Dedup) usize { + return slots * 4 + slots * 16 * 4 + 4; + } + + pub fn reference(_: *Dedup, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + /// The lists' bytes against route_dedup's; at the non-finite gate, planted rows must have been live. + pub fn check(p: *Dedup, at: g.Gate) !?[]const u8 { + const got = try p.rig.outputBytes(); + if (std.mem.indexOfDiff(u8, got, p.base.items)) |i| return try std.fmt.bufPrint(&p.msg, "lists differ from route_dedup's from byte {d}", .{i}); + if (at == .nonfinite and p.planted == 0) return "no row holding NaN or an infinity was live: no proof"; + return null; + } + + pub fn replaced(p: *Dedup) ![]const u8 { + return p.base.items; + } +}; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 3c064cbb02a..f21d9568c66 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -24,6 +24,7 @@ const flash_pool = @import("metal_flashnext_pool.zig"); const flash = @import("metal_flashnext.zig"); const fsr = @import("metal_fsr.zig"); const flash_index = @import("metal_flashnext_index.zig"); +const tfq3_dedup = @import("metal_flashnext_tfq3_dedup.zig"); const gemma = @import("metal_gemma4.zig"); const gemma_embed = @import("metal_gemma4_embed.zig"); const gemma_mixed = @import("metal_gemma4_mixed.zig"); @@ -225,6 +226,18 @@ pub fn main(init: std.process.Init) !u8 { index_made += 1; try kernels.append(a, index_probes[index_made - 1].kernel()); } + var dedup_probes: [std.enums.values(tfq3_dedup.Control).len]tfq3_dedup.Dedup = undefined; + var dedup_made: usize = 0; + defer for (dedup_probes[0..dedup_made]) |*probe| probe.deinit(); + for (std.enums.values(tfq3_dedup.Control)) |control| { + if (!wanted(o, tfq3_dedup.name(control))) continue; + dedup_probes[dedup_made] = tfq3_dedup.Dedup.init(a, device, queue, control) catch |err| { + try kernels.append(a, .{ .spec = tfq3_dedup.spec(control), .ctx = undefined, .vt = undefined, .control = tfq3_dedup.gate(control), .init_error = err }); + continue; + }; + dedup_made += 1; + try kernels.append(a, dedup_probes[dedup_made - 1].kernel()); + } var d3norm: ?drama3_k.Norm = null; defer if (d3norm) |*n| n.deinit(); if (wanted(o, drama3_k.spec().name)) { diff --git a/zig/tests/flashnext_tfq3_route_test.zig b/zig/tests/flashnext_tfq3_route_test.zig new file mode 100644 index 00000000000..931264d9549 --- /dev/null +++ b/zig/tests/flashnext_tfq3_route_test.zig @@ -0,0 +1,164 @@ +//! Flash Next TFQ3 B=2..16 routing: fwht_x_fwd's parallel rows and dedup_par against route_dedup, byte for byte. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const tfq3 = tf.flashnext_replay.tfq3; + +const D = tfq3.hidden_size; +const NE = tfq3.num_experts; +const TOPK = tfq3.topk; + +/// Logits, rows and both paths' outputs (pick, wts, uids, umem, ucount), each output buffer prefilled with 0xA5. +const RouteRig = struct { + lg: mtl.Buffer, + x: mtl.Buffer, + rows: mtl.Buffer, + out: [2][5]mtl.Buffer, + const sizes = [5]usize{ 16 * TOPK * 4, 16 * TOPK * 4, 160 * 4, 160 * 16 * 4, 16 }; + const opt = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + + fn init(dev: mtl.Device) !RouteRig { + var rig: RouteRig = undefined; + rig.lg = try dev.buffer(16 * 513 * 4, opt); + errdefer rig.lg.deinit(); + rig.x = try dev.buffer(16 * D * 2, opt); + errdefer rig.x.deinit(); + @memset(rig.x.contents()[0 .. 16 * D * 2], 0); + rig.rows = try dev.buffer(16, opt); + errdefer rig.rows.deinit(); + var made: usize = 0; + errdefer for (0..made) |k| rig.out[k / 5][k % 5].deinit(); + for (&rig.out) |*side| for (side, sizes) |*b, n| { + b.* = try dev.buffer(n, opt); + made += 1; + }; + return rig; + } + + fn deinit(rig: *RouteRig) void { + rig.lg.deinit(); + rig.x.deinit(); + rig.rows.deinit(); + for (rig.out) |side| for (side) |b| b.deinit(); + } + + /// Every case's outputs from route_dedup and from fx (fwht_x_fwd, flags 4) + dd (dedup_par) byte-equal, 5 runs. + fn agrees(rig: *RouteRig, queue: anytype, p: *const tfq3.Pipes, fx: mtl.Pipeline, dd: mtl.Pipeline) !bool { + var rng = std.Random.DefaultPrng.init(0x7f3a); + const rand = rng.random(); + for (2..17) |window| for ([_]usize{ window, window - 1, 1, 0, window + 3 }) |live| for (0..5) |variant| { + const lg = rig.lg.slice(f32, 16 * 513); + for (lg) |*v| v.* = (rand.float(f32) - 0.5) * 2.0; + for (0..window) |r| switch (variant) { + 0 => {}, // independent rows: few shared experts + 1 => for (0..12) |k| { // every row's top experts the same set, in a different order a row + lg[r * 513 + (k * 37 + 5) % NE] = 9.0 - @as(f32, @floatFromInt((k + r) % 12)) * 0.25; + }, + 2 => for (0..TOPK) |k| { // ties: equal logits across experts, broken by expert id + lg[r * 513 + (k * 51 + r * 3) % NE] = 7.5; + }, + 3 => for (0..TOPK) |k| { // rows in pairs: row r shares its picks with row r ^ 1 + lg[r * 513 + ((r >> 1) * 29 + k * 7) % NE] = 8.0 + @as(f32, @floatFromInt(k)) * 0.125; + }, + else => { // three finite logits: the rest of the top 10 repeats the lowest id among -inf, in one row + @memset(lg[r * 513 ..][0..513], -std.math.inf(f32)); + for (0..3) |k| lg[r * 513 + (k * 97 + r * 11) % NE] = 1.0 + @as(f32, @floatFromInt(k)); + }, + }; + rig.rows.slice(i32, 1)[0] = @intCast(live); + const d: tfq3.Dims = .{ .rows = @intCast(window), .slots = @intCast(window * TOPK), .topk = TOPK, .experts = NE, .flags = 4 }; + var first: [5][]u8 = undefined; + var have_first = false; + defer if (have_first) for (first) |f| std.testing.allocator.free(f); + for (0..5) |run| { + for (rig.out) |side| for (side, sizes) |b, n| @memset(b.contents()[0..n], 0xA5); + const cb = queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(p.get(.route_dedup)); + e.setBuffer(rig.lg, 0, 0); + e.setBuffer(rig.rows, 0, 1); + for (0..5) |j| e.setBuffer(rig.out[0][j], 0, 2 + j); + e.setValue(d, 7); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32, 1, 1)); + e.setPipeline(fx); + e.setBuffer(rig.x, 0, 0); + e.setBuffer(p.xrot_buf, 0, 1); + e.setBuffer(rig.rows, 0, 2); + e.setValue(d, 3); + e.setBuffer(rig.lg, 0, 4); + e.setBuffer(rig.out[1][0], 0, 5); + e.setBuffer(rig.out[1][1], 0, 6); + e.dispatchGroups(mtl.Size.of(21, window, 1), mtl.Size.of(32, 1, 1)); + e.setPipeline(dd); + e.setBuffer(rig.out[1][0], 0, 0); + e.setBuffer(rig.rows, 0, 1); + for (2..5) |j| e.setBuffer(rig.out[1][j], 0, j); + e.setValue(d, 5); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(tfq3.max_decode_slots, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.debug.print("route rig: {s}\n", .{msg}); + return error.GpuFailed; + } + for (0..5) |j| { + const got = rig.out[1][j].contents()[0..sizes[j]]; + if (!std.mem.eql(u8, rig.out[0][j].contents()[0..sizes[j]], got)) return false; + if (have_first and !std.mem.eql(u8, first[j], got)) return false; + } + if (run == 0) { + var made: usize = 0; + errdefer for (first[0..made]) |f| std.testing.allocator.free(f); + for (0..5) |j| { + first[j] = try std.testing.allocator.dupe(u8, rig.out[1][j].contents()[0..sizes[j]]); + made += 1; + } + have_first = true; + } + } + }; + return true; + } +}; + +test "Flash Next TFQ3: parallel routing and dedup give route_dedup's bytes at B=2..16, live rows short too; planted controls fail" { + const a = std.testing.allocator; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const dev = try mtl.Device.init(); + defer dev.deinit(); + const queue = try dev.queue(); + defer queue.deinit(); + var pipes = try tfq3.Pipes.init(a, dev, null); + defer pipes.deinit(); + var rig = try RouteRig.init(dev); + defer rig.deinit(); + try std.testing.expect(try rig.agrees(queue, &pipes, pipes.get(.fwht_x_fwd), pipes.get(.dedup_par))); + + const src = try tfq3.buildSource(a, dev.tensorUnits()); + defer a.free(src); + const Control = struct { name: []const u8, from: []const u8, to: []const u8 }; + const controls = [_]Control{ + .{ .name = "lists in expert order", .from = "t < i; ++t) u += int(opens[t]);", .to = "t < i; ++t) u += int(opens[t] != 0 && pk[t] < pk[i]);" }, + .{ .name = "no -1 tail", .from = "for (; m < 16; ++m) umem[u * 16 + m] = -1;", .to = "" }, + .{ .name = "window rows, not live rows", .from = "const int S = metal::min(metal::max(R, 0) * 10, 160);", .to = "const int S = int(d.rows) * 10;" }, + .{ .name = "members past the first dropped", .from = "if (pk[t] == pk[i]) umem[u * 16 + m++] = t;", .to = "if (pk[t] == pk[i] && t == i) umem[u * 16 + m++] = t;" }, + .{ .name = "row routed at the wrong place", .from = "pick + ulong(gid.y) * 10ul", .to = "pick + ulong(gid.y) * 9ul" }, + }; + for (controls) |c| { + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src, c.from)); + const text = try std.mem.replaceOwned(u8, a, src, c.from, c.to); + defer a.free(text); + const lib = try mtl.Library.fromSource(dev, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const fx = try mtl.Pipeline.init(dev, lib, "fn_pw_fwht_x_fwd", false); + defer fx.deinit(); + const dd = try mtl.Pipeline.init(dev, lib, "fn_pw_dedup_par", false); + defer dd.deinit(); + if (try rig.agrees(queue, &pipes, fx, dd)) { + std.debug.print("planted control passed: {s}\n", .{c.name}); + return error.PlantedControlPassed; + } + } +} diff --git a/zig/tests/flashnext_tfq3_test.zig b/zig/tests/flashnext_tfq3_test.zig index f22cec3ae83..977d61ddf6c 100644 --- a/zig/tests/flashnext_tfq3_test.zig +++ b/zig/tests/flashnext_tfq3_test.zig @@ -422,10 +422,11 @@ fn parity(units: bool) !void { ck.widths[r * 11 + 10] = 8; } - // Run B=4 deduplicated in one pass, twice: the repeat gives the same output bytes. + // Run B=4 deduplicated in one pass, three times: route_dedup, then the default twice, all the same output bytes. var first: ?[]u16 = null; defer if (first) |f| a.free(f); - for (0..2) |pass| { + for (0..3) |pass| { + pipes.serial_route = pass == 0; // pass 0: main's route_dedup; 1, 2: the default, the same bytes, last const cb = queue.commandBuffer(); run.enc = cb.compute(.serial); tfq3.dispatch.moeDecode(