Repository navigation
CUDA: read the Flash Next NVFP4 (ModelOpt FP4) checkpoint as it ships - #67
tournierjc wants to merge 125 commits into
Conversation
…bles The Swift 1.5 Flash Next NVFP4 checkpoint (ModelOpt) quantizes the routed experts only: packed E2M1 nibbles, fp8e4m3 block scales (groups of 16) and a per-tensor scale; everything else is BF16. - nvfp4.py: the checkpoint's layout (bits built by hand around torch's broken fp8 casts), the FP4 table (E2M1 codes as bf16 bit patterns + fp32 row scales), the dequantize reference, split-K by shape, and the Triton matmul: one tensor-core dot per 16-input block, the block's fp32 row scale one fp32 rounding after, slices summed in slice order - a row's bits depend on its row and the shape only. - nvfp4_moe.py: MoE4 on the qmm Experts face (stacked gate/up and down grids with an expert axis over the tiles, the shared BF16 expert as an identity-scaled table), the grouped gateup/down steps and the engine's moe() into the qmm MoEBuffers contract. - tests/cuda/test_flashnext_nvfp4.py: the format on CPU (packing, dequantize, tiling, the stacked grid, the shared table, split-K by shape) and kernel-first on CUDA (the fp32 reference, row invariance at 1..128 rows, the split-K reduce's order). Real-checkpoint layer 11 (experts 0/255/511): dequantize is exact row-for-row against the stored triples, the stacked grids included.
…experts, the stacked tables checked on real data
…le's refusals route)
…eal checkpoint checks
…checkpoint excludes them from FP4)
… change speed, never bits)
…scales stacked, load time at the 512-expert scale)
…oken-id order (the sampler maps the subset as on the MLX path)
… format, the header, the route's faces)
…ls, the value table for subnormals, the NaN codes kept) — the widening the real checkpoint's scales decode through
…rwise), the Swift checkpoint listed in MODELS
…ous, N tiles outer) and the decode gathering in int64 — torch's CUDA kernels index no uint16, and a program's scale block needs SBN
…, the qmm kernels' dest), count read as the property it is, and the per-row reference taking a window row
…he weight's shape, never the row count) and the K loop in block steps
…rs by their names (b16_from_rows, stack(proj))
…hecks (I64 like the real one, and a table of their row count) and the loader test comparing on the tensor's device
…Spark list, the runbook's) and what the real weights were checked against (layer 11, the tail, the n-gram constants)
…delOpt config and its block size of 16, the Swift checkpoint in 'models')
… widths nvfp4_tiny.write takes a prefix and writes the language model as model.language_model.* while lm_head and mtp stay top level, and it now sizes the tensors the way the real checkpoint and the engine's buffers do: attention and DeltaNet take hidden (not streams*hidden), lm_head takes hidden, the hyper-connections keep the wide stream dimension, and the n-gram shards are dims/8 int32 words with dims/32 fp16 scales and biases at ngram_size 3, matching state.Buffers' PLE rows. The loader test gains the naming case: the same checkpoint written both ways loads to the same faces.
Revision 3ff05202 stores the PLE table as plain BF16 rows (…ngram_embedding.shard_N.weight, [2500012, 160] a shard) with no per-shard scales or biases, where the converted checkpoints pack 4-bit words plus a scale and bias every 32 values; the loader looked for that 4-bit layout only, so a full serve of the revision stopped at layer 1's PLE. host_table.BF16Table memory-maps the rows as uint16 and gathers them a lookup at a time, ple_nvfp4 picks the layout from the shard's own header (4-bit shards to HostTable, BF16 rows to BF16Table) and refuses a mix, and stage_ple_rows copies the rows to the device as they are for glue.ple_embed_bf16, which places them per head and sums each group of 32 as the 4-bit kernel does after dequantizing. Checked against the real revision: shard 2 of embedding-model-00006-of-00131.safetensors (BF16 [2500012, 160], 800 MB) gathers rows bit-identical to an independent read of the file, 128 shards of that size make the 320,001,536-row table the digest derives, and the engine's staging and kernel place real values. Tests: the loader picks BF16Table and its gather equals the file's bytes, stage_ple_rows lands them in the buffers bit for bit, ple_embed_bf16 places rows and sums groups at (2, 32) and (16, 160), and a forward with the PLE layer live over a BF16 table keeps the window contract — a window's logits equal serial steps' bits. The README, RUNBOOK and the Flash Next recipe say the table's BF16 layout is read as it ships instead of naming it a gap, and engine.py's PLE budget sums each table's own nbytes.
The FP4 checkpoints store their block scales as `F8_E4M3` — the published Swift revision carries 73,728 of them, and across its 81 safetensors files that was the only dtype `capacity.SIZES` lacked — so the header walk died on a bare KeyError that `admit`'s rank-wide handler reported as "CUDA startup memory geometry could not be established on every rank: 'F8_E4M3'", a message that names neither the tensor nor the cause. FP8 is one byte a value like the other formats: SIZES gains F8_E4M3, F8_E5M2 and F8_E8M0; an unknown dtype now raises a ValueError naming the tensor and listing the known dtypes, through `capacity.itemsize`, which `geometry.size` and `geometry.padded` use too so an unsizable dtype names itself wherever the estimate reads headers; and the admission handler prefixes the exception type, so the next such failure reads as a cause rather than as text. Checked on the published revision (3ff05202) over its real headers: the estimate completes — 97.39 GiB within a 104.28 GiB budget, native window 262,144 tokens, weights 78.54 GiB, loading 18.85 GiB, cache workspace 18.14 GiB — and the n-gram table measures 95.37 GiB in the BF16 layout this revision ships (102.4 GB over 128 shards, not the 29.8 GiB the 4-bit layout takes), so it does not fit beside the weights and caches and its pages are read from disk. Before this commit the same command printed the dtype and stopped. Tests: an `F8_E4M3` tensor is sized at one byte a value, and a dtype the estimate cannot size reaches the operator's message with the tensor's name in it.
…rnel The FP4 table stored one uint16 bf16 bit pattern a weight and fp32 block scales, so an FP4 checkpoint cost four times its codes on the device: the published Swift revision's 60.4 GB of U8 words became 241.6 GB of patterns, plus 30.2 GB of fp32 scales where the file holds 7.55 GB of fp8e4m3, and building a single layer peaked at 16.26 GiB (a 6.25 GiB int64 gather index for one expert stack). Measured on the hardware: 5.67 GB of tables a layer for a 1.42 GB checkpoint layer — the model could not be served on a 121.56 GiB GPU at all, and the admission estimate, which counts file bytes, could not see why. `FP4` now carries the checkpoint's bytes: the codes as their stored nibbles ([N/BN, K/64, 32, BN] uint8, the low nibble the even input) and the block scales as their stored fp8e4m3 bytes ([K/16, N] uint8), with the per-tensor `weight_scale_2` a fp32 kernel argument — never a widening in memory. The kernel unpacks the nibbles through a field-arithmetic E2M1 table and rebases the fp8 exponent (the subnormals as values, the NaN codes as NaN) exactly as `e2m1_bits` and `row_scales` do, and the weight traffic halves with it: a byte a value, not two. The exact-BF16 form stays for operands that are not E2M1 — the shared expert — as patterns with fp32 scales, chosen by the table's `packed` flag, both paths compiled into one kernel. `stacked_fp4` builds the per-expert form, one factor an expert beside its rows, the gate/up join keeping each half's own. Verified on the hardware: the stored bytes are 1.01x the checkpoint's, was 4.00x. 462 CUDA tests pass — the four NVFP4 files at 50 — including two that pin the guarantee: a packed table holds the checkpoint's bytes, and a packed stack keeps each expert's slab decodable. The n-gram tables' mappings are advised MADV_RANDOM: their readers gather rows by key, so read-ahead brings in pages nobody asked for beside the weights (102 GB of table against 79 GiB of them).
A table the eager step and a CUDA graph capture both read must not allocate on first use: the pattern form now carries its ones factor from construction, so nothing allocates inside a capture. Also forwards the CUDA crash switches through the serving container when set (TORCH_USE_CUDA_DSA, CUDA_LAUNCH_BLOCKING, PYTORCH_CUDA_ALLOC_CONF).
…turable The NVFP4 grouped step walks its plan's item list and its counts on the host — items() slices plan.items and calls tolist() — a synchronising device-to-host copy. Inside a capture that is cudaErrorStreamCaptureInvalidated: a real serve died after loading the weights with "operation failed due to a previous error during capture" and nothing pointing at the cause. The tiny tests never saw it, because they capture with empty plans, where tolist() reads nothing. MoE4 declares capturable = False and the engine reads that answer instead of capturing a step that cannot be captured: it decodes eagerly, says so once, and the model serves. The tokens are the same — the eager path is the one the tiny tests exercise end to end. A device-side item loop, as the generic grouped path has, is what would let this route capture again. Two tests pin it: the route's own declaration, and an engine asked for graphs over such experts building none and still decoding.
Correct dequant fixed quality but open-ended prompts accept few MTP drafts, so depth=10/confidence=0.20 wasted large verify windows. Cap proposed drafts from a recent-accept EMA (tokens unchanged — verify still exact-matches). Keep NVFP4 draft-vocab lm_head rows in BF16 by default so proposals match verify dtype; TENSORFOLD_NVFP4_DRAFT_HEAD=q4 restores the 4-bit A/B path.
Correct dequant fixed quality but open-ended prompts accept few MTP drafts, so depth=10/confidence=0.20 wasted large verify windows. Cap proposed drafts from a recent-accept EMA (tokens unchanged — verify still exact-matches). Keep NVFP4 draft-vocab lm_head rows in BF16 by default so proposals match verify dtype; TENSORFOLD_NVFP4_DRAFT_HEAD=q4 restores the 4-bit A/B path.
tensorfold/cuda/nvfp4_experts.{cu,cpp,py} runs NVIDIA's FP4 experts the way experts.cu runs MLX 4-bit ones: a
warp a (item, 16 rows, 32 columns) unit on the experts plan, the tensor-core fragments loaded two groups ahead.
A table keeps the checkpoint's bytes: the E2M1 nibbles in experts.pack's fragment order (the two formats pack
nibbles alike) and, where an MLX group keeps its scales and biases, the 64-input group's e4m3 block scales, a
word a lane. Lane t of a quad carries one NVFP4 block's inputs, so a lane decodes its fragment to exact bf16
values, 2 x code x block scale (a byte table and nvfp4_format.cuh's e4m3; at most six significant bits), and each
(pair, column) is one fp32 mma chain over K: K split into slices fixed by K (4 at 2,048 inputs, 2 at 512), the
slices added in order in shared memory, times the expert's per-tensor scale over two. A pair is one mma row, so
no pair's bits depend on the other rows of a call. The shared expert is the table's last expert: a MoE step is the
router, the plan, one gate/up launch (SwiGLU epilogue) and one down launch. A prompt plan's call takes K in one
slice and four row tiles a warp (chunk-invariant bits of its own); the dense form runs one table with no plan.
On an RTX PRO 6000 Max-Q with Qwen3.6's shapes (257 experts, 512 x 2,048), a layer's gate/up takes 11 us for one
row and 33 us for four (MLX 4-bit: 33 and 38; ashhart#67's grouped Triton step: 155 and 263), down 5 and 17 us; a
4,096-row prompt chunk 1.07 and 0.69 ms (MLX's prompt kernels: 1.05 and 0.72). tensorfold.cuda.moe.run takes
an nvfp4-grouped table.
Tests: the table keeps the checkpoint's bytes (subnormal block scales included); pairs get the fp32 reference's
values in both forms; every row alone and among up to 1,024 rows (5,120 pairs, the plan's wide form) keeps its
bits; the dense form's rows keep theirs and score the reference's values.
- Experts: each layer's 256 routed experts and its NVFP4 shared expert in one nvfp4_experts table (gate/up 0.84 ms of a four-row verify forward, 10.6 ms on ashhart#67's grouped step). MoE4 and the shared-expert pool go. - Heads: lm_head and the draft head through nvfp4_experts' dense form, 210 us and 78 us for a row (ashhart#67's nvfp4.matmul: 608 and 192); the draft head's logits are the head's own, bit for bit. - MTP layer: its bf16 experts only draft, so they ride the MLX route's 4-bit experts kernel, requantized at load (affine4): drafting stays as fast as the MLX route's and the layer takes 0.46 GB, not 1.7. - Prompt chunks: the FP8 projections take K in one slice with 128-wide tiles (a 4,096-row chunk's in 51 ms, not 93); with the experts' prompt form a 4,096-token prompt prefills at 19,500 tok/s (was 13,400; MLX 22,100). A verify forward takes 4.4 ms of GPU time for one row and 5.1 ms for four (MLX 4-bit: 4.7 and 5.0). Admission counts the tables (the MTP layer at 4 bits) and no pool. Tests: the loader's table holds each expert's and the shared expert's bytes and halved scales; the MTP experts' 4-bit fit; the heads' dequantized weights; the prompt form's FP8 rows keep their bits.
…ps (#67) PR #67's first twenty commits, rebased onto next-0.3.6.2 as one (their branch merged main twice; the moved MoE module is the only adaptation). Its commits: - nvfp4: the format's decoder, its row-invariant matmul, and the MoE tables - nvfp4: the engine's route for the checkpoint — BF16 non-experts, FP4 experts, the stacked tables checked on real d - nvfp4: the family admits modelopt checkpoints on CUDA (require_readable's refusals route) - nvfp4: the recipe's NVFP4 section — the format, the route, what the real checkpoint checks - nvfp4: the MTP layer's BF16 stacked experts ride the FP4 tables (the checkpoint excludes them from FP4) - nvfp4: the BF16 embedding as a plain B16 (the row lookup, not a matmul face) - nvfp4: the draft head from the bf16 lm_head requantized 4-bit (drafts change speed, never bits) - nvfp4: the whole expert stack decodes in one pass (e2m1_bits and row_scales stacked, load time at the 512-expert sca - nvfp4: the draft head quantized from the full bf16 lm_head, rows in token-id order (the sampler maps the subset as o - nvfp4: a tiny modelopt checkpoint builder and the loader's tests (the format, the header, the route's faces) - nvfp4: e4m3_bits exact on all 256 fp8 codes (the field form for normals, the value table for subnormals, the NaN cod - nvfp4: the family's check reads modelopt (NVFP4 group 16 refused otherwise), the Swift checkpoint listed in MODELS - nvfp4: the FP4 tables in the kernel's tile order (the K block contiguous, N tiles outer) and the decode gathering in - nvfp4: the MoE buffers at the engine's flat index (row * slots + slot, the qmm kernels' dest), count read as the pro - nvfp4: the b16 matmul reading whole BK blocks a slice (the split by the weight's shape, never the row count) and the - nvfp4: the loader's BF16 faces and the expert stack calling the helpers by their names (b16_from_rows, stack(proj)) - nvfp4: the tiny checkpoint shipping the n-gram constants the loader checks (I64 like the real one, and a table of th - nvfp4: the docs say what the engine reads (README's refusals and the Spark list, the runbook's) and what the real we - nvfp4: the CPU checks pin the NVFP4 route (the family's check on a ModelOpt config and its block size of 16, the Swi - nvfp4: the tiny fixture mirrors the published naming and the engine's widths
|
Thank you, @tournierjc. This is careful work and it's going in: your commits shipped in 0.3.6.3 with |
|
Thank you - and the 186 GB checkpoint runs end to end here. One DGX Spark (GB10, 128 GB unified), 0.3.6.3 (1911880), Throughput, TTFT from the first streamed chunk, decode as
The replies are coherent French (the checkpoint thinks before it answers). One client trap worth knowing: it streams its text as Against the branch this rig was pinned to ( One thing I did find still open on main, in For the record, on the branch's Triton grouped step (which main no longer has): timing it against variants of its own source with each decode replaced by a cast puts the E2M1 and E4M3 decodes at 21% of the step at this geometry, and the step itself reads at 65.8%/71.4% of the box's 273 GB/s standalone but only ~40% inside a captured round - so the weight traffic, not the decode, was its ceiling. |
…ps (#67) PR #67's first twenty commits, rebased onto next-0.3.6.2 as one (their branch merged main twice; the moved MoE module is the only adaptation). Its commits: - nvfp4: the format's decoder, its row-invariant matmul, and the MoE tables - nvfp4: the engine's route for the checkpoint — BF16 non-experts, FP4 experts, the stacked tables checked on real d - nvfp4: the family admits modelopt checkpoints on CUDA (require_readable's refusals route) - nvfp4: the recipe's NVFP4 section — the format, the route, what the real checkpoint checks - nvfp4: the MTP layer's BF16 stacked experts ride the FP4 tables (the checkpoint excludes them from FP4) - nvfp4: the BF16 embedding as a plain B16 (the row lookup, not a matmul face) - nvfp4: the draft head from the bf16 lm_head requantized 4-bit (drafts change speed, never bits) - nvfp4: the whole expert stack decodes in one pass (e2m1_bits and row_scales stacked, load time at the 512-expert sca - nvfp4: the draft head quantized from the full bf16 lm_head, rows in token-id order (the sampler maps the subset as o - nvfp4: a tiny modelopt checkpoint builder and the loader's tests (the format, the header, the route's faces) - nvfp4: e4m3_bits exact on all 256 fp8 codes (the field form for normals, the value table for subnormals, the NaN cod - nvfp4: the family's check reads modelopt (NVFP4 group 16 refused otherwise), the Swift checkpoint listed in MODELS - nvfp4: the FP4 tables in the kernel's tile order (the K block contiguous, N tiles outer) and the decode gathering in - nvfp4: the MoE buffers at the engine's flat index (row * slots + slot, the qmm kernels' dest), count read as the pro - nvfp4: the b16 matmul reading whole BK blocks a slice (the split by the weight's shape, never the row count) and the - nvfp4: the loader's BF16 faces and the expert stack calling the helpers by their names (b16_from_rows, stack(proj)) - nvfp4: the tiny checkpoint shipping the n-gram constants the loader checks (I64 like the real one, and a table of th - nvfp4: the docs say what the engine reads (README's refusals and the Spark list, the runbook's) and what the real we - nvfp4: the CPU checks pin the NVFP4 route (the family's check on a ModelOpt config and its block size of 16, the Swi - nvfp4: the tiny fixture mirrors the published naming and the engine's widths
Adds a native read path for the NVFP4 (ModelOpt FP4) Flash Next checkpoint on CUDA, so
tensorfold serve ukisai/Swift-1.5-Qwen3.8-Flash-Next-NVFP4runs on the checkpoint as it ships, without aconversion step. Nothing here touches the MLX paths; the CUDA route picks it up on
cfg.quant == "modelopt".The format (
cuda/nvfp4.py)Packed E2M1 nibbles (
[N, K/2]uint8), fp8-e4m3 block scales ([N, K/16]) and a per-tensor scale; adequantized weight is
E2M1(code) * (fp32(e4m3) * 2**-7 * scale_2)per 16-value block. The stored grid keepsthe format's math off torch's fp8 casts (whose bf16 path yields zeros): the E2M1 codes ride as bf16 bit
patterns, the kernel widens them the way the reference does, one fp32 rounding per block product, blocks in
order, K slices summed in slice order — row-invariant, the same contract the 4-bit kernels keep.
The engine route
exclude_moduleskeeps every other linear BF16:hyper-connections, DeltaNet, attention, the indexer, the router, the shared expert, the PLE's key/value,
the embeddings,
lm_headand the MTP head's projections.cuda/bf16.pycarries those faces.cuda/nvfp4_moe.py) stacks gate and up rows per expert into one grid and calls upstream'stensorfold.cuda.experts.Plan; the MTP head's BF16 stacked experts ride the same tables.lm_headin token-id order, so drafting changes speed, never bits.HostTable) orthe published BF16 rows (
host_table.BF16Table, new).cuda/forward.pystages either into the PLEbuffers and
glue.ple_embed_bf16places the bf16 rows per head.model.language_model.*whilelm_headandmtp.*stay at the top level.Verification
tests/cudainnvcr.io/nvidia/pytorch:26.07-py3on a GB10 (sm_121): 460 passed, 70 skipped, 0 failed(baseline
main0.3.6.1 in the same container: 429 passed, 70 skipped).3ff05202, 186.4 GB): 16 routed experts bit-exactagainst the reference dequantization, FP4 matmul error 2.6e-3 / 2.3e-3, BF16 faces 2.9e-3, row invariance
from 1 to 64 rows, 512 MTP experts exact, the n-gram hashing constants equal value for value.
embedding-model-00006-of-00131.safetensors(BF16[2500012, 160], 800 MB) gathers rows bit-identical to an independent read of the file, 128 shards ofthat size make the 320,001,536-row table the digest derives, and the staging plus kernel place those values
exactly.
buffers bit for bit;
ple_embed_bf16places rows and sums groups at (2, 32) and (16, 160); and a forwardwith a live PLE layer over a bf16 table keeps the window contract — a window's logits equal serial steps' bits.
Not verified (stated, not implied)
embedding-*files, so ~102 GB of the n-gram table are not present locally. Load and kernels are checked per family
against the real shards instead.
131
embedding-*headers could not be swept). The loader checks each shard's header and raises on a mixedlayout, so a different layout fails loudly rather than loading wrongly.
Plan's item list host-side, so acaptured graph encodes one step's list. Worth a look before the FP4 route is used with graphs enabled.
Notes