Skip to content

NF4 dequant cache: no pre-hook on models without NF4 weights, keep autocast on the compiled route, invalidate on in-place scale writes - #18433

Merged
danielhanchen merged 4 commits into
mainfrom
kp-dequant-cache
Nov 19, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
kp-dequant-cache

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

NF4 dequant cache: no Trainer pre-hook on models without NF4 weights

Summary

Stop the NF4 dequant cache's Trainer scope from installing its forward pre-hook on models with no NF4 weights. Before this change, every dense or 16-bit LoRA model trained with a transformers Trainer after import unsloth paid a host read of the attention mask on every forward, for a cache it can never use.

Root cause

#18285 (merge 567f979) appends UnslothDequantCacheScope to transformers.trainer.DEFAULT_CALLBACKS. Its on_train_begin registers _model_pre_hook on whatever model is trained. For a 2D attention mask the hook calls _padded, which runs bool(mask.all()), a host sync on a CUDA mask, before checking whether the model has anything to cache. Measured with a dispatch-mode counter on CPU: one aten.is_nonzero / _local_scalar_dense call per forward of a plain dense model on origin/main, zero on the parent. This is a cost, not a correctness issue: one extra device sync per micro-batch at the start of the forward.

Reachability: the default case. Any non-4-bit model (bf16 LoRA, full fine-tuning) trained with a Trainer while the cache mode is auto.

Fix

  • New _has_nf4_weights(model): one pass over the modules per train(). It looks for a bitsandbytes NF4 quant state on a parameter, or on a Linear4bit's own quant_state copy (FSDP2 all-gathers the packed bytes into a Parameter without one).
  • on_train_begin leaves the scope off (_ACTIVE = 0, no hook) when the trained model has none, so nothing is cached for that run.
  • If the check cannot run, it returns True and keeps the previous guarded behaviour. NF4 models are unchanged, hook included.

Tests

New tests/test_nf4_dequant_cache_dense_model.py (CPU; each arm prints the dequant_cache.__file__ it imported):

  • origin/main (8ef13a7) with only the new test copied in: 1 failed, 2 passed (dense model: assert 1 == 0 host reads per forward).
  • this branch: 3 passed. The NF4 cases (quant state on the parameter, or only on the Linear4bit) still install the hook and still do the one mask read.
  • Existing tests/test_nf4_dequant_cache.py passes on this branch (35 passed together with the new file).

Command: pytest tests/test_nf4_dequant_cache_dense_model.py tests/test_nf4_dequant_cache.py -o addopts= -m "not server and not native_mxc" -p no:cacheprovider.

Not proven here

  • The per-step time cost of the removed sync was not measured on a GPU.
  • An NF4 weight whose quant state is reachable neither from its parameter nor from its module would now turn the cache off for that run. This is slower but safe, since nothing is cached. None of the current loaders do this.

NF4 dequant cache: keep autocast semantics on the compiled matmul route

Summary

Keep autocast semantics on the compiled NF4 matmul route added in #18285. Under torch.compile with autocast, matmul_lora on an NF4 weight (no LoRA term, grad off, as inside the fused LoRA autograd functions) returned a different dtype and different values than the eager path.

Root cause

#18285 (merge 567f979) routes traced NF4 matmuls through the opaque op unsloth::nf4_cached_matmul (unsloth/kernels/dequant_cache.py). It replaces a torch.matmul that autocast casts to the autocast dtype, but autocast does not see inside the op and its fake returns X.dtype. Measured on B200, torch 2.14.1, on origin/main:

  • fp16 input, fp16 NF4 weight, bf16 autocast: compiled output was fp16 inf in default, fullgraph=True and fullgraph=True, dynamic=True; eager gives finite bf16 524288.
  • bf16 input under fp16 autocast: compiled output bf16, eager fp16.
  • fp32 input, bf16 weight, bf16 autocast: compiled call failed with expected mat1 and mat2 to have the same dtype.

Reachability: only when the activation dtype differs from the autocast dtype inside a compiled, grad-off NF4 matmul_lora call (for example a user torch.compile around the fused LoRA path under a mismatched torch.autocast). Default FastLanguageModel training keeps the activation, quant state and autocast dtypes equal (patch_model_and_tokenizer casts quant_state.dtype), so I found no default configuration that reaches it. The fix is cheap and makes the op match the code it replaced.

Fix

  • nf4_matmul (traced Python wrapper): when there is no LoRA term and autocast is on for the input's device, cast X to the autocast dtype, as autocast would for torch.matmul. The checks are constant-folded by Dynamo and the autocast state is already part of Dynamo's global guards, so no new guard, graph break or recompile.
  • _matmul_impl: cast the dense weight to X.dtype when they differ, so the result no longer depends on whether autocast is active when the compiled graph runs.
  • The lora-first form is unchanged: it replaces unsloth::lora_first_addmm, which was already an opaque op that autocast did not cast. nf4_cached_addmm_ is unchanged (an in-place addmm_, which autocast does not cast).

Tests

New tests/test_nf4_dequant_cache_autocast.py (CUDA; compiled vs eager matmul_lora under autocast, asserts the traced op route ran). Both arms on one B200 lease, each arm importing its own tree (dequant_cache.__file__ printed):

  • origin/main (8ef13a7) with only the new test copied in: 5 failed, 34 passed (3x fp16 inf vs bf16, 1x bf16 vs fp16 dtype, 1x fp32 dtype mismatch RuntimeError).
  • this branch: 39 passed.

Command: pytest tests/test_nf4_dequant_cache_autocast.py tests/test_nf4_dequant_cache.py -o addopts= -m "not server and not native_mxc" -p no:cacheprovider.

Not proven here

  • Correctness on B200 (sm100) only; sm75 / sm80 / sm89 / sm120 and AMD were not run.
  • Only torch 2.14.1 was run on GPU. torch.is_autocast_enabled(device) and torch.get_autocast_dtype(device) exist and are constant-folded by Dynamo from torch 2.4, so the 2.6 floor imports, but no 2.6 GPU run was done.
  • No end-to-end Unsloth training run reaching the mismatched-dtype case, since I found no default configuration that reaches it.

NF4 dequant cache: invalidate on in-place scale writes

Summary

The NF4 dequant cache from #18285 could keep serving a dense weight decoded with old scales after an in-place write to the quant state's scales. The cache entry now records the address and version of every scale tensor the decode reads.

Root cause

#18285 (merge 567f979) keys a cache hit on the packed weight's storage pointer and version and on absmax.data_ptr() (_lookup / _miss in unsloth/kernels/dequant_cache.py). An in-place write to absmax (for example quant_state.absmax.mul_(2)) keeps its address, so the hit still matched. With nested quantization (compress_statistics=True), the decode also reads state2.absmax and offset, which were not checked at all. Reproduced on CPU with real bitsandbytes NF4 states: the stale entry differed from a fresh decode by up to 4.09 (plain absmax), 2.88 (nested absmax), 1.47 (state2.absmax) and 1.02 (offset).

Reachability: I found no Unsloth, PEFT or bitsandbytes path that writes NF4 scales in place during training; reloads, merges and requantization build new tensors, which the address check already caught. It needs user or third-party code that edits scales in place. The fix is a few host attribute reads per lookup, with no device sync.

Fix

  • New _scales_key(absmax, absmax2, offset): the data_ptr() and _version of absmax and, when present, of the nested absmax2 and offset. It is stored in the entry slot that held absmax.data_ptr() and compared on every hit and in _miss.
  • dequantize passes quant_state.state2.absmax and quant_state.offset. _dense_from_parts (the traced op path) passes the absmax2 and offset it already receives.
  • Inference tensors have no version counter; for those the key falls back to the address alone. They cannot be written in place outside inference mode, and the cache is bypassed inside it.

Tests

New tests/test_nf4_dequant_cache_scales.py (CPU, real bitsandbytes NF4 states, faked memory reading; each arm prints the dequant_cache.__file__ it imported):

  • origin/main (8ef13a7) with only the new test copied in: 4 failed, 33 passed (absmax plain, absmax nested, state2.absmax and offset cases all served stale).
  • this branch: 37 passed (new test plus the existing tests/test_nf4_dequant_cache.py).

Command: pytest tests/test_nf4_dequant_cache_scales.py tests/test_nf4_dequant_cache.py -o addopts= -m "not server and not native_mxc" -p no:cacheprovider.

Not proven here

  • The in-place write was simulated. No real training workload that writes scales in place was found or run.
  • The extra attribute reads on the hit path were not timed. They are host-only (data_ptr, _version), with no device sync.
  • In-place writes to the NF4 code tables (code, state2.code) are still not tracked. These are constant codebooks.

The traced unsloth::nf4_cached_matmul op replaced a torch.matmul that autocast
casts to its dtype, but the op is opaque to autocast and its fake returns
X.dtype. Under compile, an fp16 input under bf16 autocast came back as fp16
inf (eager: finite bf16), a bf16 input under fp16 autocast came back bf16,
and an fp32 input failed with a dtype mismatch. Apply autocast's cast to X in
the traced wrapper and cast the dense weight to X's dtype inside the op when
they differ. Paths without autocast or with matching dtypes are unchanged.

(cherry picked from commit 5514d69257074ad73bad08defce7680c41e599b0)
The cache hit compared the packed weight's version and the absmax address,
so an in-place write to absmax (or, with nested quantization, to the
second-level absmax or the offset) kept serving the dense weight decoded
with the old scales. Key the entry on the address and version of every
scale tensor the decode reads. Host attribute reads only, no device sync.

(cherry picked from commit 38134ddc66a0c5041d7980d3a553c367f4969f8f)
The Trainer scope installed its forward pre-hook on every trained model, so
a dense or 16-bit LoRA model paid a host read of the attention mask
(bool(mask.all())) on every forward for a cache it can never use. Check once
per train() whether the model holds a bitsandbytes NF4 weight (a parameter's
quant state or a Linear4bit's own copy) and leave the scope off otherwise.
NF4 models are unchanged.

(cherry picked from commit 85ded792805592eb220b7613543f334db1416dca)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T09:19:59.755778Z 6f416a5 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7df20e6430

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/kernels/dequant_cache.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 6f416a568b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 550121e into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the kp-dequant-cache branch November 19, 2026 11:02
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 20, 2026
…rker, bit-exact checksums (unslothai#18630)

Follow-up fixes for unslothai#18434, unslothai#18433, found while re-checking the PRs
merged on 2026-11-19. One commit per fix; every fix has a test that
fails on main and passes here.

| Fix | Follows up | Severity |
|---|---|---|
| QAT round checksum hashes 8-byte dtypes by their bits | unslothai#18434 | P2 |
| QAT round: re-round after an in-place reload under inference mode |
unslothai#18434 | P2 |
| QAT round: cross-recipe state_dict loads keep the target fake
quantizer | unslothai#18434 | P2 |
| NF4 dequant cache: inference-tensor scales and packed weights | unslothai#18433
| P2 |

## Tests (this branch vs main `54af93780b`, CPU)

- New and changed tests: main 10 failed / 8 passed, this branch 18
passed. Each test loads the code of its own tree.
- Neighbouring suites on this branch: QAT and NF4 dequant cache suites:
243 passed, 16 skipped.
- `prepush_gate.py` passes.

## QAT round checksum hashes 8-byte dtypes by their bits (follows up
unslothai#18434)

#### QAT round: checksum the bits of 8-byte dtypes, not their values

##### What broke

unslothai#18434 marks a rounded QAT base weight with `_checksum`
(`unsloth/models/_qat_round.py`) so a later device move or reload of the
same values is recognised as already rounded. `_checksum` views 1, 2 and
4 byte dtypes as integers, but an 8-byte dtype (float64) is converted by
value with `.to(torch.int64)`. Every float64 tensor below 1 in magnitude
therefore hashes to 0 and matches any other float64 tensor of the same
shape: two random 64 x 64 float64 weights give the same checksum.

Reachability today: none found. torchao fake quantization rejects
float64 inputs (`Unsupported input dtype: torch.float64`), so no QAT
model rounds a float64 weight yet. This is a latent fix so the checksum
means what its docstring says.

##### Fix

View every dtype wider than 2 bytes as int32 words (4-byte dtypes
exactly as before; 8-byte dtypes as two words). Checksums of 1, 2 and 4
byte dtypes are unchanged.

##### Tests

New `tests/test_qat_round_checksum_bits.py` (CPU): different values give
different checksums and a clone gives the same one, for float64 /
float32 / bfloat16 / float16; the file asserts it imports its own tree.

| Arm | Result (new file + `tests/test_qat_round_rewrite.py` +
`tests/test_qat_weight_memo_guards.py`) |
|---|---|
| origin/main 635532f | 1 failed (float64 checksums equal), 30
passed, 1 skipped |
| this branch | 31 passed, 1 skipped |

## QAT round: re-round after an in-place reload under inference mode
(follows up unslothai#18434)

#### QAT round: detect an in place reload of an inference-tensor base
weight by value

##### What broke

unslothai#18434 re-rounds a rounded QAT base weight that was rewritten after
preparation. It detects the rewrite from `(data_ptr, _version)`. An
inference tensor (built under `torch.inference_mode`, as base weights
shared with vLLM can be) has no version counter, so its state is
`(data_ptr, None)` before and after an in place reload.

Repro (CPU): prepare a real torchao int8 QAT LoRA model under
`torch.inference_mode()`, then `load_state_dict` a different base weight
into the same storage, still under inference mode.
- The post-load hook and a later `round_frozen_qat_weights` both treat
the weight as unchanged.
- The raw incoming weight stays in service with fake quantization off.
- It is 0.0162 away (max abs) from per call fake quantization of the
same weight.

The parent behaves the same way.

##### Fix

For an unversioned weight whose `(pointer, None)` state did not change,
compare its values with the checksum recorded at rounding time. A
mismatch is handled like a versioned rewrite: the quantizer comes back
and the weight is rounded again, in place under inference mode.
Versioned weights take exactly the old path. The extra checksum runs
only for inference-tensor weights, on load and on
`round_frozen_qat_weights`.

##### Tests

New `tests/test_qat_round_inference_reload.py` (CPU, asserts it imports
its own tree):
- An inference weight reloaded through `load_state_dict` or `copy_` then
`round_frozen_qat_weights` matches `UNSLOTH_QAT_ROUND_INPLACE=0`
bitwise, and the quantizer is off again (rounded in place).
- An unchanged inference weight is not rounded twice. int8 rounding is
not idempotent, so a second rounding would show.

| Arm | Result (new file + `tests/test_qat_round_rewrite.py` +
`tests/test_qat_weight_memo_guards.py`) |
|---|---|
| origin/main 635532f | 2 failed, 28 passed, 1 skipped |
| this branch | 30 passed, 1 skipped |

##### Not covered

Not run end to end with `fast_inference=True` and a live vLLM engine.

## QAT round: cross-recipe state_dict loads keep the target fake
quantizer (follows up unslothai#18434)

#### QAT round: name the fake quantization recipe in the rounded-weight
marker

##### What broke

unslothai#18434 marks a rounded QAT base weight in `state_dict()` metadata with a
checksum of its values. A load whose incoming weight matches the marker
is kept as already rounded. The marker does not say which grid the
values were rounded to.

Repro (CPU, real torchao QAT layers):
1. Load an int8-prepared model's `state_dict()` into an int4-prepared
model.
2. The checksum matches, so the destination keeps the int8-rounded
values verbatim with its int4 quantizer off.
3. Its output differs from per call int4 fake quantization of the same
weights (up to 0.0059 on the weight).

The reverse direction behaves the same. The parent also left the
destination disabled.

##### Fix

The marker now carries the quantizer type and its config repr (dtype,
granularity, mapping, precision). A marked weight from another recipe
fails the check and is rounded for this module like any new weight.
Same-recipe loads, including through `torch.save` /
`torch.load(weights_only = True)`, are still kept as is. Markers written
by the previous format no longer match, so those loads are rounded again
(the pre-marker behaviour).

##### Tests

New `tests/test_qat_round_recipe_marker.py` (CPU, asserts it imports its
own tree): int8 to int4 and int4 to int8, in memory and through
`torch.save` / `torch.load`. The destination must match
`UNSLOTH_QAT_ROUND_INPLACE=0` bitwise and end with its quantizer off.

| Arm | Result (new file + `tests/test_qat_round_rewrite.py` +
`tests/test_qat_weight_memo_guards.py`) |
|---|---|
| origin/main 635532f | 4 failed, 27 passed, 1 skipped |
| this branch | 31 passed, 1 skipped |

## NF4 dequant cache: inference-tensor scales and packed weights
(follows up unslothai#18433)

#### NF4 dequant cache: read each scale's version on its own; never
cache an inference packed weight

##### What broke

unslothai#18433 keys a cached dense NF4 weight on the address and version of
every scale tensor (`_scales_key`). When any of them was an inference
tensor (no version counter), the whole key fell back to `(absmax
pointer, None)`. That dropped the versions of the ordinary scales too.

Repro (CPU, real bitsandbytes nested NF4 state):
1. Make only `offset` an inference tensor and admit the weight to the
cache.
2. Double `state2.absmax` in place, outside inference mode.
3. The next lookup is a hit and returns the old dense weight, 1.47 away
(max abs) from a fresh decode. Making `absmax` the inference tensor
instead behaves the same.

Separately, an inference packed weight raised `RuntimeError: Inference
tensors do not track version counter` on admission.

No default training path was found that builds these states. They need
weights or scales created under `torch.inference_mode` that outlive it.

##### Fix

- `_version(t)` returns `None` for an inference tensor and `t._version`
otherwise. `_scales_key` reads it per tensor, so one inference tensor no
longer hides writes to the others.
- `_lookup` decodes an inference packed weight afresh instead of
admitting it.

The ordinary path is unchanged apart from one `is_inference()` call per
tensor on the hit path, which is host only.

##### Tests

New `tests/test_nf4_dequant_cache_inference_tensors.py` (CPU, reuses the
scales test fixtures, asserts it imports its own tree):
- An inference `offset` or `absmax` with an in place write to
`state2.absmax` is served fresh.
- An inference packed weight is decoded and not admitted.

| Arm | Result (new file + the three existing
`tests/test_nf4_dequant_cache*.py`) |
|---|---|
| origin/main 635532f | 3 failed, 42 passed |
| this branch | 45 passed |

## Not proven here

GPU runs of the QAT reload paths and the NF4 cache with inference
tensors; the double rounding after a safetensors round trip described in
unslothai#18434 is unchanged.
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