Skip to content

flashnext tfq3: route B=2..16 decode windows in parallel and build the dedup lists in parallel, bit for bit - #5506

Open
abm9111 wants to merge 4 commits into
ashhart:mainfrom
abm9111:pr/tfq3-parallel-route
Open

abm9111 wants to merge 4 commits into
ashhart:mainfrom
abm9111:pr/tfq3-parallel-route

Conversation

@abm9111

@abm9111 abm9111 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #5471

What

In a TFQ3 decode window of 2-16 rows on Metal (any Apple GPU: the decode dispatch has no tensor-unit branch),
moeDecode ran fn_pw_route_dedup as one 32-thread threadgroup: it routed each row's top 10 one row after another, then lane 0 alone built the dedup lists
(uids, umem, ucount) while the rest of the GPU waited behind the barrier.

  • fn_pw_fwht_x_fwd: with a new flag bit 4, group 20 routes every live row (gid.y < R), not only row 0. Same
    fn_route_row, so picks and weights are the same bits. moeDecode launches 21 groups at every width.
  • New fn_pw_dedup_par (one threadgroup, a thread a slot, max_total_threads_per_threadgroup(160)): a slot opens a
    list when no earlier slot picked its expert; the list's index is the number of lists earlier slots opened; its
    members are the slots holding that expert in slot order, then -1. That is route_dedup's order, so uids, umem
    and ucount are the same bytes, and lists past ucount are untouched as before.
  • FZ_TFQ3_SERIAL_ROUTE=1 keeps the old path (row added to docs/environment-names.md; happy to drop it).
  • B=1 is unchanged.

Exactness

No arithmetic changes. zig/tests/flashnext_tfq3_route_test.zig (under test-flashnext-tfq3) compares every output
buffer of the new path with route_dedup's byte for byte: windows of 2-16 rows; live rows equal to the window, one
less, 1, 0 and above it; independent, overlapping, tied and paired picks and rows with three finite logits; five
repeats, untouched bytes checked against a fill. Five planted controls (lists in expert order, no -1 tail, window rows
instead of live rows, members after the first dropped, a row's picks at the wrong offset) each make it fail. The B=4
parity test in flashnext_tfq3_test.zig gets a third pass through route_dedup, byte-equal to the first.
test-flashnext-tfq3 passes on an M3 Ultra; not run on M1, M2 or M5, and the speed below is the M3's only. The M5 runs
the same routing path, where the old step is the same serial single-simdgroup latency, so I expect a gain there too;
not measured.

Speed

M3 Ultra (60-core GPU), macOS 27.2, tensorfold-native built from main and from this branch
(zig build native -Dcpu=apple_m1), TensorFold/Qwen3.8-Flash-Next-TFQ3 at eeb675d, MTP drafts on (defaults),
A-B-B-A, a fresh server per arm and round. Drafted cells: 3 MMLU-Pro prompts, a code prompt and a prose prompt greedy
at 768 tokens, and 2 prompts sampled at temperature 0.8, seed 7, 512 tokens. Plain cells: the 5 greedy prompts with
--no-drafts. Engine-logged decode time.

Arm drafted ms a round drafted tok/s plain ms a token
main 26.64, 28.19 111.2, 105.1 15.42, 15.63
this branch 25.48, 25.59 117.1, 116.4 15.59, 15.57
  • Drafted: -1.88 ms a round (-6.8 %), +8.0 % tok/s, faster in both pairs.
  • Plain (one row): unchanged, as expected.
  • Every reply in every arm and round has the same token hash, greedy and seeded sampled.
  • The faster arm finished about 0.7 % more tokens a round (2.98 against 2.96) with the same tokens; round boundaries
    were not exactly fixed from run to run on main either, so the ms-a-round figure is the cleaner one.

Open points (from #5471)

@abm9111

abm9111 commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

The two red checks are not from this branch: env_names.py on main (d593d2e) reports the same TF_Q27_FLAT_GLUE / TF_Q27_QK rows missing, and zig-windows fails in cuda.zig's checkpoint_cli imports (tfq3_validate.zig needs flashnext_memory), which this PR does not touch.

@ashhart

ashhart commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Thanks, @abm9111. The parallel routing keeps the old slot order, and the new suite compares every routing buffer byte for byte across live-row variants with planted controls that can fail. B=1 and the serial fallback are preserved.

One landing requirement is still missing. zig/kernels/metal/flashnext_tfq3/common.metal:154 adds fn_pw_dedup_par, but the kernel is not registered with the Metal kernel contract. The standalone route suite is useful evidence; it does not replace contract registration.

Please register the kernel for gates 1–5 at its served 2–16-row shapes, including its 160-thread launch and M1/M2 compile-time limit records. Keep the byte-equality and planted-control checks, and post the resulting contract summaries with any unrun chips named. I found no other source blocker in this re-check.

No device run was performed here.

  • Synthena

…for TFQ3 parallel routing

A-B-B-A against main on an M3 Ultra with the published TFQ3 checkpoint (TensorFold/Qwen3.8-Flash-Next-TFQ3
at eeb675d): drafted 27.41 -> 25.54 ms a round, 108.1 -> 116.7 tok/s, faster in both pairs; one row 15.52 /
15.58 ms; every token hash equal in every arm and round.
@ashhart
ashhart force-pushed the pr/tfq3-parallel-route branch from 9a60a8c to 93507d9 Compare November 29, 2026 20:11
…row windows

A replacement of fn_pw_route_dedup's lists: gates 1-4 run fn_pw_dedup_par on the picks route_dedup made and
require route_dedup's uids, umem and ucount byte for byte, at every window from 2 to 16 rows with live rows equal,
one short, 1, 0 and 3 past the window (74 shapes); each window meets all five of the route suite's logit patterns.
Gate 1 turns each planted row's first pick into NaN or -Inf and adds +Inf. Five planted controls, each red at gate
3: the route suite's four source edits and live rows not capped at the window. Gate 5: 160 threads reserved in the
source, 800 threadgroup bytes, and the M1/M2 compiles' limit of 160. A control whose source edit no longer applies
is tallied as an init error rather than stopping the run.
@abm9111

abm9111 commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. fn_pw_dedup_par is now registered with the kernel contract in f4dd630 (one commit on your rebased head 93507d9).

Registration (zig/tests/contract/metal_flashnext_tfq3_dedup.zig)

  • Replacement of fn_pw_route_dedup's lists: gates 1–4 run fn_pw_dedup_par on the picks route_dedup made and require its uids, umem and ucount byte for byte. Outputs on both sides start as 0xA5 (0xFF would read as a tail's -1).
  • Served shapes: every window from 2 to 16 rows, with live rows equal to the window, one short, 1, 0, and 3 past the window (74 shapes). The route suite's five logit patterns (independent, shared set reordered, ties, paired rows, -inf rows) rotate across them: every window from 3 to 16 rows meets all five, the 2-row window four.
  • Gate 1: in each planted row, the would-be first pick becomes NaN or -Inf, and +Inf is added. Stated rule: it reads expert ids only; route_dedup skips NaN and ranks infinities, and its lists of those picks are matched byte for byte.
  • Gate 4: N/A (no sums).
  • Five planted controls, each red at gate 3: the route suite's four fn_pw_dedup_par edits (lists in expert order, no -1 tail, window rows not live rows, members past the first dropped), and R = rows_buf[0] (live rows not capped at the window). Only the past-window shapes catch the last one.
  • Gate 5 (tfq3_records.zig): 160 threads reserved in the source, 800 threadgroup bytes, M1/M2 compile limit 160 (from --offline).
  • If a control's source edit stops applying, it is tallied as an init error instead of stopping the whole run.

The byte-equality route suite is unchanged and still passes (zig build test-flashnext-tfq3: 4/4 tests).

SUMMARY, Metal, Apple M3 Ultra (applegpu_g15), macOS 27.2.1, Xcode 27.1, Zig 0.17.0, head f4dd630 (this kernel's lines and the SUMMARY; the harness's own self-check lines are left out):

$ tf-kernel-contract --only fn_pw_dedup_par --offline DIR
PASS nonfinite flashnext tfq3 fn_pw_dedup_par: the stated rule holds: it reads expert ids only; route_dedup skips NaN logits and ranks infinities, and its lists of those picks are matched byte for byte
PASS repeat flashnext tfq3 fn_pw_dedup_par: five runs byte-identical (10884 bytes), inputs and guards untouched, no overlap
PASS shapes flashnext tfq3 fn_pw_dedup_par: 74 shapes bit-equal to the kernel it replaces (worst 0.000 of the bound), 0 edges refused by the kernel
N/A  sums flashnext tfq3 fn_pw_dedup_par: declares none sums
FAIL shapes control: flashnext tfq3 fn_pw_dedup_par, lists in expert order: at 16x10x16 its bytes differ from fn_pw_route_dedup's uids, umem and ucount on the same picks's from byte 44
CONTROL control: flashnext tfq3 fn_pw_dedup_par, lists in expert order: red at shapes, as planted
FAIL shapes control: flashnext tfq3 fn_pw_dedup_par, no -1 tail: at 16x10x16 its bytes differ from fn_pw_route_dedup's uids, umem and ucount on the same picks's from byte 696
CONTROL control: flashnext tfq3 fn_pw_dedup_par, no -1 tail: red at shapes, as planted
FAIL shapes control: flashnext tfq3 fn_pw_dedup_par, window rows, not live rows: at 2x10x1 its bytes differ from fn_pw_route_dedup's uids, umem and ucount on the same picks's from byte 1280
CONTROL control: flashnext tfq3 fn_pw_dedup_par, window rows, not live rows: red at shapes, as planted
FAIL shapes control: flashnext tfq3 fn_pw_dedup_par, members past the first dropped: at 16x10x16 its bytes differ from fn_pw_route_dedup's uids, umem and ucount on the same picks's from byte 644
CONTROL control: flashnext tfq3 fn_pw_dedup_par, members past the first dropped: red at shapes, as planted
FAIL shapes control: flashnext tfq3 fn_pw_dedup_par, live rows past the window kept: at 2x10x5 its bytes differ from fn_pw_route_dedup's uids, umem and ucount on the same picks's from byte 1344
CONTROL control: flashnext tfq3 fn_pw_dedup_par, live rows past the window kept: red at shapes, as planted
PASS limits here flashnext tfq3 fn_pw_dedup_par: 160 threads launched, the pipeline takes 160; 800 threadgroup bytes and 0 set (declared at most 800, the GPU's most 32768)
PASS offline flashnext tfq3 fn_pw_dedup_par: 160 threads; M1 pipelines take 160, M2 160 (recorded 160, 160)
SUMMARY 1 kernels: 1 pass gates 1-4, 0 fail, 0 known findings; 5 controls: 5 red as planted, 0 missed; 0 limit problems; gates 110 ms, limits 146 ms

The run exited 0. (Shapes are rows x picks x live rows: the past-window control first went red at 2x10x5.)

SUMMARY, Metal, Apple M5 Ultra (applegpu_g17, tensor units true), macOS 27.2.1, Xcode 27.2, same head: the same lines, gate for gate and control for control, ending

PASS shapes flashnext tfq3 fn_pw_dedup_par: 74 shapes bit-equal to the kernel it replaces (worst 0.000 of the bound), 0 edges refused by the kernel
PASS limits here flashnext tfq3 fn_pw_dedup_par: 160 threads launched, the pipeline takes 160; 800 threadgroup bytes and 0 set (declared at most 800, the GPU's most 32768)
PASS offline flashnext tfq3 fn_pw_dedup_par: 160 threads; M1 pipelines take 160, M2 160 (recorded 160, 160)
SUMMARY 1 kernels: 1 pass gates 1-4, 0 fail, 0 known findings; 5 controls: 5 red as planted, 0 missed; 0 limit problems; gates 79 ms, limits 27584 ms

It also exited 0.
The M5 has Zig 0.17.1, which build.zig refuses, so it ran the runner built on the M3 machine with Zig 0.17.0 (-Dcpu=apple_m1, ReleaseFast, sha256 7c09e437…a1804; Metal source compiled at run time on the M5).

Chips: gates 1–4 and on-device limits ran on M3 and M5. M1 and M2 are covered by the offline compiles (no device). M4 was not run. CUDA, HIP and XPU: n/a (Metal-only kernel).

Two inherited problems on this base stop the Metal runner before any kernel runs; neither is touched here:

  1. IncompleteLlamaContract: ae60fb0 added ll_add_qkv_bias to llama/model.zig's glue_names with no registration, so requireComplete in metal_llama_all.zig fails on every run, --only or not. For the run above only, I appended that name to the runner's functions list locally; it is not in the commit.
  2. metal_q27_stack.zig Suite.deinit loops over s.precision twice, the second time after deinit has set it to undefined, so Debug and ReleaseSafe builds segfault in collectStack. The run above used a ReleaseFast build (-Doptimize=ReleaseFast), which avoids it.

A pre-existing edge I noticed while reading the router, not changed here: in fn_route_row (common.metal), a row whose logits are all NaN never replaces bid = 512. That id becomes a pick, and lane 0 writes v[512 >> 5], which is v[16], one past the end of the 16-element array. A row with at least one logit that is not NaN is fine: once that id is picked it becomes -inf, and later rounds fall back to the lowest -inf id. Gate 1 here does not plant an all-NaN row, since that would test route_dedup rather than dedup_par.

Checks on f4dd630: zig build test-kernel-contract passes (Metal launch map: 1483 registered launches, 0 missing); zig fmt --check build.zig zig and git diff --check are clean; lean is 92 on base 0546bee and 92 on head, 0 new.

@ashhart

ashhart commented Nov 30, 2026

Copy link
Copy Markdown
Owner

Thanks, @abm9111. The registration covers what we asked for, and the M3 and M5 summaries are easy to check.

Confirmed at f4dd630e6:

  • fn_pw_dedup_par is registered at every 2-16-row window. The live rows are set to the window, one short, 1, 0 and 3 past it (zig/tests/contract/metal_flashnext_tfq3_dedup.zig:69-93). Its lists are compared byte for byte with fn_pw_route_dedup's on the same picks (:238-243), and five planted controls go red (:21-34). The runner wiring is at zig/tests/contract/metal_main.zig:229-240.
  • Gate 5 has the 160-thread launch, 800 threadgroup bytes and the M1/M2 records (zig/src/core/contract/tfq3_records.zig:5-8), joined at zig/src/core/contract/registry_joins.zig:84.
  • The kernel follows route_dedup's order (zig/kernels/metal/flashnext_tfq3/common.metal:154-190). A slot opens a list only when no earlier slot holds its expert. The list's index is the number of earlier openings, and its members follow in slot order with a -1 tail. B=1 still routes row 0 alone under flags 2 (:206). The route suite still compares pick and wts byte for byte as well as the lists.
  • It merges cleanly with main.

One change is needed before landing. zig/src/families/flashnext/tfq3.zig:288 reads FZ_TFQ3_SERIAL_ROUTE with a raw getenv. New settings have to be read through the registry in zig/src/platform/environment.zig. There is also a bug in the current read: because it only tests for != null, FZ_TFQ3_SERIAL_ROUTE=0 would also turn the serial path on. The parallel path is shown to give the same bytes, so the simplest fix is to drop the environment read and its row at docs/environment-names.md:116. Please keep the serial_route field, which the parity test's first pass sets (zig/tests/flashnext_tfq3_test.zig:429). If you'd rather keep a switch, register it in environment.zig as a .metal .flag, add its cases to environment_valid_cases.zig, and read it with platform.environment.read(bool, "FZ_TFQ3_SERIAL_ROUTE", false).

Thanks also for reporting the two runner problems. Both are still on main: ll_add_qkv_bias is missing from the llama contract's function list, and Suite.deinit in zig/tests/contract/metal_q27_stack.zig walks precision twice. We'll take those up separately. And yes, please send the all-NaN guard for fn_route_row as its own pull request.

This was a source review; we haven't run it on a device ourselves.

  • Synthena

@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Performance receipt required (kind:perf)

Routes B=2..16 TFQ3 decode windows in parallel via a new fn_pw_dedup_par kernel and a flags bit in fn_pw_fwht_x_fwd, keeping route_dedup's output bytes bit for bit, with an env-var escape hatch and extensive byte-parity tests.

  • Performance claim detected without a verified tf-receipt-v1 receipt.

Performance PRs require a verifiable benchmark receipt before running project CI hardware. See CONTRIBUTING.md (Performance PRs: verifiable benchmark receipt) and attach the output of:

python3 tools/perf_receipt.py run --base-bin /path/to/base-tf --head-bin /path/to/head-tf --model /path/to/model.tfold --out receipt.json

Findings:

  • [BLOCKER] zig/kernels/metal/flashnext_tfq3/common.metal: fn_pw_dedup_par declares threadgroup arrays sized 160 and is launched with threadgroup size tfq3.max_decode_slots, but the kernel never checks that the launch width is at least S; if max_decode_slots were ever below 160 the tail slots would be silently unrouted, and more importantly the kernel reads rows_buf[0] and pick[i] for i < S without any guard that the pick buffer actually holds window10 live entries when rows_buf[0] exceeds d.rows (R is clamped, but pick indexing relies on the caller's buffer sizing). Suggested fix: Assert or document the invariant that the dispatch threadgroup size equals 160 (or >= S) and that pick has d.rows10 valid entries, e.g. add a compile-time/static check in tfq3_dispatch.zig tying the dispatch size to the kernel's [[max_total_threads_per_threadgroup(160)]] attribute.
  • [WARNING] zig/src/families/flashnext/tfq3_dispatch.zig: The flags value 4 is only meaningful for the non-serial path, but Dims.flags is also consumed by other kernels sharing this struct; if any other kernel interprets bit 4 differently the parallel path could silently change behavior outside moeDecode. Suggested fix: Confirm bit 4 is reserved exclusively for the routing flag in FnPwDims and add a comment or constant (e.g. kFlagRouteAllRows = 4) shared between the Zig dispatch and the Metal source so the two cannot drift.
  • [WARNING] zig/tests/flashnext_tfq3_route_test.zig: The parity test compares only the first sizes[j] bytes of each output buffer, but dedup_par writes uids/umem/ucount for lists past ucount as untouched (0xA5 fill); if route_dedup leaves different bytes in the untouched region than the 0xA5 prefill, the test would pass while the real engine buffers differ. Suggested fix: Also assert the untouched tail bytes equal the 0xA5 fill for both paths (the test already prefills with 0xA5, so add an explicit check that bytes past ucount*16 in umem and past ucount in uids remain 0xA5 on both sides).
  • Synthena

@ashhart ashhart added synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY and removed synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 5, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:perf Classified by Synthena as performance improvement synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY

Projects

None yet

2 participants