Repository navigation
QAT: weight memo guards for inference mode, side streams and static scales; re-round after a base weight reload - #18434
Conversation
… current stream The memo read w._version before its inference mode guard, so a frozen weight built under torch.inference_mode raised. Static scale quantizers read their own scale / zero point, which the key did not cover, so a changed scale served the old fake quantized weight. A cached CUDA tensor carries no event, so a second stream could be served it before the producer stream wrote it; the key now includes the current stream, so a cached weight is only served where it was produced. (cherry picked from commit dc55d27bb70a02001dbffa0408c7aa0135f43fd3)
A rounded base keeps its quantizer off and is flagged, so loading a different base weight afterwards (load_state_dict of a full checkpoint, a residual rebase) left it unquantized, and round_frozen_qat_weights skipped it as already rounded. Rounding now records the weight's data_ptr and version. A load_state_dict post hook turns the quantizer back on when the loaded weight differs from the rounded one and rounds it again in place; round_frozen_qat_weights rounds again any flagged weight rewritten since. Reloading the rounded values themselves, adapter only loads, PEFT merge / unmerge and copies keep the rounded weight. (cherry picked from commit a9ef1eb0fca576766bba57ac7298bb4ecbeb6741)
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 Summary: 🔄 RunningThis 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: 71d975927a
ℹ️ 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".
…load load_state_dict only recognised the destination's own rounded values, so a state_dict from another prepared model with different base weights was fake quantized a second time, which moves int8 / cactus weights. state_dict() now records a checksum of each rounded weight in the module's state dict metadata (no new keys, kept by torch.save), and a load whose weight still matches it is kept as is. An edited or replaced weight fails the checksum and is rounded again as before.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1bc4d0e54f
ℹ️ 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ce8720c493
ℹ️ 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".
…alues still match
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 608e86e61f
ℹ️ 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e13d6e9327
ℹ️ 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".
… (copies and unpickled models too)
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bc51471bd2
ℹ️ 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".
…e cast, accept it when the cast is exact
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6372d44879
ℹ️ 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".
…ng, MLX batch sizes, QAT CUDA skip) (#18471) ## Summary Four tests fail on `main` in the "Repo tests (CPU, studio)" shard, so every PR that runs it is red (seen on the staging runs of #18353 and others). Reproduced on `main` at `415cdcf1be`: ``` FAILED tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe FAILED tests/studio/test_model_picker_contracts.py::test_batch_sizes_setting_wired_end_to_end FAILED tests/studio/test_model_picker_contracts.py::test_batch_sizes_reach_an_api_load_through_the_server_mirror FAILED tests/studio/test_chat_ui_picker_collapsed_row.py::test_a_loaded_model_still_opens_the_picker_collapsed ``` Each was attributed to the PR that changed the code it reads, and each was checked for whether the PR or the test is wrong. ## Root causes and changes ### Picker collapsed after a load (#18445): test was wrong #18445 added the "Show full model list" setting, so the load effect now calls `setExpanded(useChatRuntimeStore.getState().pickerExpandLoaded)` instead of a literal `?? false`. The setting defaults to off, so a fresh browser (every CI driver) still opens the picker collapsed, which is what this test protects: the drivers' expand click is still needed. `test_a_loaded_model_still_opens_the_picker_collapsed` now accepts either form, and when the setting drives it, also asserts the store default is `loadBool(PICKER_EXPAND_LOADED_KEY, false)`. Flipping that default to `true` fails the test, which the old literal check could not see. ### Batch sizes sent on a load (#18426): test was wrong #18426 brought MLX up to GGUF parity, so `n_batch` / `n_ubatch` are now sent for `(target.isGguf || mlx)` and copied for MLX overrides too. GGUF behaviour is unchanged; the tests pinned the old GGUF-only literal. - `test_batch_sizes_setting_wired_end_to_end`: matches the gate with a regex that allows widening to MLX but still requires `target.isGguf` and "only when set". Dropping the gate (sending the fields to every engine) fails it. - `test_batch_sizes_reach_an_api_load_through_the_server_mirror`: replaces the source-text check on the GGUF block with a behavioural check through `_override_load_kwargs`, which the test already imports. Dropping `n_ubatch` from the copied keys fails it. ### QAT stream test skip guard (#18434): PR was wrong `tests/test_qat_weight_memo_guards.py` gated `test_cached_weight_not_served_to_another_stream` on `torch.cuda.is_available()`, which `tests/_zoo_aggressive_cuda_spoof.py` patches to `True` process-wide, so on a CPU runner the test un-skips and calls `.cuda()` when it shares a session with the spoofing suites. The existing guard caught this. The skip now gates on `has_real_cuda()` first, as the other CUDA-only tests do. ## Testing - The four tests plus their files: `241 passed, 1 skipped` on this branch; the same four fail on `main`. - Sabotage, each against this branch: - store default `pickerExpandLoaded` set to `true`: the picker test fails; - `n_batch` sent without the GGUF/MLX gate: the end-to-end batch test fails; - `n_ubatch` dropped from the backend override copy: the server-mirror test fails; - QAT skip guard reverted: the skip-guard test fails.
…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.
QAT weight memo: skip inference tensors and static scales, key on the current stream
Summary
Three key / guard fixes in the QAT frozen weight cache added by #18286 (
unsloth/models/_qat_weight_memo.py), one file:torch.inference_mode()(an inference tensor, for example a base weight that shares storage with vLLM) made every training mode QAT forward raiseRuntimeError: Inference tensors do not track version counter. The parent of QAT LoRA: fake-quantize the frozen base weight once instead of every forward #18286 ran the same call.IntxFakeQuantizer(is_dynamic=False) whosescale/zero_pointchanged while the weight stayed the same got the old fake quantized weight back (max abs output error 0.0184 on the reviewer repro; the parent recomputed it).Root cause
_weight_keyreadw._versionbefore the inference mode bypass in_memo_forward, and inference tensors have no version counter.Fix
_weight_keyreturns no key (pass through, never cached) for inference tensors and for static scale quantizers, the same exclusion_qat_round.pyandtp_native.pyalready make. No built-inqat_schemeuses static scales.(stream_id, device_index)on accelerators, nothing on CPU), so a cached weight is served only on the stream that produced it. A call on another stream recomputes, as without the cache. Single stream training still hits (checked in the test).torch.compile(the trace still calls the original forward), no host sync added, kill switchUNSLOTH_QAT_WEIGHT_MEMO=0unchanged.Tests
New
tests/test_qat_weight_memo_guards.py, one flip test per finding plus a check that dynamic schemes still hit the cache. Base arm = detachedorigin/main(8ef13a7) with only the new test copied in; each arm asserts it imports its own tree.test_inference_built_weight_does_not_raise(CPU)Inference tensors do not track version counter)test_static_scale_change_is_not_served_stale(CPU)test_cached_weight_not_served_to_another_stream(B200, torch 2.14.1)test_dynamic_scheme_still_cachedExisting
tests/test_qat_weight_memo.py+tests/test_qat_round_inplace.py: 31 passed on both arms (torch 2.14.1). On torch 2.10 CPU: 23 passed, 2 skipped (CUDA only) for the memo files on this branch.Not proven here
fast_inference=Truehands the trainer inference tensors through a path that reaches the memo was not run end to end here; the CPU repro builds the model underinference_modedirectly.automode CPU entries still have no budget (each cached weight is a second dense copy in host RAM). Not changed here: the existing tests treat that as the design, and bounding host memory needs its own design.w, soquantizer(x=...)keyword calls fail after install. Not changed here.QAT in place round: fake quantize a rewritten base weight again
Summary
#18339 (
unsloth/models/_qat_round.py) writesfake_quant(W)into a frozen LoRA base weight once and turns its quantizer off. If a different base weight is loaded afterwards (a fullload_state_dict, an older full checkpoint, a residual rebase), the quantizer stays off, so that weight is no longer fake quantized at all, andround_frozen_qat_weights(model)returns 0 because the module is flagged as rounded. On the reviewer repro the output after the reload differed from the parent by up to 0.2565. This PR fake quantizes a rewritten weight again.Root cause
round_frozen_qat_weightssetsquantizer.enabled = Falseand_unsloth_qat_rounded = Trueand later skips any flagged module. Nothing recorded which tensor state was rounded, so a later write could not be told apart from the rounded weight.Fix
(data_ptr, version)on the quantizer and registersload_state_dictpre / post hooks on that module (no forward hook, nothing in the compiled path, no per forward cost).load_state_dict, if the loaded weight differs from the rounded one, the quantizer is turned back on and, when the same storage was written in place, the weight is rounded again in place (so vLLM's shared storage stays in sync). A new tensor (assign=True) keeps per call fake quant until the nextround_frozen_qat_weights.round_frozen_qat_weights(model)now rounds again any flagged weight whose data_ptr or version changed since it was rounded..data), and deep copies (the record resets and adopts the copied tensor).UNSLOTH_QAT_ROUND_INPLACE=0still disables rounding.Tests
New
tests/test_qat_round_rewrite.py. The reference is the same model prepared withUNSLOTH_QAT_ROUND_INPLACE=0(the per call path), given the same load. Base arm = detachedorigin/main(8ef13a7) with only the new test copied in; each arm asserts it imports its own tree.test_load_state_dict_of_a_new_weight(int4 / int8, module and whole model, 4 cases)test_round_again_after_in_place_rewritetest_unchanged_weights_stay_rounded(own state reload, adapter only load, deepcopy)With
tests/test_qat_round_inplace.pyandtests/test_qat_weight_memo.py: main 5 failed / 33 passed, this branch 38 passed (torch 2.14.1 CPU); this branch on torch 2.10 CPU: 18 passed for the round files.Not proven here
fast_inference=Truerun of the reload path.load_state_dict(user code, a residual rebase) is only picked up whenround_frozen_qat_weights(model)is called again, as the QAT LoRA: round the frozen base onto the fake quantization grid once, in place #18339 description says.merge_adapter()now givesfake_quant(W) + deltainstead offake_quant(W + delta), and turning the quantizer off after prepare (a delayed QAT warmup done by hand through torchao) cannot give back the unrounded weight. Unsloth has no delayed QAT option; such a schedule needsUNSLOTH_QAT_ROUND_INPLACE=0.Loading rounded checkpoints (added during review)
A prepared model's
state_dict()marks each rounded base weight in the state dict's per-module metadata with an exact, device independent checksum of its rounded values (recorded at rounding time and whenever a rounded weight is adopted). Onload_state_dict, an incoming weight that matches its marker (checked before any dtype cast, and only accepted if the cast is exact) is kept as is; anything else is rounded again. A device move (model.cpu(),.to()) keeps the mark when the values still match, and callinground_frozen_qat_weightsagain after a move is a no-op. No new state dict keys, so exported files are unchanged.Known limitation: formats that do not carry PyTorch state dict metadata (for example
safetensors.torch.save_file(model.state_dict(), path)) lose the mark. Such a checkpoint is then treated like any other incoming base weight and rounded again, which can move int8 / cactus values slightly (their scales are recomputed from the already rounded values). Persisting the mark there would need an extra tensor key per rounded layer, which changes exported checkpoints and breaks strict loads into unprepared models, so it is out of scope here.