Skip to content

fix(tenstorrent): load block-float checkpoints at their own precision, not fp32 - #3813

Merged
Qubitium merged 3 commits into
mainfrom
fix/tt-blockfloat-dtype
Nov 13, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/tt-blockfloat-dtype

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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.dtype request was coerced to float32

So 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_pretrained semantics).

There was a second, quieter upcast: TTBlockfloatEmbedding.forward called dequantize() 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 returned logits dtype: float32.

Why bf16 is safe here

Nothing in the solve needs fp32 weights:

step precision
activation → X^T X upcast to float32 (collect_layer_hessians, unchanged)
per-column GPTQ solve weight upcast to float32 (gptq_solve_blockfloat)
solved weight copied back bf16 is exact for the grid

bf4_b keeps 3 significant bits and bf8_b keeps 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's torch_dtype; an explicit torch.dtype or string wins; the loader's "not provided" sentinel is not a dtype and does not win.
  • script: --dtype {auto,float32,bfloat16,float16}, default auto; prints the resolved dtype; the post-save reload check now runs at the saved precision.
  • loader: build_tt_blockfloat_model / _load_tt_blockfloat_model pass dtype through instead of forcing float32.
  • TTBlockfloatEmbedding: records the dtype the model was built at (set by swap_blockfloat_modules from the module it replaces) and dequantizes into it.
  • tests: resolver semantics, bf16 exactness of the grid, bf16 checkpoint load + bit-exact reload, explicit fp32 still selectable.

Verification

  • pytest tests/test_tenstorrent_support.py → 100 passed, 14 skipped; ruff clean.
  • Real end-to-end, facebook/opt-125m --dtype bfloat16:
    [Q] source dtype: torch.bfloat16
    [Q] quantized 53 modules in 10s
    [Q] mean norm_l1=0.2143 on_grid=True
    [Q] reloaded 53 layers from the HF index, logits maxdiff=0.00e+00
    
    saved config.json → torch_dtype: bfloat16.
  • unsloth/Llama-3.2-1B-Instruct config resolves to torch.bfloat16 (previously would have loaded fp32).
  • Backward compatible: the published fp32 checkpoint (Qubitium/llama3.2-1b-instruct-tenstorrent-bf8-bf4-w4a16) still loads as float32 and its embedding still emits float32.

Notes

  • No re-quantization is needed for existing checkpoints; they declare torch_dtype and keep loading at it.
  • --dtype float32 remains available for debugging.

…, 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.
Comment thread tests/test_tenstorrent_support.py Fixed

Copy link
Copy Markdown
Collaborator Author

Review of 6ff47d1a089058ae030a9ea105f4e8cd42ef3d10 against 276605140c04d8b58b145f7245c7e3b11dd5cfee, including a fresh subagent pass and parent reproduction. Three confirmed findings:

  1. [P2] Preserve FP32 rotary buffers when applying the checkpoint's default dtype. The newly resolved dtype at tt_blockfloat_quant.py:1606 reaches _from_config(config).to(dtype=dtype) at line 1624. That blanket conversion also narrows Llama's deliberately FP32 rotary_emb.inv_freq to BF16. A tiny BF16 Llama loaded through actual from_pretrained, quantized, saved and reloaded consequently changes its rotary frequencies and logits. Reproduced maximum logit difference: 0.0078125; restoring only the source's FP32 inv_freq makes the logits bit-exact again. The added test misses this because its source also uses a blanket .to(bfloat16). Construct through the model's dtype-aware initialization path while preserving buffers intentionally kept in FP32.

  2. [P2] Keep config dtype synchronized with an explicit load override. tt_blockfloat_quant.py:1606 resolves dtype=torch.float32 without updating the BF16 config. Loading a BF16 checkpoint with that override produces FP32 parameters but leaves model.config.dtype=bfloat16. Re-saving then writes conflicting "dtype": "bfloat16" and "torch_dtype": "float32"; Transformers prioritizes the former, so this PR's default reload silently returns to BF16. In a sharded save/load reproduction, a norm value 1.0010000467300415 becomes 1.0. The exact base loads the same artifact as FP32 and preserves the value. Propagate the resolved dtype into authoritative model/config metadata and avoid emitting conflicting dtype fields.

  3. [P2] Make the embedding's output dtype follow module dtype conversions. tt_blockfloat.py:267 stores the dtype as a plain Python attribute. Module.to(), .float(), .half() and .bfloat16() do not update it. A BF16 block-float embedding followed by a BF16 dense linear works initially; after model.float(), the embedding still emits BF16 while the linear is FP32, and forward raises a dtype-mismatch error. A normal embedding follows the cast correctly. Track this through module conversion—for example, a zero-element non-persistent floating buffer—rather than freezing the construction-time dtype.

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.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

All three reproduced and fixed in afb35a0.

1. FP32 rotary buffers (P2). Confirmed the mechanism: LlamaForCausalLM._from_config(cfg) gives bf16 params with inv_freq: float32, while .to(torch.bfloat16) narrows it — so the loader's blanket .to() diverged from from_pretrained. Fixed by building through _from_config and casting per tensor, skipping buffers HF pins to fp32 (*inv_freq, plus model._keep_in_fp32_modules). The bf16 test now builds its source with _from_config (the previous one did use a blanket .to(bf16), exactly as you noted), asserts inv_freq is float32 after load, and requires bit-exact logits — it passes.

2. Config dtype desync (P2). Confirmed: _from_config does not touch config.dtype when no dtype is passed, so an explicit dtype=torch.float32 left dtype: bfloat16 beside torch_dtype: float32. Now _sync_config_dtype sets both on resolve (writing the deprecated mirror through __dict__ to avoid a per-load warning), and save_blockfloat_model writes both from the actual parameter dtype. The test re-saves the upcast model, asserts dtype/torch_dtype are both float32 in the artifact, and checks a norm tensor survives the reload unchanged.

3. Embedding output dtype (P2). Confirmed: after model.float() the table kept emitting bf16 into fp32 linears. output_dtype is now a property over a zero-element non-persistent buffer, which Module.to/.float()/.bfloat16() converts and which does not enter the state dict. New test covers both cast directions and asserts _output_dtype_anchor is absent from state_dict().

Also fixed the file-handle note (with open(...)) and resolved that thread.

Verification: pytest tests/test_tenstorrent_support.py → 101 passed, 14 skipped; ruff clean. Re-ran the real path end to end (facebook/opt-125m --dtype bfloat16): quantize → save → reload gives logits maxdiff=0.00e+00 with config.json dtype/torch_dtype both bfloat16.

Backward compatibility: the published fp32 artifact already carries dtype: float32 and torch_dtype: float32, so it still loads at fp32; no re-quantization needed.

Copy link
Copy Markdown
Collaborator Author

Review of afb35a0abfec3f705fd2ea16d15f41ff2d4bd358 against 276605140c04d8b58b145f7245c7e3b11dd5cfee.

[P2] Convert pinned parameters to FP32 instead of leaving them at their initialization dtype. In _cast_model_dtype, lines 172–177, _is_pinned_fp32 makes parameters skip conversion altogether. However, the preceding _from_config(config) still initializes parameters using the checkpoint's declared dtype. For GPT-OSS, _keep_in_fp32_modules includes the norms, so a BF16 checkpoint explicitly loaded with dtype=torch.float32 retains BF16 norms while the remaining parameters and config.dtype become FP32. Copying any FP32 norm payload into those BF16 parameters then silently rounds it.

Reproduced through save_blockfloat_model → load_blockfloat_model(..., dtype=torch.float32) using a real one-layer GptOssForCausalLM (hidden/intermediate size 32, two experts, BF16 config), on-grid attention/embedding weights, and a dense FP32 final norm filled with 1.001. The source/stored norm is 1.0010000467300415; this head reloads it as BF16 1.0, whereas the exact base reloads FP32 1.0010000467300415. This also breaks the explicit override even when the stored norm was already BF16. Please assign an explicit target dtype to pinned tensors rather than assuming they started in FP32, while retaining the rotary-buffer fix; add a non-Llama checkpoint regression covering this case.

The three previously reported Llama/config/embedding-cast issues are addressed by the new tests. Validation on free-threaded Python with PYTHON_GIL=0, Torch 2.15.0.dev20260928+cu130, Transformers 5.20.2: full tests/test_tenstorrent_support.py yielded 96 passed, 15 skipped, 4 failed on head versus 92 passed, 15 skipped, the same 4 failures on exact base. Those four failures require an initialized Tenstorrent PJRT runtime. The additional CPU checkpoint reproduction above and git diff --check passed. No native Tenstorrent execution, large-model quality evaluation, or concurrent-loader qualification is claimed. No source edits.

`_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.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Fixed in 60d88c2.

Confirmed the mechanism. _is_pinned_fp32 was used as "leave alone", but _from_config initialises pinned params in the checkpoint dtype, so they were never promoted. Reproduced with a one-layer GptOssForCausalLM (bf16 config, norms set to fp32 1.001 as from_pretrained would leave them), saved through save_blockfloat_model:

old (skip):  norm dtype torch.bfloat16   value 1.0
new (promote): norm dtype torch.float32  value 1.0010000467300415

Change: pinned tensors are now converted to float32 rather than skipped; everything else still follows the resolved dtype. The rotary fix is unaffected — inv_freq is already fp32, so the explicit .to(float32) is a no-op there, and the existing bf16 bit-exact test still passes.

Regression test: test_blockfloat_pinned_fp32_norms_survive_an_fp32_override builds a real GPT-OSS (hidden/intermediate 32, two experts, bf16 config), asserts the precondition that the norm starts bf16, saves with an fp32 norm payload, then checks both loads:

  • default → model bf16, model.norm.weight fp32 (matches from_pretrained)
  • dtype=torch.float32 → model.norm.weight fp32, value exactly 1.0010000467300415

pytest tests/test_tenstorrent_support.py → 102 passed, 14 skipped; ruff clean. No Tenstorrent runtime was needed for this reproduction; the 4 PJRT-dependent failures you noted are unchanged and pre-existing.

@Qubitium
Qubitium merged commit 33df888 into main Nov 13, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/tt-blockfloat-dtype branch November 13, 2026 06:12
Qubitium added a commit that referenced this pull request Nov 13, 2026
* 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant