Repository navigation
feat(flashnext): add native Metal TFQ3 (2D-AffineCoset/half4) routed MoE runtime - #4964
Merged
Merged
Conversation
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
force-pushed
the
feat/flashnext-tfq3
branch
from
November 24, 2026 23:01
10d1979 to
40411e4
Compare
…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
force-pushed
the
feat/flashnext-tfq3
branch
from
November 25, 2026 04:13
0c73650 to
3e2f672
Compare
ashhart
added a commit
that referenced
this pull request
Nov 25, 2026
This was referenced Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 theflashnext(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 viammap+ page-alignedbufferNoCopy(with safe copy fallback for unaligned metadata sections) and dispatched through native TFQ3 Metal kernels for both decode (B=1and deduplicatedB=2..16) and prompt prefill (supporting both M5 NAXtensor_opsand pre-M5TF_SIMD_FRAGSviafrags.precision.source). Non-TFQ3 checkpoints take the existing MLX affine paths with zero behavior change.Key Changes
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-bit2D-AffineCoset/half4trellis matvec helpers (nosplit1/2/4).moe_decode.metal: Fused decode kernels (dec_gu_b1,dec_down_b1,dec_gu_dedup,dec_down_dedup) specialized forHAS_5B ∈ {false, true}.prefill.metal: Tile-scanned TFQ3 prefill GEMM reusing existingb.ds/b.ascratch buffers (zero extra prefill VRAM; safe for staggered 2-segment prefill).zig/src/families/flashnext/):tfq3_files.zig(host-only sidecar discovery & byte sizing underflashnext_memory),tfq3.zig(header/bounds-checked zero-copy mmap loader + lazyPipesregistered inr.held),tfq3_dispatch.zig(decode & prefill dispatchers).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.--ssd-expertscleanly on TFQ3 checkpoints while keeping--ple-on-ssdfully supported.zig/tests/flashnext_tfq3_test.zig, steptest-flashnext-tfq3):fp64reference (max_diff < 0.02), bit-exactB=1 == B=4decode parity, and prefill-vs-decode parity.Verification
Automated Checks
zig fmt --check build.zig zig— passedpython3 tools/pr_check.py—0 errors,0 new lean findingsTF_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 passedReleaseFast, NAXtensor_ops):zig build test-flashnext-tfq3 -Doptimize=ReleaseFast— passedReal Checkpoint End-to-End Benchmarks (
Qwen3.8-Flash-Nexton 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), plusp2048prefill,B=1, andMTP depth=3decode:p2048PrefillB=1DecodeMTP d3Decoded0 == d3Qwen3.8-Flash-Next-MLX-4bit-MTPloads withtfq3=falseand unchanged outputs/perplexity.