Repository navigation
NF4 dequant cache: no pre-hook on models without NF4 weights, keep autocast on the compiled route, invalidate on in-place scale writes - #18433
Conversation
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)
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
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
transformersTrainer afterimport unslothpaid a host read of the attention mask on every forward, for a cache it can never use.Root cause
#18285 (merge 567f979) appends
UnslothDequantCacheScopetotransformers.trainer.DEFAULT_CALLBACKS. Itson_train_beginregisters_model_pre_hookon whatever model is trained. For a 2D attention mask the hook calls_padded, which runsbool(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: oneaten.is_nonzero/_local_scalar_densecall 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
_has_nf4_weights(model): one pass over the modules pertrain(). It looks for a bitsandbytes NF4 quant state on a parameter, or on aLinear4bit's ownquant_statecopy (FSDP2 all-gathers the packed bytes into a Parameter without one).on_train_beginleaves the scope off (_ACTIVE = 0, no hook) when the trained model has none, so nothing is cached for that run.Tests
New
tests/test_nf4_dequant_cache_dense_model.py(CPU; each arm prints thedequant_cache.__file__it imported):1 failed, 2 passed(dense model:assert 1 == 0host reads per forward).3 passed. The NF4 cases (quant state on the parameter, or only on theLinear4bit) still install the hook and still do the one mask read.tests/test_nf4_dequant_cache.pypasses 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
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.compilewith autocast,matmul_loraon 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 atorch.matmulthat autocast casts to the autocast dtype, but autocast does not see inside the op and its fake returnsX.dtype. Measured on B200, torch 2.14.1, on origin/main:infin default,fullgraph=Trueandfullgraph=True, dynamic=True; eager gives finite bf16 524288.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_loracall (for example a usertorch.compilearound the fused LoRA path under a mismatchedtorch.autocast). Default FastLanguageModel training keeps the activation, quant state and autocast dtypes equal (patch_model_and_tokenizercastsquant_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, castXto the autocast dtype, as autocast would fortorch.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 toX.dtypewhen they differ, so the result no longer depends on whether autocast is active when the compiled graph runs.unsloth::lora_first_addmm, which was already an opaque op that autocast did not cast.nf4_cached_addmm_is unchanged (an in-placeaddmm_, which autocast does not cast).Tests
New
tests/test_nf4_dequant_cache_autocast.py(CUDA; compiled vs eagermatmul_loraunder autocast, asserts the traced op route ran). Both arms on one B200 lease, each arm importing its own tree (dequant_cache.__file__printed):5 failed, 34 passed(3x fp16infvs bf16, 1x bf16 vs fp16 dtype, 1x fp32 dtype mismatch RuntimeError).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
torch.is_autocast_enabled(device)andtorch.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.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/_missinunsloth/kernels/dequant_cache.py). An in-place write toabsmax(for examplequant_state.absmax.mul_(2)) keeps its address, so the hit still matched. With nested quantization (compress_statistics=True), the decode also readsstate2.absmaxandoffset, 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
_scales_key(absmax, absmax2, offset): thedata_ptr()and_versionofabsmaxand, when present, of the nestedabsmax2andoffset. It is stored in the entry slot that heldabsmax.data_ptr()and compared on every hit and in_miss.dequantizepassesquant_state.state2.absmaxandquant_state.offset._dense_from_parts(the traced op path) passes theabsmax2andoffsetit already receives.Tests
New
tests/test_nf4_dequant_cache_scales.py(CPU, real bitsandbytes NF4 states, faked memory reading; each arm prints thedequant_cache.__file__it imported):4 failed, 33 passed(absmax plain, absmax nested, state2.absmax and offset cases all served stale).37 passed(new test plus the existingtests/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
data_ptr,_version), with no device sync.code,state2.code) are still not tracked. These are constant codebooks.