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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/environment-names.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
17 changes: 17 additions & 0 deletions docs/optimization-ledger.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --- | --- | --- | --- | --- | --- |
Expand Down Expand Up @@ -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 |
| --- | --- | --- | --- | --- |
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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 |
| --- | --- | --- | --- | --- |
Expand Down Expand Up @@ -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]),
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
11 changes: 10 additions & 1 deletion zig/build/flashnext_checks.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
44 changes: 43 additions & 1 deletion zig/kernels/metal/flashnext_tfq3/common.metal
Original file line number Diff line number Diff line change
Expand Up @@ -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)]],
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/contract/registry_joins.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 ++
Expand Down
7 changes: 6 additions & 1 deletion zig/src/core/contract/tfq3_records.zig
Original file line number Diff line number Diff line change
@@ -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 } } },
Expand Down
3 changes: 3 additions & 0 deletions zig/src/families/flashnext/tfq3.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)];
Expand Down Expand Up @@ -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,
};
}

Expand Down
35 changes: 23 additions & 12 deletions zig/src/families/flashnext/tfq3_dispatch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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) {
Expand Down Expand Up @@ -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));
Expand Down
5 changes: 5 additions & 0 deletions zig/tests/contract/metal_family_limits.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
Loading
Loading