Skip to content

hip: ModelOpt NVFP4 and FP8 checkpoints keep their codes and decode in flight - #2490

Merged
ashhart merged 14 commits into
ashhart:mainfrom
ElderOrb:hip-nvfp4
Dec 3, 2026
Merged

ashhart merged 14 commits into
ashhart:mainfrom
ElderOrb:hip-nvfp4

Conversation

@ElderOrb

@ElderOrb ElderOrb commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Serves NVIDIA's ModelOpt NVFP4 and FP8 checkpoints on the HIP engine without widening a weight.

What the checkpoint holds, and what the engine keeps

For a projection of N outputs from K inputs ModelOpt writes weight U8 e2m1 codes [N, K/2] (input 2i in the low nibble), weight_scale E4M3 [N, K/16] and weight_scale_2, one global scale. An FP8 layer writes E4M3 codes [N, K] and one f32 scale a projection.

The host keeps exactly those tensors, and the device keeps that layout too - as quant.mlx does - so an upload is a copy. The one transform is at read: an E4M3 group scale widens to BF16, exactly (three mantissa bits fit seven). A F32 block table is refused (ModelOpt writes E4M3, and the kernel reads a 16-bit table), and a stack of experts is refused because its experts carry a global scale each.

The preflight counts what the device holds rather than the stored files: table.deviceBytes keeps U8 and E4M3 code tensors as stored and counts only an E4M3 group table at two bytes a value.

On the current head (5b0c8b7) deviceBytes counts the MTP head exactly once, from the single source Files.mtpSource selects: a side shard set wins over an indexed head, and repeated names across side files are deduplicated as Table.open maps them. Checkpoint.mtp() retains that selected source object, so a combined indexed-plus-side checkpoint observes side precedence through m.owned, and a zero-declaration embedded head is found by presence in the main table. One classification rule (isMtpName) sends both mtp*.safetensors and model-mtp.safetensors to the side set in Files.list, Files.indexed and the side collector. Four regressions in mtp_source_test.zig cover the byte total, zero-declaration presence, indexed model-mtp.safetensors and source precedence; checkpoint_hf_test.zig is 588 lines after moving them out, and all changed files stay under the 600-line cap.

Kernels

quant/nvfp4_tiles.hpp serves a prompt through tf_nvfp4_gemm: a 64 x 64 tile stages a column chunk once and serves 64 rows, a thread a 4 x 4 block of output elements (acc[4][4], ty = tid & 15, tx = tid >> 4, 256 threads), a group's 16 inputs folded in f32 with the group's own E4M3 scale, the one global applied to the sum once, the nibble through an e2m1 bit table.

A decode round takes tf_nvfp4_col1 .. tf_nvfp4_col4 instead (launches/nvfp4.zig:78, chosen at a.m <= 4 with @rem(a.k, 64) == 0, grid ceil(n / 256)): a thread a column and ROWS (1..4) of that column, summed in the same per-group order, reading codes and scales straight through registers (hold[2][8], no LDS at all), so a decode row's bits are the tile's bits and the row's work is not padded out to sixteen rows. tf_nvfp4_small remains the 16-row LDS block for a round wider than four rows.

quant/fp8_tiles.hpp is its sibling for FP8, tf_fp8_gemm: each E4M3 code turns into the exact f32 it names, all of K sums in f32, and the projection's one scale multiplies the result once, as CUDA's qmmf.cu reduce does. A short row keeps each chunk's partial in f32 and adds it once, so a row that crosses a chunk carries the rounding the 64-row tile does and the result stays row-invariant.

Both serve bf16 activations only, since the engine refuses an fp16 build for a ModelOpt checkpoint; one kernel serves a prompt's rows and a round's, so a row's bits never depend on its round.

Why dedicated kernels rather than the shared GEMM and stream tiles: both step along K in 32-code chunks (kGemmK = 32, nch = a.k >> 5, a chunk's scale index q >> gshift), and NVFP4's group is 16, so a chunk holds two scales: a.group / kGemmK is 0 and the shift would have to be negative. tiles/stream.hpp and tiles/dot2_tiles.hip keep only their MLX code.

The engine

A ModelOpt checkpoint's own bf16 layers (an lm_head, an unquantized linear, the MTP head) read as .dense on the row-invariant dense kernels rather than through rocBLAS, so the engine keeps main's e.plain() gate and opens no rocBLAS for them. The vision tower never calls rocBLAS either (no blas reference in zig/src/vision/qwen_hip.zig), so the engine carries no tower field.

A ModelOpt checkpoint carries its own refusals: an fp16 build and more than one rank are refused by name, and graphs stay off. A ModelOpt checkpoint with routed experts is refused by name too, before its shards are read. A refusal names the tensor and the reason through core's Why buffer.

The format tag

core.quant.Format no longer names NVFP4 or FP8: it and Decoder are the three formats both engines read. A projection still has to carry them, so quant.Projection gains optional nvfp4 and fp8 fields beside a nullable handle, and format()/decoder() return optionals. The family's host projection is its own union, with rows, bytes, read, halves, sliceRows and sliceCols over it; its device projection is a union of quant.Device, quant.nvfp4.Device and its FP8 tensors.

Kernel contract

hip_records_nvfp4.zig holds every entry point's resources from hip-kernel-contract-limits, in gfx1030, gfx1100, gfx1151, gfx1201 order (VGPRs / SGPRs / LDS bytes):

  • tf_nvfp4_gemm: 138/38/16384, 144/38/16384, 144/38/16384, 143/36/16384.
  • tf_fp8_gemm: 58/49/18432, 56/49/18432, 56/49/18432, 58/48/18432.
  • tf_nvfp4_col1: 130/22/0, 138/22/0, 138/22/0, 138/23/0.
  • tf_nvfp4_col2: 164/26/0, 165/26/0, 165/26/0, 164/28/0.
  • tf_nvfp4_col3: 148/31/0, 145/30/0, 145/30/0, 147/34/0.
  • tf_nvfp4_col4: 121/32/0, 141/32/0, 141/32/0, 144/38/0.

Bound 256, wave32, no scratch, and every ModelOpt line reads "record current" on all four chips when the contract is taken with the toolchain the records were made on. The tile stages a column chunk in LDS, which is why the product kernels moved from the pre-tile numbers (NVFP4 11264, FP8 12288); the col entry points carry no LDS because a column's codes and scales stay in registers.

Re-run to confirm, on this head: zig build hip-kernel-contract-limits -Dhip=true -Dhipcc=<hipcc> compiles the contract for gfx1030, gfx1100, gfx1151 and gfx1201 and audits every chip's records. 77 of 79 build steps complete; the audit's run step then exits 1 on the inherited failures below.

I re-ran it here, and the result depends on which compiler takes the contract, so it is worth stating exactly:

  • With the toolchain the records were made on - HIP version: 7.2.26024-f6f897bd3d, AMD clang version 22.0.0git - all six ModelOpt lines read "record current" on all four chips, as the records above were written that way.
  • With the newer toolchain on my own machine - HIP version: 7.16.26385-7da43026e4, AMD clang version 24.0.0git - all six read "record" against different numbers: tf_nvfp4_gemm 118/33 on gfx1030, 111/33, 111/34, 111/32, where the records hold 138/38, 144/38, 144/38, 143/36. FP8 reads 56/53 on every chip against a recorded 58/49, 56/49, 56/49, 58/48. A newer clang allocates registers differently; the kernel source is unchanged between the two runs.

So the records are current for the compiler they name, and a future toolchain bump will move them. That is why every record carries the compiler in the body above rather than only the numbers.

  • The audit's inherited mismatches are 847, byte-identical on the base commit and on this head. I ran hip-kernel-contract-limits on b7298b4ea and on e57bc1132 with the same toolchain, and every one of the 847 FAIL lines appears in both, all in kernels this PR does not touch (RMS norm, mamba, and their neighbours); per chip the counts are 207 / 212 / 212 / 216 on both sides, and Compare-Object over the sorted FAIL lines reports no difference either way. The PR's only effect on the audit is the 24 new ModelOpt lines, and all 24 pass. (An earlier revision of this body said 540; that was the same audit under a clang 24 toolchain, where the inherited count moves - the base-against-head run above, on the toolchain the records name, is the one that shows what this PR changes.)
  • The audit pulls in lighton_ocr.hip:182, which refuses M_SQRT1_2 on this toolchain. That file is byte-identical to main and is not touched by this PR. A local shim for that one constant (0.70710678f, the same float as M_SQRT1_2) lets the build reach 77/79, which is where the numbers above were read; the shim is not part of this PR.

The same run compiles every group for the four chips, which is the gfx1100 and gfx1201 build. tests/hip/contract_nvfp4.zig carries a test type for both and the runner builds it; on gfx1151 (Radeon 8060S):

PASS nonfinite hip ModelOpt NVFP4 product: 256 non-finite and 1024 finite outputs match the float64 classes
PASS repeat hip ModelOpt NVFP4 product: five runs byte-identical (1024 bytes), inputs and guards untouched, no overlap
PASS shapes hip ModelOpt NVFP4 product: 4 shapes within the float64 bound (worst 0.001 of the bound), 0 edges refused
PASS sums hip ModelOpt NVFP4 product: exact sums at k 4096, where fp16 sums would miss by 847512x and bf16 by 4765421x
PASS nonfinite hip ModelOpt FP8 product: 256 non-finite and 1024 finite outputs match the float64 classes
PASS repeat hip ModelOpt FP8 product: five runs byte-identical (1024 bytes), inputs and guards untouched, no overlap
PASS shapes hip ModelOpt FP8 product: 4 shapes within the float64 bound (worst 0.001 of the bound), 0 edges refused by
PASS sums hip ModelOpt FP8 product: exact sums at k 4096, where fp16 sums would miss by 442122x and bf16 by 4889576x
PASS limits live ModelOpt NVFP4 product: 256 threads launched, the runtime allows 256; 144 VGPRs, 16384 + 0 LDS bytes
PASS limits live ModelOpt FP8 product: 256 threads launched, the runtime allows 256; 56 VGPRs, 18432 + 0 LDS bytes
SUMMARY gfx1151 164 kernels: 164 pass gates 1-4, 0 fail, 2 known findings; 43 controls: 43 red as planted, 0 missed

All ten ModelOpt lines pass on the current head. The two known findings are the bf16 prompt tiles' NaN classes, which predate this branch. The run's 189 other limits live lines are other kernels' recorded resources against this host's hipcc (a different ROCm version from the one that recorded them); none of them is a ModelOpt launch, and none is touched here.

Testing

  • zig build -Dhip=true test on gfx1151, this head on b7298b4ea: 769/772 steps, 10344/10594 tests (247 skipped, 3 failed). main at b7298b4ea, same command on the same host: 769/772 steps, 10322/10572 tests (247 skipped, 3 failed), so the branch adds 22 tests and skips none. The three failures are the same three on both trees, and neither file is touched here: flashnext/hip/tables.zig's two pool tests (lines 483 and 517) cannot pass off Linux, because host_pages.zig:109 returns cold() == false unconditionally when builtin.os.tag != .linux, so the pool is never woken; and families/nemotron/hip/embedding.zig:106 cannot map its temporary table on Windows, std.Io.Threaded returning AccessDenied from the page-file mapping. Both files are byte-identical to the base commit. An earlier run of this command reported 3977/4100 tests because that build carried no CUDA suites; with the CUDA toolchain on the path the same tree builds them too.
  • After the last rebase the head is 8a8bec665 on ce0264367; the one conflict was native.zig's served(...), where main now passes the drafter (served(e, d, streams, capacity, readouts)) so admission counts its scratch: that call is kept as main has it, with this branch's ModelOpt format names on top. The rebase also brings in aec48047e/17a554e16, which fix the walk-away race this branch's last CI run hit in request_admission_http_test.zig:503 (a file this branch does not touch); on that run zig-b was green and zig-windows/zig-macos-dev-tools were cancelled behind the one failing host step. On that base I re-ran the host targets (test-qwen35, test-qwen35-hip-host, test-native-hip-host, check-native-hip-host, all with -Dhip=true -Dfixed-cpu), zig fmt --check on the changed files, and the lean check above: all pass. The device numbers above (tests, contract limits, hip-kernel-test) are the ones measured at e57bc1132 on b7298b4ea; the card is serving another model right now, so I did not displace it for a re-measure.
  • tools/zig/lean_check.py reads 165 problems on this head and 165 on main at ce0264367, the same set: Compare-Object over the sorted lines reports no difference, so the branch adds none. The 600-line rule bites on the rebased base: engine.zig reached 602 lines and native.zig 617, so the lean step reported two problems the base lacks and the zig job failed before any test ran. Both are split now - the layer-cancel poll to prompt_poll.zig and the four config-only refusals to native_refusals.zig, with no behavior change - leaving engine.zig at 597 and native.zig at 582, and the lean step reports 0 new problems. The poll split also carries the base's edge-event handoff: one layer stays queued while the previous one's edge is awaited, and a cancel still drains before error.Cancelled. The shared handle's optionality moved one line, prompt_tail.zig:63, to p.format() == .dense.
  • Kernel tests compare both products with quant.nvfp4.reference and quant.fp8.e4m3 in f64 against the bound each kernel's chain derives, print the worst error, and check a row against the format reference alone at one, three and five rows. hip/kernel_tests/fp8.zig:119 and nvfp4.zig:150 then compare one row with the same row inside a round of seventeen at K = 192, so the round crosses the sixteen-row threshold and the two sides take different paths; the row's outputs must be equal bit for bit, which is what pins the short path's per-chunk sum to the tile's.
  • Host tests cover the reader (unfit, the exact widen, halves and slices), the preflight count, the FP8 and F32 refusals, the ModelOpt MoE refusal, that a ModelOpt checkpoint's dense layers land on .dense through a real Checkpoint.open, that an E4M3 NaN code is refused by name, and that a ModelOpt checkpoint offers its NVFP4 formats to qwen3_5 alone.

Served: the checkpoint loads and answers

nvidia/Qwen3.8-27B-NVFP4 at revision 482ca0f3 (19 files, 20.44 GB, the three shards checked against their LFS oids) serves through zig build native-hip on gfx1151 (Radeon 8060S), zig 0.17.0, TheRock's ROCm SDK with HIP version: 7.2.26024-f6f897bd3d and AMD clang version 22.0.0git (target x86_64-pc-windows-msvc):

[tensorfold] HIP gfx1151 device 0, rank 0 of 1: model 20.63 GiB; 1 stream at once, 0.65 GiB each at a 8192-token window
[tensorfold] serving qwen38-nvfp4 at http://127.0.0.1:8124/v1 (context: 8192; loaded in 259.3s)

A greedy request answers correctly and repeats bit for bit across runs (the same token_sha256 twice). The MIXED_PRECISION header gives the loader no trouble: format is read from the tensors, weight_scale_2 for NVFP4 and weight_scale for FP8, and the checkpoint's 208 FP8 and 193 NVFP4 layers both load.

Decode is 2.0 tok/s and TTFT 4.75 s at 8192 context, one stream at a time, drafting on. That is 20.63 GiB of weights read per token at 2.0 tok/s, about 44 GB/s.

The card's ceiling, measured by a pure read_only pass over 2 GiB and confirmed by hipInfo (512-bit bus, 800 MHz memory clock): 240 GB/s. A 5120 x 5120 NVFP4 layer's 16.38 MB of codes fit in the 32 MB MALL, where the same read runs at 732 GB/s.

So decode reaches about 18% of the floor. The prompt path is a 64 x 64 tile and was timed directly at that shape:

rows time GB/s of weights vs the floor
16 (a round) 1.32 ms 12.4 5.2%
64 (a prompt tile) 1.47 ms 11.1 4.6%

Rows = 1 is not in that table because decode does not take the tile: it takes tf_nvfp4_col1 (see Kernels). Those kernels were not timed in isolation - the SDK has no rocprof/omniperf - so their rate is only observable end to end, which is the 44 GB/s above. The two are not comparable directly: the tile's 22.7 GB/s at m = 1 is a path decode no longer runs, and the ~2x it would suggest cannot be separated from the x86 harness in this SDK. What is measurable is that decode reaches 18% of the card while the prompt tile reaches 5%.

Two candidates I measured on the tile and ruled out:

  • The 16-way LDS bank conflict in xs[16][64] (sixteen threads share a row): padding the stride to 68 changes nothing but 1.09x, outputs bit-identical.
  • kE2m1Bf16 declared __device__ rather than __constant__: moving it to constant memory is 1.00x - the cache already absorbs it. Unrolling the 16-deep accumulator chain into four gives 1.13x, also bit-identical.

Together those explain 1.23x of the tile's gap. The rest is launch geometry: a 64 x 64 tile at m = 1 would be 80 blocks of 256 threads on a card that holds 40,960 threads, with nvfp4_small spreading its threads over all sixteen rows of xs while writing only row < a.m - fifteen sixteenths of the work discarded. That is exactly what tf_nvfp4_col1 stops doing: its grid is ceil(n / 256), a thread owns a column, and no row is padded out to sixteen.

This is a kernel-optimization gap, not a correctness one - every contract gate and the 17-row tests pass, and the bit-for-bit determinism holds. I would rather report this honestly and improve the decode path further in a follow-up than tune it inside this PR, whose subject is that these checkpoints serve as stored.

Memory: a separate patch, and what the numbers mean

The working-set arm is not in this branch. The numbers below were taken with a small local patch applied on top of this head. That patch is now its own pull request, #3866: it touches core/checkpoint*, the loader every family and every backend shares, so it does not belong in a PR about the NVFP4 format. Nothing in this branch's diff changes loading memory; without the patch this branch behaves exactly as main does.

The finding, so the second PR has a record: on Windows the reader had no way to drop a step's shard pages. safetensors.zig:265 gates release on builtin.os.tag != .linux, and checkpoint_drop.zig, checkpoint_file_cache.zig and shard.zig's madvise are Linux-only too, so model.zig:66's "no ck.release() between layers" held for a reason that did not apply. The pages stayed in the process's working set, which is what made a load look like it needed far more memory than it does.

The patch adds platform/working_set.zig (reached as sys.working_set, beside the other Win32 declarations) as the Windows arm, called from Checkpoint.release/releaseExcept and from qwen3_5/weights/checkpoint.zig's release after a layer's files are walked: one SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1) per step, not per tensor, since Windows has no per-range advice. It removes pages from the working set and leaves them on the standby list, so a later read is a soft fault, not disk.

Measured on the card with that patch compiled in (2 s sampling, gfx1151, the 8192-token server, external trimmer off so only the build's own release acts):

peak working set lowest free RAM standby load
main (no trim arm on Windows) 18.47 GB at 127.8 s 1.52 GB of 31.65 19.94 GB 259.3 s
this head + the patch 1.92 GB at 7.1 s, then 0.03-0.23 GB 12.47 GB 14.73 GB 259.8 s

The private bytes do not move (peak 0.76 GB either way), so the 18.47 GB was mapped shard pages, not the process's own allocations. The standby list holds the pages the trim dropped instead of the working set holding them, so a later read is a soft fault: the load takes 259.8 s against 259.3 s, within noise.

At --parallel 8 --context 32768 the same arm holds: peak working set 2.86 GB, lowest free RAM 14.06 GB, standby growing to 16.56 GB as the shards are read once and kept. No disk read repeats.

A 27B checkpoint now loads on a 32 GiB Windows side.

Concurrency and drafting, measured

All rows below are the same greedy prompt, the same 64 max_tokens, temperature: 0, --context 8192, --snapshot-dir none, so every reply is directly comparable and every row's token_sha256 is the same hash.

At --parallel 2:

wall tok/s reply sha
solo, 2 runs 36.11 / 36.00 s 2.0 each e02735d4c9b7
2 concurrent, both at once 49.93 / 49.89 s 1.4 / 1.6 each, 2.6 aggregate e02735d4c9b7
"draft": false, 2 runs 86.44 / 86.59 s 0.8 each e02735d4c9b7
drafting on, 3 runs 36.02 / 36.02 s 2.0 each e02735d4c9b7

Three things this settles:

  • Drafting is 2.4x. 36.02 s against 86.44 s for the same 64 tokens, and the log agrees: accepted=41/67 rounds=23 against accepted=0/0 rounds=63.
  • Drafting does not change the answer. The "draft": false reply and the drafted reply hash identically, which is the contract tokens.zig:124 states ("drafted and "draft": false replies must match"). The format's row-invariance is what makes that hold.
  • Two streams do not double. Each drops to 1.28 tok/s from 1.78 solo (0.72x its own rate) while the pair together reaches 2.57 tok/s, 1.44x solo. So the second stream buys about half a stream, not a second one - the same shape as eight, less severe.

At --parallel 8 --context 32768, the same shape:

tokens wall tok/s reply sha
solo, 3 runs 128 66.02 / 65.88 / 66.00 s 2.1 each bf993d6b8399 each
8 concurrent 64 each 150.65-151.09 s 0.4-0.6 each, 3.4 aggregate e02735d4c9b7 each

Every concurrent reply is bit-identical, so the format and the row-invariant products hold under a shared round. What does not hold is throughput: eight streams reach 3.4 tok/s together, 1.6x a single stream rather than 8x, and each stream's TTFT degrades from 4.75 s to 9.5-37.6 s as the eight prefills queue behind each other (the log's queued= field lands at 4.3-4.7 s a request). Drafting collapses under the load too: accepted=83/131 solo against accepted=5/12 concurrent.

Prompt cache, measured

--prompt-cache-gib 4, --parallel 1, a 3162-token prompt, 16 tokens out, same prompt three times:

TTFT decode wall cached tokens sha
cold 230.6 s 8.20 s 239.0 s 0 d6fb55f2cf55
resumed 4.76 s 8.11 s 12.87 s 3136 of 3162 d6fb55f2cf55
resumed 4.74 s 8.12 s 12.87 s 3136 of 3162 d6fb55f2cf55

Prefill drops 48x and decode does not move (1.8 tok/s either way), which is the expected split: the cache restores the prompt's rows, not the round. The reply's bits are identical cold and resumed, so a restored prefix gives the same answer as one read from the start.

That is the same memory floor as the single-stream section: at 2.0 tok/s the card reads about 44 GB/s of the 240 GB/s it can sustain, so several streams have headroom to share and still only add up to 1.6x. A decode path that reached even a third of the floor would make these tables look very different, which is why the follow-up is the kernels and not this PR.

Not measured: one MLX checkpoint's reply on main against this branch. It cannot be measured for a ModelOpt checkpoint, since main refuses the format by name and never loads it - which is the point of the PR.

@ashhart

ashhart commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Thanks, @ElderOrb. Serving ModelOpt NVFP4 and FP8 Qwen3.5 checkpoints on HIP through the BF16 rocBLAS path is in scope. A few things first:

  1. The served weights aren't the checkpoint's. weights/modelopt.zig:73 and :90 round each dequantized weight to BF16. Code × E4M3 block scale fits BF16 exactly, and so does a bare E4M3 value. The FP32 global and per-tensor scales don't, and the product is rounded twice (f64, then f32, then BF16). We take no lossy weight formats (docs/pr/SKILL.md:74). Please widen only the exact part and apply those scales to the f32 sum, as CUDA does (qmmf.cu:89), or refuse any tensor BF16 would round.
  2. The memory preflight: engine.zig:71 counts stored bytes, but the device holds 2 bytes a weight, about 3.5× NVFP4's stored size. Please count the widened size, so WeightsDoNotFit still refuses a checkpoint that doesn't fit.
  3. Admission: please go through core/modelopt.zig, so unsupported recipes, E4M3 NaN scales and a zero, Inf or NaN global are refused by name. Please also refuse qwen3_5_moe ModelOpt experts, which still load through experts.routed unwidened, or say how they load.
  4. Tests: the one test's values are all powers of two, so nothing rounds. Please add tests against core/quant/nvfp4.zig's f64 reference, with FP8, values that would round, and a zero global, and show them failing before the change.
  5. hip/memory.zig:84 puts every HIP upload, for every family, in 64 MiB windows. Please split that into its own PR, or explain why it belongs here.
  6. A CHANGELOG line ending "(hip: ModelOpt NVFP4 and FP8 checkpoints keep their codes and decode in flight #2490). Thanks to @ElderOrb.", and a rebase: hip/engine/mtp.zig, hip/engine/native.zig and weights/projection.zig conflict with main.

We have no AMD GPU, so please post your own main-against-branch numbers, naming the gfx target, along with drafted replies equal to "draft": false.

@ElderOrb
ElderOrb force-pushed the hip-nvfp4 branch 4 times, most recently from 54ade02 to 5b32fc7 Compare November 8, 2026 23:34
@ElderOrb ElderOrb changed the title hip: serve ModelOpt NVFP4 and FP8 checkpoints as BF16 (Windows + ROCm) hip: ModelOpt NVFP4 checkpoints keep their codes and decode on the tiles Nov 8, 2026
@ElderOrb
ElderOrb force-pushed the hip-nvfp4 branch 3 times, most recently from 655c707 to bba2f2b Compare November 8, 2026 23:56
@ashhart

ashhart commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@ElderOrb thanks, keeping the codes as stored is a much better design: the NVFP4 weights are now the checkpoint's, the E4M3 → BF16 table is exact, the NaN and zero-global refusals are in, and admission goes through core/modelopt.zig. On the format tag: please use the HIP-local type you offered, so core keeps no Format tag. What's left:

  1. FP8 still rounds: weights/modelopt.zig:60 rounds e4m3 × scale to BF16, twice. Widen the bare E4M3 (exact) and apply the scale to the f32 output, or refuse FP8 layers. Please also refuse per-row and zero FP8 scales (:51-55).
  2. F32 block scales: read keeps them F32 (core/quant/nvfp4.zig:70,98), but the stream tile reads every table entry as BF16 (nvfp4_decoder.hpp:180-183). Please refuse F32 block scales, since ModelOpt writes E4M3.
  3. Row invariance: ops/project.zig:431 sends decode rounds over 16 rows to the GEMM, so a row's bits depend on the round's size. Please choose by o.prefill alone, as the MLX path does, with a test of 17 rows against one.
  4. rocBLAS: these checkpoints now serve chat, but their BF16 linears (widened FP8 layers, the MTP head, an unquantized lm_head) run on rocBLAS, whose products vary with rows (engine.zig:195). Please post concurrent = solo and drafted = "draft": false on your gfx target, or route those layers through the row-invariant kernels.
  5. Kernel contract: please register tf_nvfp4_gemm and the 8 stream entry points with hip_records, and post hip-kernel-contract on your chip and -limits for every served target. That also re-checks the MLX stream tile after the stream.hpp edit.
  6. Other targets: nvfp4_wmma_gemm (nvfp4_tiles.hpp:32) compiles on every target. Please guard it as TF_MATRIX does (or drop the unused wrappers), and confirm gfx1100 and gfx1201 build.
  7. Preflight: please count FP8 layers at 2 bytes a weight and the scale table at 2 bytes a group (engine.zig:69-75).
  8. Tests: please add a non-power-of-two global, an FP8 case and the qwen3_5_moe refusal, show them failing before the fix, and say whether the kernel tests ran on the card.
  9. Housekeeping: one-line comments (core/quant/nvfp4.zig:1-5, launches/nvfp4.zig:1-4, the .hpp headers); the stale doc at config.zig:43; route by recipes or drop the field; drop the docs' RDNA2 claim (engine.zig refuses fp16); drop the windows commit (landed as hip: upload large tensors in windows so the blit can pin them #2584); end the CHANGELOG line "(hip: ModelOpt NVFP4 and FP8 checkpoints keep their codes and decode in flight #2490). Thanks to @ElderOrb."

We have no AMD GPU, so please post main-against-branch numbers, naming the gfx target.

@ElderOrb

ElderOrb commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and reworked since your note; the body above describes the current state. Summary of what changed:

  • The shared tiles are gone from this path. Both step along K in 32-code chunks (kGemmK = 32, nch = a.k >> 5, a chunk's scale index q >> gshift), and NVFP4's group is 16, so a chunk holds two scales: a.group / kGemmK is 0 and the shift would have to be negative. quant/nvfp4_tiles.hpp is now one product kernel, tf_nvfp4_gemm plus tf_nvfp4_gemm_f16; tiles/stream.hpp and tiles/dot2_tiles.hip keep only their MLX code, so the MLX stream tile needs no re-check from this change.
  • Row invariance by construction: one kernel for every row count, so ops/project.zig no longer picks by m and a row's bits cannot depend on its round.
  • Preflight: table.deviceBytes counts what the device holds (U8 codes as stored, an E4M3 tensor at 2 bytes a value) instead of the stored files, with a host test.
  • F32 block scales are refused (unfit), and the reader no longer keeps one; the kernel reads a 16-bit table only.
  • recipes field dropped; it was admitted and then unused. The stale note at weights/config.zig is corrected and the module and header comments are one line each.
  • Evidence on the card: zig build hip-kernel-test -Dhip-arch=gfx1151 on a 8060S is 19/19, with two NVFP4 kernel tests: the product at one row, three and five against quant.nvfp4.reference (2e-4), and a row's bits alone against a round of four (bit for bit). zig build test on Windows passes.

Still open, and in the body: the Format tag in core (needs the family-local projection type on both host and device sides), hip_records registration plus hip-kernel-contract/-limits, and FP8 exactness. On FP8 I would rather not pick for you: the scaled f32 product CUDA uses (qmmf.cu) is the exact one, and refusing FP8 layers refuses mixed checkpoints outright. Which do you want?

@ashhart

ashhart commented Nov 10, 2026

Copy link
Copy Markdown
Owner

Thanks @ElderOrb, this is a much better shape. The codes and E4M3 tables stay as stored, one product kernel serves
every row count, F32 block tables are refused, the preflight counts what the device holds, the recipes field and the
windows commit are gone, and the kernel tests ran on your 8060S. Thanks too for the clear account of why the shared
tiles can't take a group of 16.

On your FP8 question: the exact route, please. Widen the bare E4M3 values (exact in BF16), sum in f32, and apply the
per-tensor scale once to the f32 result, as CUDA's reduce does (zig/kernels/cuda/qmmf.cu:92). A sibling of your
NVFP4 kernel that decodes E4M3 in flight would do that, and it would also keep those layers row-invariant and off
rocBLAS. If that makes this PR too big, refuse FP8 layers by name here and bring the FP8 product as its own PR.

What's left, smallest first:

  1. Docs and comments.
    • docs/quantization.md:140 still says FP16 where a card has no BF16 dot2. But engine.zig:208-212 refuses fp16 for
      this path, so tf_nvfp4_gemm_f16 can't run either.
    • docs/quantization.md:142 and the CHANGELOG line say "a quarter of the bytes". Codes plus a BF16 scale per 16
      come to 5 bits a weight on the device, about 31 %.
    • Some comments still describe the old version: hip/ops/project.zig:410 ("the dot2 tiles"),
      hip/kernel_tests/nvfp4.zig:1 and weights/checkpoint.zig:60 ("dequantizes"). There's also a dead branch at
      weights/modelopt.zig:59.
  2. One rounding for the global. quant/nvfp4_tiles.hpp:51 multiplies each group scale by the global, which is a
    rounding per group. Each E4M3 scale is exact in f32, so fold each group with its own scale and apply the global
    once to the sum.
  3. The kernel test's bound. 2e-4 (kernel_tests/nvfp4.zig:104) is far looser than an f32 sum needs at K ≤ 128.
    Please use the derived bound the dense test uses (kernel_tests/dense.zig:35-41) and log the worst error.
  4. Tests still owed from last round. A non-power-of-two global (every global in the tests is 0.25, 0.5, 1 or 2),
    an FP8 case, and qwen3_5_moe ModelOpt experts refused by name with a host test. Please show each one failing
    before its fix.
  5. The BF16 layers on rocBLAS. A text-only ModelOpt checkpoint isn't chatBf16 (engine.zig:80-84), so its BF16
    lm_head and widened layers take rocBLAS (project.zig:52-61), whose products vary with the round's rows. Please
    route them through the row-invariant dense kernels, as the chat path does, or show drafted equal to "draft": false
    and concurrent equal to solo on the card. The MTP head on rocBLAS is fine, since its drafts are verified.
  6. The Format tag out of core (core/quant/types.zig:10), as you offered.
  7. Kernel contract. Please register tf_nvfp4_gemm in hip_records, post hip-kernel-contract on gfx1151 and
    -limits for the served chips, and confirm that gfx1100 and gfx1201 build.
  8. Served numbers on your card, naming the gfx target: decode and prompt tok/s, drafted equal to "draft": false,
    concurrent equal to solo, and resumed equal to fresh.

We have no AMD GPU, so your numbers are the receipt for this one. Main is closed for a release right now, but none of
this needs to wait for that.

@ElderOrb
ElderOrb force-pushed the hip-nvfp4 branch 3 times, most recently from cb32ea6 to 6b1b659 Compare November 10, 2026 15:38
ashhart added a commit to ElderOrb/TensorFold that referenced this pull request Dec 3, 2026
The loader kept its own presence test for a side or model-shard head
(mtp.norm_e.weight or mtp.pre_fc_norm_embedding.weight), while
Files.mtpSource took any `mtp.` key. The two disagreed on malformed
layouts:

- a side file with `mtp.` tensors but neither norm loaded as "no head",
  while preflight counted its bytes;
- a stray `mtp.` tensor in the model shards made the main table the
  source, and the loader then failed on a missing norm where main returns
  null.

mtpSource now selects a shard set by those first norms (isMtpNorm, the
names readMtp reads for every head it accepts): the side files first,
then the model shards, unprefixed (the main table) before
`language_model.`. A set holding `mtp.` tensors but neither norm is
refused with error.MtpHeadWithoutNorm and one message naming the file and
both norms. Checkpoint.open, deviceBytesAt and textBytes all call it, so
the loader and preflight refuse together. The loader's side check calls
the same names (Table.hasMtpNorm).

Well-formed checkpoints keep their source and totals: every layout in
mtp_source_test.zig is unchanged, and a head readMtp can read always holds
one of the two norms.

Tests: a side file of mtp tensors without a norm, and a stray mtp tensor
in the model shards, are each refused by Checkpoint.open, the preflight
source and the byte counters; both fail on ashhart#2490's head.
ashhart added a commit to ElderOrb/TensorFold that referenced this pull request Dec 3, 2026
…rt#2490's core projection

Main's hip_prompt_test.zig (8c14c27) sets e.weights.embed to .{ .mlx = undefined } and .{ .bf16 = undefined },
written while a Projection was quant.Device itself; ashhart#2490 makes it a union whose core arm holds that Device beside
nvfp4 and fp8, so those four lines now say .{ .core = .{ .mlx = undefined } } and .{ .core = .{ .bf16 = undefined } }.
Engine.plain reads the format through .core, so each test checks what it did on main.
@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

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

Adds ModelOpt NVFP4 and FP8 checkpoint support to the HIP engine with new in-flight-decode GEMM/decode kernels, host readers, uploader/bridge plumbing, and MTP source accounting tests. The docs claim memory-traffic and byte-footprint wins, so a benchmark receipt is required.

  • 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/src/families/qwen3_5/backend/hip/model/bridge.zig: The FP8 bridge view derives n and k from d.weight dims but never validates that the scale buffer is finite/nonzero or that k is a multiple of anything the kernel needs; a malformed checkpoint that passed the host reader is fine, but any path that builds a view from a non-ModelOpt fp8 Device (e.g. a stack) would silently produce a wrong product since coreView only guards nvfp4/fp8 tags, not rank of scale. Suggested fix: Validate scale numel == 1 and weight rank == 2 in the fp8 branch (and reject k % 1 != 0 is trivially fine, but assert scale ptr alignment) before constructing the view, mirroring the host reader's refusals.
  • [BLOCKER] zig/src/families/qwen3_5/weights/modelopt.zig: This O(N*K) host scan over every FP8 weight byte runs on the load path for every projection and will dominate load time on large checkpoints, and it also rejects 0x7f/0xff which are NaN but the kernel would propagate anyway; more importantly it scans w.bytes which for a sharded/sliced tensor may be a view with offset, so the scan is correct only if bytes is the full tensor. Suggested fix: Drop the full scan (or gate it behind a debug flag); NaN codes in weights are not a correctness hazard for a sum-with-scale kernel and the per-byte host pass is a load-time regression.
  • [WARNING] zig/src/core/quant/quant.zig: Making handle optional and adding parallel nvfp4/fp8 fields means every existing switch on p.handle or p.format() across the codebase must now tolerate null; prompt_tail.zig was updated (p.format() == .dense) but any other call site that pattern-matches the tag without an orelse will fail to compile or, worse, silently take a default branch. Suggested fix: Grep for all p.format()/p.handle consumers and confirm each handles the null (ModelOpt) case explicitly; add a compile-time exhaustive switch test.
  • [WARNING] zig/src/families/qwen3_5/backend/hip/engine/mtp.zig: try if (...) expr; evaluates the expression and discards the error union via try, but the if has no else branch so when the condition is false the statement yields void, not an error — this is valid Zig but reads as if the try applies to the condition; if tokenProb can fail, the error propagates only when the condition holds, which is intended, yet the form is fragile and easy to misread as swallowing errors. Suggested fix: Rewrite as if (cut and n + 1 < most) try o.tokenProb(...); for clarity.
  • [WARNING] zig/src/families/qwen3_5/weights/projection.zig: This branch runs before the modelopt.algo check only when algo() returned null, meaning a ModelOpt bf16 checkpoint's non-quantized (ignored) layers read dense — correct — but the vision tower exclusion is a bare string prefix match on two spellings; a key like "model.visual_foo." or a differently-named tower would silently take the dense path and change numerics. Suggested fix: Match on the config's vision module names or a shared predicate rather than two hardcoded prefixes.
  • Synthena

@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

READY to land on this head. HIP path, with shared loader code: our GB10 A/B of this head against its base on CUDA has tokens equal in every cell and speed unchanged, so the CUDA path is unaffected. We have no HIP device; the HIP results (ModelOpt NVFP4 and FP8 codes kept and decoded in flight, exact against the HIP baseline) rest on the author's receipts.

  • Synthena

@ashhart ashhart added synthena:ready Reviewed by Synthena and ready for group train and removed synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 3, 2026
ElderOrb and others added 14 commits December 3, 2026 13:42
A ModelOpt checkpoint writes NVFP4 as E2M1 codes with a 16-element-block
scale and one global scale, and FP8 as E4M3 codes with one scale, neither
of which the shared formats name. This reads both as they are stored and
decodes them on the device, so a converted checkpoint serves without being
re-quantized to MLX's layout.

NVFP4 keeps its E2M1 code through the BF16 dot2 product, which is exact
for the format's levels; FP8 decodes in flight and is exact in f32. Both
run through one 64 x 64 tile that stages a column chunk once and serves 64
rows, with a 16-row block for a decode round summing as the tile does.

The host projection is the family's own union of the shared formats,
`quant.nvfp4.Host` and a stored FP8, so core's format vocabulary keeps the
three formats both engines read. A routed expert stack stays core's: a
global scale an expert, so NVFP4 stacks are refused. A ModelOpt
checkpoint's bf16 layers read dense.

Scale handling carries the review's asks: FP8 scales ModelOpt does not
write are refused, as is a weight holding an E4M3 NaN code, and each
refusal names the tensor and the reason through core's `Why` buffer rather
than an uninitialised name.

A decode round on the product ran the 16-row block, which distributes its
threads over all sixteen rows while writing only a.m of them, so fifteen
sixteenths of the work is discarded at m = 1. The same header gains four
entry points, tf_nvfp4_col1 to tf_nvfp4_col4, over one
nvfp4_columns<ROWS, DEPTH>: a thread owns one output column, reads that
column's whole K span, and holds ROWS accumulators. The launch picks the
entry point whose ROWS matches a.m exactly, so no row is padded and a
row's offset stays constant.

They are separate entry points rather than a branch on a.m because the
contract records resources an entry point, and a branch would make every
variant carry the widest one's registers.

nvfp4_columns prefetches DEPTH chunks into registers and fetches the next
before the group loop consumes the held one. On gfx1151 at a 5120 x 5120
layer, m = 1: 0.0969 ms against 0.2516 ms reading each chunk in place,
2.6x, and 0.0580 ms for the prefetched form that follows the guard -
282.5 GB/s, 17.5x the single-chunk form. A guard clause that returns
early measured 2.6x slower at 22 VGPRs against 33, so the prefetch sits
after the guard rather than replacing it.

Against the product on the same host, m = 1: attention 5120 x 1024
14.86x, gate/up 5120 x 17408 4.96x, down 17408 x 5120 7.79x, lm_head
5120 x 151936 5.22x. At m = 2: 13.71x, 4.86x, 8.85x, 4.90x. Row variants
at 5120 x 5120: m = 1 9.81x, m = 2 9.92x, m = 3 7.33x, m = 4 7.03x, every
one bit-identical to the tile. A K that is not a multiple of 64 keeps its
tail on tf_nvfp4_gemm.

build/hip.zig's headers list becomes hip_headers.zig, which walks every
.hpp under zig/kernels/hip instead of naming them. The list it replaces
had gone three headers out of date - quant/nvfp4.hpp, nvfp4_tiles.hpp and
fp8_tiles.hpp were missing - so an edit to one left the .hsaco that
includes it stale, and the four new symbols then failed to resolve in
affine_tiles although they were compiled. A walked list cannot be left
out of, and hip.zig loses ten lines to it.

The product records name the tile's measured LDS on the four served chips.

`hip-kernel-contract-limits` on gfx1030, gfx1100, gfx1151 and gfx1201
after the 64 x 64 tile and the 16-row decode block: the tile stages a
column chunk in LDS, so NVFP4 holds 16384 bytes (was 11264) and FP8 18432
(was 12288), and FP8's scale and accumulator registers moved with it.
The four column entry points' records, measured on the same run (VGPRs /
SGPRs / LDS bytes):

- tf_nvfp4_gemm: 138/38/16384, 144/38/16384, 144/38/16384, 143/36/16384.
- tf_fp8_gemm: 58/49/18432, 56/49/18432, 56/49/18432, 58/48/18432.
- tf_nvfp4_col1: 130/22/0, 138/22/0, 138/22/0, 138/23/0.
- tf_nvfp4_col2: 164/26/0, 165/26/0, 165/26/0, 164/28/0.
- tf_nvfp4_col3: 148/31/0, 145/30/0, 145/30/0, 147/34/0.
- tf_nvfp4_col4: 121/32/0, 141/32/0, 141/32/0, 144/38/0.

All 24 ModelOpt lines read "record current" on all four chips, and the
run's problem count is the same as before this branch: 799 on the base
and 799 here, every line of them predating it.

Main's prompt tail names the shared handle's dense tag (prompt_tail.zig:63);
the handle is optional here, so it asks the projection's format instead.
A single-format ModelOpt FP8 checkpoint declares quant_algo FP8 and carries
no config_groups, so the config check fell through to the NVFP4 branch and
refused it before the FP8 tensor reader ran. admit and admitRecipes now take
one rule through singleFormat: NVFP4 checked as ModelOpt writes it, plain FP8
accepted per tensor. Sharing the one rule keeps the two entry points from
drifting, and every other algorithm is still refused by name; the grouped FP8
formats are named MXFP8 and FP8_PB_WO and stay refusals by module.

The Qwen-shaped MTP head always splits the fused mtp.fc, but the FP8 split
returned UnevenSplit. It now cuts the codes into two contiguous halves along
K, keeps every row in order, and shares the projection's one F32 scale
between them.

Tests: both entry points admit one ModelOpt FP8 config fixture, an INT4_AWQ
fixture is still refused by name, and an FP8 fused FC beside the pre-FC norms
checks both halves' shapes, code bytes and the shared scale.

zig build test: 6528 passed, 168 skipped, 0 failed.
…endencies

The HIP code objects' dependency scan walked only .hpp, so a group source's
own include was untracked: attention.hip brings in attention/attention_fa.hip,
and an edit to that include could reuse a stale code object until a clean
rebuild. The scan now reads every kernel source under the root and tracks the
files it includes, resolved beside the including file first as clang reads
"...", then at the -I root, so a later include is covered without a list to
update.

hip_headers.zig's walk becomes a pure collect(allocator, io, root), tested on
a synthetic tree: a .hpp and an included .hip are tracked, a compiland that
nothing includes is not. A test-hip-headers step joins `test` and runs without
-Dhip, so a dropped include fails in CI as well as on the next edit.

The singleFormat comment is one line, as the lean rule requires.
The indexed file selection kept only shards holding model.language_model.* or
lm_head.*, and always returned an empty side list. A ModelOpt checkpoint whose
declared mtp.* tensors ship in their own indexed shard or in an
mtp*.safetensors side file therefore lost the head: Checkpoint.mtp reopened the
model's shards, found no MTP norm and returned null without an error.

indexed() now takes whether to keep the head, adds the shards holding mtp.* and
the mtp*.safetensors files beside them, leaving an mtp-named file out of the
model list so a tensor is not counted twice. mtp() looks through the side files
and then the model's own shards and only returns null when neither holds a norm,
so a head that ships apart is found and one that is absent is still silent.
Checkpoint.open passes the config's ModelOpt flag, so the same selection feeds
the preflight.

deviceBytes counted every stored byte, doubling only E4M3 group tables. Norms,
A_log, dt_bias and conv weights read through projection.float, centred and conv,
which produce F32 tensors, and the uploader allocates those lengths: a BF16 norm
of N elements costs 4N on the device, not 2N. Each conversion is now counted
against the tensor's own value count, and the MTP shards and side files are
counted with the rest.

Tests: an indexed MTP shard and an mtp side file each reach Checkpoint.mtp, and
each fails before the selection change; a BF16-to-F32 case beside the existing
table and embedding test.
… rule

The lean rule's 600-line limit fails on the current base: engine.zig reached
602 lines and native.zig 617. The no-GPU lean step reported two problems the
base lacks and the zig job failed before any test ran.

The layer-cancel poll moves to prompt_poll.zig: the Poll struct, its layer
hook and the trace that decides whether a pass can stop. The engine keeps
Cancel and Poll as aliases and forwards poll in one line, so hip_lanes and
the nemotron family see the same shapes they did. The port also carries the
base's edge-event handoff: one layer stays queued while the previous one's
edge is awaited, and a cancel still drains before error.Cancelled.

The four config-only refusals move to native_refusals.zig: decisionOnly,
oneRank, bf16Drafter and the Refused/refuse/gibs they need. They read the
checkpoint's config and never touch a device, so nothing about admission or
loading changes. Refused is re-exported, so native/hip.zig's error.Refused
tests are untouched.

No behavior change: every moved body is byte-for-byte the same.

lean check against the rebased base: 0 new problems; engine.zig 597 and
native.zig 582 lines. zig fmt --check and zig ast-check pass on all four
files.
The rebase joined upstream's unused-tensor refusal with this branch's
side-first MTP table search: the refusal named `side`, but this function
reaches the shard sets through `c.files.side` and declares no such local.
The Windows `zig build test` step could not compile checkpoint.zig.

Use `c.files.side` in the refusal, matching the search above it.
…counters

One presence test on Files now decides the source for Checkpoint.open, textBytes and deviceBytesAt, so a bf16 checkpoint's text count can no longer disagree with what its loader reads. A head the loader refuses (declared mtp_layers) is counted by neither, and an embedded language_model.mtp head is counted once, from the shards that hold it.
The loader kept its own presence test for a side or model-shard head
(mtp.norm_e.weight or mtp.pre_fc_norm_embedding.weight), while
Files.mtpSource took any `mtp.` key. The two disagreed on malformed
layouts:

- a side file with `mtp.` tensors but neither norm loaded as "no head",
  while preflight counted its bytes;
- a stray `mtp.` tensor in the model shards made the main table the
  source, and the loader then failed on a missing norm where main returns
  null.

mtpSource now selects a shard set by those first norms (isMtpNorm, the
names readMtp reads for every head it accepts): the side files first,
then the model shards, unprefixed (the main table) before
`language_model.`. A set holding `mtp.` tensors but neither norm is
refused with error.MtpHeadWithoutNorm and one message naming the file and
both norms. Checkpoint.open, deviceBytesAt and textBytes all call it, so
the loader and preflight refuse together. The loader's side check calls
the same names (Table.hasMtpNorm).

Well-formed checkpoints keep their source and totals: every layout in
mtp_source_test.zig is unchanged, and a head readMtp can read always holds
one of the two norms.

Tests: a side file of mtp tensors without a norm, and a stray mtp tensor
in the model shards, are each refused by Checkpoint.open, the preflight
source and the byte counters; both fail on ashhart#2490's head.
…to the kernels' u32

unfit took 2 * weight.shape[1] and scale.shape[1] * 16 unchecked, so a header-only empty tensor (shape [0, 2^63]
or a scale [0, 2^60], which the safetensors parser accepts as no bytes) wrapped to K = 0 and passed every check;
view repeated the products and cast N and K to u32, a panic for an empty [2^33, 0]. unfit now multiplies with
std.math.mul and refuses past 2^64, refuses N or K at 2^32 or more (the kernels take u32), and read names the
weight in the refusal; view checks the same products and casts with std.math.cast, refusing as UnsupportedTables.
A host test builds header-only safetensors files with those shapes and checks each reason.
…rt#2490's core projection

Main's hip_prompt_test.zig (8c14c27) sets e.weights.embed to .{ .mlx = undefined } and .{ .bf16 = undefined },
written while a Projection was quant.Device itself; ashhart#2490 makes it a union whose core arm holds that Device beside
nvfp4 and fp8, so those four lines now say .{ .core = .{ .mlx = undefined } } and .{ .core = .{ .bf16 = undefined } }.
Engine.plain reads the format through .core, so each test checks what it did on main.
@ashhart
ashhart merged commit 8b2a204 into ashhart:main Dec 3, 2026
7 of 8 checks passed
ashhart added a commit that referenced this pull request Dec 3, 2026
The loader kept its own presence test for a side or model-shard head
(mtp.norm_e.weight or mtp.pre_fc_norm_embedding.weight), while
Files.mtpSource took any `mtp.` key. The two disagreed on malformed
layouts:

- a side file with `mtp.` tensors but neither norm loaded as "no head",
  while preflight counted its bytes;
- a stray `mtp.` tensor in the model shards made the main table the
  source, and the loader then failed on a missing norm where main returns
  null.

mtpSource now selects a shard set by those first norms (isMtpNorm, the
names readMtp reads for every head it accepts): the side files first,
then the model shards, unprefixed (the main table) before
`language_model.`. A set holding `mtp.` tensors but neither norm is
refused with error.MtpHeadWithoutNorm and one message naming the file and
both norms. Checkpoint.open, deviceBytesAt and textBytes all call it, so
the loader and preflight refuse together. The loader's side check calls
the same names (Table.hasMtpNorm).

Well-formed checkpoints keep their source and totals: every layout in
mtp_source_test.zig is unchanged, and a head readMtp can read always holds
one of the two norms.

Tests: a side file of mtp tensors without a norm, and a stray mtp tensor
in the model shards, are each refused by Checkpoint.open, the preflight
source and the byte counters; both fail on #2490's head.
ashhart added a commit that referenced this pull request Dec 3, 2026
…s core projection

Main's hip_prompt_test.zig (8c14c27) sets e.weights.embed to .{ .mlx = undefined } and .{ .bf16 = undefined },
written while a Projection was quant.Device itself; #2490 makes it a union whose core arm holds that Device beside
nvfp4 and fp8, so those four lines now say .{ .core = .{ .mlx = undefined } } and .{ .core = .{ .bf16 = undefined } }.
Engine.plain reads the format through .core, so each test checks what it did on main.
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Thank you @ElderOrb. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

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:ready Reviewed by Synthena and ready for group train

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants