Repository navigation
fix(tenstorrent): load block-float checkpoints at their own precision, not fp32 - #3813
Conversation
…, not fp32
`scripts/tt_quantize_blockfloat.py` loaded the source model with
`dtype=torch.float32`, and both `build_tt_blockfloat_model` and
`_load_tt_blockfloat_model` coerced any non-dtype request to float32. A bf16
Llama-3.2-1B was therefore resident at twice its size and replayed in fp32
during calibration -- a deviation from the GPTQ/AWQ routes, which use the
checkpoint's declared dtype.
Nothing about the solve needs fp32 weights: `collect_layer_hessians` upcasts
activations and accumulates `X^T X` in float32, the per-column solver upcasts
the weight, and every bf4_b/bf8_b grid value is exactly representable in bf16
(3 and 7 significant bits against bf16's 8), so solved weights survive bf16
storage without rounding.
Also fixes a second silent upcast: `TTBlockfloatEmbedding.forward` called
`dequantize()` with its float32 default, so a bf16 checkpoint still ran the
whole forward in float32 -- visible as float32 logits out of a bf16 model. The
table now records the dtype the model was built at, set by
`swap_blockfloat_modules` from the module it replaces.
- `resolve_blockfloat_dtype`: None/"auto" -> checkpoint dtype, explicit wins
- script: `--dtype {auto,float32,bfloat16,float16}`, default `auto`
- loader: stop coercing to float32; reload check uses the saved precision
- tests: resolver, bf16 exactness of the grid, bf16 load + bit-exact reload
Verified end to end: OPT-125M quantized at bf16 saves and reloads with
`logits maxdiff=0.00e+00`; the published fp32 checkpoint still loads as fp32.
|
Review of
Validation: the full Tenstorrent support suite returned 95 passed, 15 skipped, 4 failed on head versus 92 passed, 15 skipped, the same 4 failures on exact base. All four failures require an initialized Tenstorrent PJRT runtime and are unrelated to this change. The three newly added tests pass. Additional CPU probes reproduced all findings above using Torch 2.15.0+cu132 / Transformers 5.22.1; no Tenstorrent runtime or free-threaded qualification is claimed. No source edits. |
…e's dtype honest Three findings from review of 6ff47d1, all reproduced. 1. The loader built with `_from_config(config).to(dtype)`. A blanket `.to()` also narrows Llama's float32 rotary `inv_freq`, which `from_pretrained` deliberately leaves alone (it is created with an explicit `.float()` and is absent from the checkpoint). Loading, saving and reloading a bf16 model therefore changed the rotary frequencies; measured logit drift 0.0078125. Build through `_from_config` and cast per tensor, skipping buffers HF pins to fp32 (`inv_freq`, plus `_keep_in_fp32_modules`). Logits are bit-exact again. 2. Resolving an explicit `dtype=torch.float32` left `config.dtype` at the checkpoint's bf16. `save_blockfloat_model` then wrote `dtype: bfloat16` next to `torch_dtype: float32`, and transformers prefers `dtype`, so the next load silently reverted to bf16 and a norm of 1.0010000467300415 came back as 1.0. Sync both fields when the dtype is resolved, and write both from the actual parameter dtype on save. 3. `TTBlockfloatEmbedding` stored its output dtype as a plain attribute, which `Module.to()`/`.float()`/`.bfloat16()` never update: after `model.float()` the table still emitted bf16 into fp32 linears and the forward raised a dtype mismatch. Track it through a zero-element non-persistent buffer, which `Module.to` converts and which does not enter the state dict. Also closes the review's file-handle note in the test (`with open(...)`). Tests: the bf16 load test now builds its source the way `from_pretrained` does and asserts fp32 `inv_freq` plus bit-exact logits; a new test covers the embedding after `.float()`/`.bfloat16()`; the explicit-override path is checked for config consistency across a re-save and reload.
|
All three reproduced and fixed in 1. FP32 rotary buffers (P2). Confirmed the mechanism: 2. Config dtype desync (P2). Confirmed: 3. Embedding output dtype (P2). Confirmed: after Also fixed the file-handle note ( Verification: Backward compatibility: the published fp32 artifact already carries |
|
Review of [P2] Convert pinned parameters to FP32 instead of leaving them at their initialization dtype. In Reproduced through The three previously reported Llama/config/embedding-cast issues are addressed by the new tests. Validation on free-threaded Python with |
`_cast_model_dtype` skipped every tensor `_is_pinned_fp32` matched. That is wrong when the model declares `_keep_in_fp32_modules` (GPT-OSS lists `input_layernorm`, `post_attention_layernorm` and `norm`): `_from_config` initialises them in the checkpoint dtype, so an explicit `dtype=torch.float32` load left bf16 norms while the rest of the model became fp32. Copying a stored fp32 norm payload into a bf16 parameter then rounded it. Reproduced with a one-layer `GptOssForCausalLM` (bf16 config, fp32 norm 1.001): old -> bf16 `1.0`, new -> fp32 `1.0010000467300415`. The rotary fix is unchanged: `inv_freq` is already fp32, so the explicit `.to(float32)` is a no-op there. Pinned tensors are now converted *to* float32; everything else follows the resolved dtype. New regression test builds a real GPT-OSS, saves it, and checks both the default load (bf16 model, fp32 norm) and the explicit-fp32 load.
|
Fixed in Confirmed the mechanism. Change: pinned tensors are now converted to Regression test:
|
* feat(tenstorrent): emulate bf8/bf4 block-float on CUDA Add a CUDA sibling of the HIP block-float kernels so a `bf4_b` / `bf8_b` checkpoint can be validated and benchmarked on an NVIDIA part without Tensix hardware. The host contract in `tt_blockfloat_cuda.h` is identical to the HIP header; only the runtime types differ. Names follow the vocabulary #3760 settled on: `bf4_b` / `bf8_b` for the two dtypes, `blockfloat_*` for the exported C entry points, and `hw/dtypes.md` section 8 as the single definition of the bit layout. The extension README points at that section instead of restating it, and `docs/tenstorrent.md` gains a short section so the emulation path is reachable from the same place as the card paths. Storage and every rounding decision match `gptqmodel.utils.tt_blockfloat_quant`: quantise reproduces the three-candidate exponent search and its strict `<` tie-break, so the new tests can require bit-exact agreement with the torch reference rather than a tolerance. The GEMM expands the packed weights once and hands the matmul to cuBLAS, which reaches roughly twice what a hand-written tile gets on the same shape. cuBLAS is resolved with dlopen/dlsym: pip CUDA wheels ship `libcublas.so.13` with no `libcublas.so` symlink, so a link-time `-lcublas` fails there and the soname follows the CUDA major. A fused `mma.m16n8k16` kernel stays as the fallback when it cannot be resolved. `TTBlockfloatLinear`, `TTBlockfloatEmbedding` and `TTBlockfloatTiedHead` read the packed codes directly on CUDA instead of materialising a dense weight, which is the point of the emulation: a `bf4_b` layer then costs what it will cost on Tensix. Every other device keeps the dense path. Two latent bugs surfaced while validating and are fixed here: the fp32 SIMT kernel offset into the packed `bf4_b` buffer with an unpacked element index, and the fused kernel packed bf16 bit patterns into an fp16 shared tile, so the fp16 fallback was wrong. Measured on a shared PG506-230 (sm_80), n = k = 4096, `bf4_b`, best of six: 48/52/46/47/64/93/145/253 us for 1/16/32/64/128/256/512/1024 tokens (136 TFLOP/s at 1024), against 218 us and 542 us for the same two ends before this change. * fix(tenstorrent): make the CUDA scratch per-call and stream-safe Addresses the four findings from the review of the CUDA block-float kernels. [P1] Overlapping streams shared one scratch buffer per device. The mutex only serialised allocation, so two stream-scoped forwards could overwrite each other's decoded weights while both were queued. Scratch is now owned by the call -- a TemporaryBuffer that is freed with cudaFreeAsync on the calling stream -- and the cuBLAS handle is per (device, stream) rather than per device, because a handle carries a device-side workspace that must not be shared either. [P2] The cached scratch stayed live at the largest size ever requested, holding an expanded copy of the weights between calls. Nothing is retained now: cudaMemPoolAttrUsedMemCurrent returns to zero once the stream drains. The buffer comes from a private per-device pool because the default pool hands every freed block straight back to the driver, which puts a fresh 34 MB allocation at ~1.9 ms; a pool that keeps its blocks makes the same alloc/free pair ~12 us. [P2] A strided activation was rejected: reshape(-1, k) can return a non-contiguous view and the op refused it. The binding materialises it with contiguous(), which is a no-op when the tensor is already packed, so the kernel path keeps the layouts the dense path accepted. [P2] The epilogue mapped every row onto grid.y, which caps at 65535, so M = 65536 failed with "invalid argument". Rows are now strided across the blocks that fit. Four regression tests cover the findings, one per report. The stream and memory tests fail against the previous implementation -- 48 MB left live in the async pool and corrupted stream output -- so they are not tautological. The forced no-cuBLAS fallback was re-validated too. Perf is unchanged: 46/58/52/54/72/96/147/254 us for 1/16/32/64/128/256/512/1024 tokens. * fix(tenstorrent): mask odd-N fallback stores and keep empty forwards Addresses the two findings from the second review round, and resolves the rebase onto #3813 (block-float checkpoints load at their own precision). [P1] The fused fallback's epilogue owns a pair of adjacent output columns per fragment, but only the first was range-checked, so an odd `n` stored into `out[m * n]` and read `bias[n]`. The second bias load and both second-column stores are now guarded by `gn + 1 < n`. This is the path taken when cuBLAS is unavailable, which is why it went unnoticed: every existing test ran through cuBLAS. `GPTQMODEL_BLOCKFLOAT_NO_CUBLAS=1` now forces the fallback, so the tests can reach it on a machine that does have cuBLAS, and the full linear validation was re-run through it. [P2] Empty forwards raised: the embedding dispatch launched a zero-block kernel and the linear binding rejected a zero-row activation, so `TTBlockfloatEmbedding` and `TTBlockfloatTiedHead` broke where the dense paths returned `(0, 16)` and `(1, 0, 3)`. Both modules now return the dense path's shape and dtype before dispatch, and the bindings tolerate empty operands so direct callers behave the same. Rebase resolution: #3813 gave the embedding an `output_dtype` that follows `Module.to`, so the gather kernel and the empty return now use `self.output_dtype` rather than float32 -- otherwise a bf16 table would have emitted float32 on both new paths. The suite also takes its skip reason from `tests/accelerator_gates.py` now, per #3805, so a HIP build is rejected before the capability probe. Two regression tests, both verified to fail against the previous head: the fallback canary test (`n = 1/3/5` with a sentinel after the last element) and the empty-forward test (shape, dtype and equality with the dense path, including a bf16-cast table). 84 tests pass; the forced fallback still matches the reference on every shape/dtype case.
Problem
The TT block-float path loaded the source model in full float32:
scripts/tt_quantize_blockfloat.py:from_pretrained(..., dtype=torch.float32)build_tt_blockfloat_model()and_load_tt_blockfloat_model(): any non-torch.dtyperequest was coerced tofloat32So a bf16 Llama-3.2-1B sat at 2x its resident size and the calibration replay ran in fp32. That is not what the GPTQ/AWQ routes do — they use the checkpoint's declared dtype (
from_pretrainedsemantics).There was a second, quieter upcast:
TTBlockfloatEmbedding.forwardcalleddequantize()with its float32 default, so even a bf16 checkpoint produced float32 activations and the whole forward ran in fp32. Diagnosed from the model itself: a bf16 checkpoint returnedlogits dtype: float32.Why bf16 is safe here
Nothing in the solve needs fp32 weights:
X^T Xcollect_layer_hessians, unchanged)gptq_solve_blockfloat)bf4_bkeeps 3 significant bits andbf8_bkeeps 7; bf16 carries 8. Every value the grid can store is therefore exactly representable in bf16, so the solved weights do not move when copied into a bf16 parameter — asserted by a new test.Changes
resolve_blockfloat_dtype(dtype, config):None/"auto"→ the checkpoint'storch_dtype; an explicittorch.dtypeor string wins; the loader's "not provided" sentinel is not a dtype and does not win.--dtype {auto,float32,bfloat16,float16}, defaultauto; prints the resolved dtype; the post-save reload check now runs at the saved precision.build_tt_blockfloat_model/_load_tt_blockfloat_modelpassdtypethrough instead of forcing float32.TTBlockfloatEmbedding: records the dtype the model was built at (set byswap_blockfloat_modulesfrom the module it replaces) and dequantizes into it.Verification
pytest tests/test_tenstorrent_support.py→ 100 passed, 14 skipped;ruffclean.facebook/opt-125m --dtype bfloat16:config.json→torch_dtype: bfloat16.unsloth/Llama-3.2-1B-Instructconfig resolves totorch.bfloat16(previously would have loaded fp32).Qubitium/llama3.2-1b-instruct-tenstorrent-bf8-bf4-w4a16) still loads as float32 and its embedding still emits float32.Notes
torch_dtypeand keep loading at it.--dtype float32remains available for debugging.