Skip to content

feat(flashnext): add native Metal TFQ3 (2D-AffineCoset/half4) routed MoE runtime - #4964

Merged
ashhart merged 7 commits into
mainfrom
feat/flashnext-tfq3
Nov 25, 2026
Merged

ashhart merged 7 commits into
mainfrom
feat/flashnext-tfq3

Conversation

@ashhart

@ashhart ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Summary

Adds runtime-only Metal support for TFQ3 (TensorFold Quant v3, 2D-AffineCoset/half4) routed MoE expert sidecars (pw_v3_tables.bin, layer_XX.tffpw, mtp_00.tffpw) in the flashnext (qwen4_exp) family on Apple Silicon.

When TFQ3 sidecars are present alongside a Flash Next checkpoint, routed MoE weights (switch_mlp.{gate,up,down}_proj, 512 experts, H=2560, I=640) are loaded zero-copy via mmap + page-aligned bufferNoCopy (with safe copy fallback for unaligned metadata sections) and dispatched through native TFQ3 Metal kernels for both decode (B=1 and deduplicated B=2..16) and prompt prefill (supporting both M5 NAX tensor_ops and pre-M5 TF_SIMD_FRAGS via frags.precision.source). Non-TFQ3 checkpoints take the existing MLX affine paths with zero behavior change.

Key Changes

  • Metal kernels (zig/kernels/metal/flashnext_tfq3/):
    • common.metal: FWHT-128 block rotations, exact top-10/512 routing + batch dedup, branch-hoisted zero-spill MLX affine shared-expert helpers (2/3/4/5/6/8-bit, group ∈ {32,64,128}).
    • moe_mv.metal: 3-bit / 4-bit / 5-bit 2D-AffineCoset/half4 trellis matvec helpers (nosplit1/2/4).
    • moe_decode.metal: Fused decode kernels (dec_gu_b1, dec_down_b1, dec_gu_dedup, dec_down_dedup) specialized for HAS_5B ∈ {false, true}.
    • prefill.metal: Tile-scanned TFQ3 prefill GEMM reusing existing b.ds/b.a scratch buffers (zero extra prefill VRAM; safe for staggered 2-segment prefill).
  • Zig runtime, admission & budgeting (zig/src/families/flashnext/):
    • tfq3_files.zig (host-only sidecar discovery & byte sizing under flashnext_memory), tfq3.zig (header/bounds-checked zero-copy mmap loader + lazy Pipes registered in r.held), tfq3_dispatch.zig (decode & prefill dispatchers).
    • Wired into index.zig, load_admission.zig, load_memory.zig, load_weights.zig, engine_load.zig, engine_widths.zig, engine_warm.zig, scale_index.zig, prompt_w.zig, replay*.zig, batch_forward.zig, run_cleanup.zig.
    • Refuses incompatible --ssd-experts cleanly on TFQ3 checkpoints while keeping --ple-on-ssd fully supported.
  • Tests (zig/tests/flashnext_tfq3_test.zig, step test-flashnext-tfq3):
    • Sidecar discovery, shader compile, 3b/4b/5b routed + 8b/32 shared decode vs CPU fp64 reference (max_diff < 0.02), bit-exact B=1 == B=4 decode parity, and prefill-vs-decode parity.

Verification

Automated Checks

  • zig fmt --check build.zig zig — passed
  • python3 tools/pr_check.py — 0 errors, 0 new lean findings
  • Local (pre-M5 TF_SIMD_FRAGS): zig build test-flashnext-tfq3 test-flashnext-host test-flashnext-budget test-flashnext-buffer-plan-host test-flashnext-memory-host test-flashnext-load-admission test-flashnext-cleanup-host test-flashnext-ssd-budget-host test-flashnext-ssd-review-host test-kernel-contract — all passed
  • Apple M5 Ultra (ReleaseFast, NAX tensor_ops): zig build test-flashnext-tfq3 -Doptimize=ReleaseFast — passed

Real Checkpoint End-to-End Benchmarks (Qwen3.8-Flash-Next on Apple M5 Ultra)

Evaluated across 1,670 main tokens (4 domains: code_systems, math_physics, prose_history, ml_quant) + 334 unseen held-out tokens (3 domains: rust_async, physics_statmech, tool_json_reasoning), plus p2048 prefill, B=1, and MTP depth=3 decode:

Checkpoint Disk Size Main NLL (1,670 tok) Held-Out NLL (334 tok) Combined PPL (2,004 tok) p2048 Prefill B=1 Decode MTP d3 Decode d0 == d3
8-bit/32 Source (Gold) 189.04 GiB 1.7315 2.1003 6.007 3,422 tok/s 79.2 tok/s 153.9 tok/s (3.74 tok/rd) BIT-EXACT
MLX 4-bit/32 105.50 GiB 1.8324 2.2006 6.644 3,914 tok/s 106.2 tok/s 212.1 tok/s (3.53 tok/rd) BIT-EXACT
TFQ3 (8b non-MoE + 3b PLE) 78.99 GiB 1.7298 2.0978 5.996 3,855 tok/s 82.9 tok/s 154.5 tok/s (3.63 tok/rd) BIT-EXACT
TFQ3 (8b non-MoE + 4b PLE) 84.95 GiB 1.7336 2.1210 6.038 3,856 tok/s 82.9 tok/s 160.1 tok/s (3.74 tok/rd) BIT-EXACT
  • Non-TFQ3 regression check: Qwen3.8-Flash-Next-MLX-4bit-MTP loads with tfq3=false and unchanged outputs/perplexity.

ashhart added a commit that referenced this pull request Nov 24, 2026
ashhart added a commit that referenced this pull request Nov 24, 2026
@ashhart
ashhart force-pushed the feat/flashnext-tfq3 branch from 10d1979 to 40411e4 Compare November 24, 2026 23:01
…or a pointer, and each mapping has one owner

E332's F1 and F2, as #4953 had them fixed:
- tfq3_check.zig (std only, beside tfq3_files in the memory module) checks a shard with checked casts, sums
  and products: magic and version, the layer it must hold (layer_NN.tffpw; the MTP shard has none to
  match), 512 experts and 1,536 tensors at 640 x 2560, three in-file sections apart from each other and the
  header, and every expert's 3/4/5-bit width with its gate, up and down words and scales inside their
  sections. Records are decoded by copy, so no host pointer depends on an alignment. Refusals are named
  (Tfq3Truncated, Tfq3Overflow, Tfq3Overlap, Tfq3Geometry, Tfq3Bits, Tfq3Layer, Tfq3Table).
- tfq3_files.scan reads each present shard's header and records and checks them, and needs the table
  beside them: presence now means a checked shard, so a 16-byte sidecar no longer relaxes index admission
  or reaches construction. Admission, both budgets and the --ssd-experts refusal take its refusal.
- The loaders check the whole mapping with the same checks, reserve their lists, make their views under
  local cleanup and then hand the mapping and views over in one step that cannot fail; bytes are counted
  after. A failure unmaps once and leaves no entry for run_cleanup. Page-unaligned sections keep their copy.
- Host tests: a valid control, E332's witnesses (the 65,540-byte shard, layer 1 in layer_00, the wrapping
  offsets and counts) and each boundary, and the scan over real files. The format and its arithmetic are
  unchanged.
… exact bytes, in both modes

E332's F4: decode B=1 against B=4 was already exact; a second B=4 pass is now compared with the first byte for
byte, and the whole test runs in the device's mode and, on an M5, in the simdgroup mode too (Pipes.initUnits),
so the alternate mode executes rather than only compiling. Prefill against decode keeps its 0.02 bound: the
owner's ruling lets the format's prefill round apart from decode.
…int4 loads read them

E333's remaining F1 case: tfq3_check accepted any gate, up or down word offset whose matrix fit its section,
but the 4-bit matvec and prefill kernels read those words four at a time as uint4 (moe_mv.metal:64, 114, 178;
prefill.metal:170, 298), so an offset off a multiple of four words reached a misaligned vector read.
check.experts now refuses such a 4-bit offset by name (Tfq3Misaligned), in the scan before admission and in the
loader alike. 3- and 5-bit words and every scale stream are read one element at a time and keep any offset;
section bases are already aligned (page-aligned views, or their own buffer). The format is unchanged.

Tests: E333's witness (gate at word 1) and the up and down cases refused, with aligned and 3/5-bit controls;
the earlier truncation case moves by a whole uint4 so it still tests the end.
On an M5 the decode/prefill parity test failed without output: its command-buffer checks and its three
bounds were bare expects. Each check now prints the mode it compiled (tensor-unit or simdgroup), the
comparison, the first index off with its row, slot and width, and both values before returning, and a
setup error is named with its mode. The bound checks count a NaN as past the bound; @max dropped NaNs, so a
NaN output used to pass. The exact checks (repeat, B=1 = B=4) and the 0.02 bounds are unchanged.

The checks live in flashnext_tfq3_report.zig, with a test of their messages.
… checks' test prints nothing

The M5 run named one real failure: the simdgroup source's prefill, executed on an M5, misses decode.
The three tensor-unit lines above it (a failed prefill buffer, B=1 against B=4, a NaN) were the checks'
own passing test printing its examples; the tensor-unit run passed.

The simdgroup source is right only before the M5 by construction. Its prefill still runs matmul2d
(nax.h, without TF_GLM_M3_FAST), but places fragment element e at cooperative-tensor slot
(e >> 2) * 8 + (e & 3) and b1 at slot + 4, while the tensor-unit source places it at e and b1 at 8 + e.
A chip has one slot layout, so at most one mapping is right on it: the tensor-unit one on the M5, the
simdgroup one before it. The engine never mixes them (Pipes.init compiles the chip's own source).

The parity test still runs the simdgroup source's decode on an M5 (decode uses no tensor op), and
compares prefill only where the source matches the chip. The checks' test runs quiet.
@ashhart
ashhart force-pushed the feat/flashnext-tfq3 branch from 0c73650 to 3e2f672 Compare November 25, 2026 04:13
@ashhart
ashhart merged commit 4c79cfe into main Nov 25, 2026
24 of 37 checks passed
ashhart added a commit that referenced this pull request Nov 25, 2026
@ashhart
ashhart deleted the feat/flashnext-tfq3 branch November 25, 2026 04:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant