Repository navigation
QAT LoRA: round the frozen base onto the fake quantization grid once, in place - #18339
Conversation
… in place With a weight-only qat_scheme (int4, int8, cactus) the frozen base of every LoRA layer is fake quantized on every forward. Write fake_quant(W) into W once at prepare time and switch the weight quantizer off: the trainer reads bitwise the same weight it computed per call (eager), with no per call cost and no extra copy. With fast_inference the base storage is shared with vLLM, so rollouts now sample from the same fake quantized weights the trainer optimises. Before, vLLM sampled from the unrounded weights (Qwen3-0.6B int4 GRPO: mean |logp_train - logp_rollout| 0.61-0.76 vs 0.023-0.028 after, the bf16 floor). Only PEFT base_layer weights that are frozen, plain, on the accelerator and not sharing memory with another parameter (tied lm_head) are rounded; activation schemes, nvfp4 / mxfp8, full fine-tuning and plain Linears keep fake quantizing per call. Merged / torchao / adapter exports read the base from the checkpoint and are unchanged. UNSLOTH_QAT_ROUND_INPLACE=0 turns it off.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0440a66a9
ℹ️ 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".
…rebases in place [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d6275decb0
ℹ️ 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".
…ase outside the quantizer [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…cales; re-round after a base weight reload (unslothai#18434) ## 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 unslothai#18286 (`unsloth/models/_qat_weight_memo.py`), one file: 1. A frozen weight built under `torch.inference_mode()` (an inference tensor, for example a base weight that shares storage with vLLM) made every training mode QAT forward raise `RuntimeError: Inference tensors do not track version counter`. The parent of unslothai#18286 ran the same call. 2. A static scale `IntxFakeQuantizer` (`is_dynamic=False`) whose `scale` / `zero_point` changed 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). 3. A cached CUDA tensor was served to any stream. A consumer on a second stream could read it before the producer stream had written it: 16,320 of 16,384 elements wrong on B200. ### Root cause - `_weight_key` read `w._version` before the inference mode bypass in `_memo_forward`, and inference tensors have no version counter. - The key covered the weight, autocast and range learning, but not static quantizer state. - The memo stores the producer's output tensor with no event and no stream identity, and the hit path returns it as is. ### Fix - `_weight_key` returns no key (pass through, never cached) for inference tensors and for static scale quantizers, the same exclusion `_qat_round.py` and `tp_native.py` already make. No built-in `qat_scheme` uses static scales. - The key now includes the current stream (`(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). - No change under `torch.compile` (the trace still calls the original forward), no host sync added, kill switch `UNSLOTH_QAT_WEIGHT_MEMO=0` unchanged. ### 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 = detached `origin/main` (8ef13a7) with only the new test copied in; each arm asserts it imports its own tree. | test | main | this branch | |---|---|---| | `test_inference_built_weight_does_not_raise` (CPU) | FAILED (`Inference tensors do not track version counter`) | PASSED | | `test_static_scale_change_is_not_served_stale` (CPU) | FAILED | PASSED | | `test_cached_weight_not_served_to_another_stream` (B200, torch 2.14.1) | FAILED (16,320 mismatched elements) | PASSED | | `test_dynamic_scheme_still_cached` | PASSED | PASSED | Existing `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 - The stream fix was checked on B200 (sm100) only, correctness only, no timing. - Whether `fast_inference=True` hands the trainer inference tensors through a path that reaches the memo was not run end to end here; the CPU repro builds the model under `inference_mode` directly. - In `auto` mode 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. - The class level wrapper still names its argument `w`, so `quantizer(x=...)` keyword calls fail after install. Not changed here. ## QAT in place round: fake quantize a rewritten base weight again ### Summary unslothai#18339 (`unsloth/models/_qat_round.py`) writes `fake_quant(W)` into a frozen LoRA base weight once and turns its quantizer off. If a different base weight is loaded afterwards (a full `load_state_dict`, an older full checkpoint, a residual rebase), the quantizer stays off, so that weight is no longer fake quantized at all, and `round_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_weights` sets `quantizer.enabled = False` and `_unsloth_qat_rounded = True` and 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 - Rounding records the weight's `(data_ptr, version)` on the quantizer and registers `load_state_dict` pre / post hooks on that module (no forward hook, nothing in the compiled path, no per forward cost). - On `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 next `round_frozen_qat_weights`. - `round_frozen_qat_weights(model)` now rounds again any flagged weight whose data_ptr or version changed since it was rounded. - Unchanged: loading the rounded values themselves (int8 / cactus fake quant is not idempotent, so these must not be rounded twice), adapter only loads (Trainer resume), PEFT merge / unmerge and vLLM fold / restore (both write through `.data`), and deep copies (the record resets and adopts the copied tensor). `UNSLOTH_QAT_ROUND_INPLACE=0` still disables rounding. ### Tests New `tests/test_qat_round_rewrite.py`. The reference is the same model prepared with `UNSLOTH_QAT_ROUND_INPLACE=0` (the per call path), given the same load. Base arm = detached `origin/main` (8ef13a7) with only the new test copied in; each arm asserts it imports its own tree. | test | main | this branch | |---|---|---| | `test_load_state_dict_of_a_new_weight` (int4 / int8, module and whole model, 4 cases) | 4 FAILED | 4 PASSED | | `test_round_again_after_in_place_rewrite` | FAILED | PASSED | | `test_unchanged_weights_stay_rounded` (own state reload, adapter only load, deepcopy) | PASSED | PASSED | With `tests/test_qat_round_inplace.py` and `tests/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 - CPU only; no GPU or vLLM `fast_inference=True` run of the reload path. - A rewrite done in place outside `load_state_dict` (user code, a residual rebase) is only picked up when `round_frozen_qat_weights(model)` is called again, as the unslothai#18339 description says. - Behaviour changes unslothai#18339 documented on purpose are left as they are: an in memory `merge_adapter()` now gives `fake_quant(W) + delta` instead of `fake_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 needs `UNSLOTH_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). On `load_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 calling `round_frozen_qat_weights` again 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.
With
qat_scheme+ LoRA the base weight is frozen, yet torchao'sweight_fake_quantizerrecomputesfake_quant(W)for every base Linear on every forward. For the weight-only schemes (int4,int8,cactus) that output depends onWalone, so this PR writesfake_quant(W)intoWonce at prepare time and switches the quantizer off. The trainer then reads exactly the tensor it used to recompute per call, with no per call cost and no extra copy.It also fixes
fast_inference=TrueGRPO with QAT. vLLM shares the base weight storage with the trainer (checked: all 197 HF base weights of Qwen3-0.6B keep theirdata_ptrthrough the torchao module swap and sit inside vLLM's parameters, so there is no copy). On main vLLM samples from the unrounded weights while the trainer optimisesfake_quant(W) + BA, a large train / rollout mismatch that nothing guards or corrects (Unsloth leavesvllm_importance_sampling_correctionoff by default). After rounding both read the same tensor.What changes
unsloth/models/_qat_round.py, called at the end of_prepare_model_for_qat.base_layerof a PEFT LoRA layer whose weight is frozen, a plain tensor, on the accelerator, and not sharing memory with another parameter or buffer.int8-int4,fp8-int4,fp8-fp8),nvfp4/mxfp8, range learning or static scales, full fine-tuning, plain Linears outside LoRA (lm_head, frozen layers of a full fine-tune), and tied weights (a tiedlm_headwould otherwise round the input embedding too).copy_underno_grad), so the storage anddata_ptrare kept. That is what lets vLLM see the rounded values.UNSLOTH_QAT_ROUND_INPLACE=0turns it off. The engagement count is recorded asqat_round_inplaceinunsloth.precision.engaged(model).Train / rollout mismatch (B200, correctness only)
Setup:
unsloth/Qwen3-0.6B, LoRA r=16,fast_inference=True, 3 GRPO steps, 8 generations x 128 tokens, temperature 1, no top-k / top-p / min-p. The table compares the per-token log-prob of the GRPO trainer's own scorer with vLLM's sampling log-prob, as logged bysampling/sampling_logp_difference/*for each of the 3 steps.On main with int4, these are the per-step counts out of about 1000 completion tokens:
token_truncateclips them when the correction is turned on.sequence_mask(C_max = 3) masks none of them, but it scales their loss by roughly 0.With this PR there are 0 tokens above 3 and 0 sequences below 1/3, which is the bf16 floor. With
UNSLOTH_QAT_ROUND_INPLACE=0the run reproduces main exactly: same rollouts and same metrics.GRPO scores with the raw
lm_head.weight. Qwen3's tiedlm_headis skipped here, so it adds no mismatch.Numerics and exports
UNSLOTH_BLOCK_COMPILE=0), Qwen3-0.6B, bf16. For int4, int8 and cactus,UNSLOTH_QAT_ROUND_INPLACE=0vs on gave bitwise equal results for all of these:save_pretrained(392 / 392 tensors),save_pretrained_merged(merged_16bit)(310 / 310) andsave_pretrained_torchao(int8 / cactus, 702 / 702)lm_head).merge_and_overwrite_lora) reads the base from the checkpoint, not from memory.=0is bitwise equal everywhere, exports included.dequantize(quantize(W)) == fake_quant(W)bitwise on the 3 weights checked per scheme. Step 1 loss moves by 3e-4 to 1e-3 (Qwen3-0.6B, about 11.9).fake_quant(fake_quant(W)) == fake_quant(W)bitwise on all 196 weights in bf16 and fp16. int8 and cactus are not:absmax / 127.5, computed in the weight dtype. The extreme element lands near ±127.46 and rounds to ±127, soabsmaxshrinks and the recomputed scale moves every code.quantize_(model, QATConfig(step = "convert"))or a manualmerge_and_unload(), the base is now the fake quantized weight the model trained against, not the unrounded one. The QAT notebook's post-convertgeneratetherefore shows the quantized base. Saved checkpoints are unchanged.Speed and memory (Colab L4, notebook recipe)
Setup:
unsloth/Qwen3-1.7B, r=16 on all linears,use_gradient_checkpointing="unsloth", bs 1 x GA 4, max_seq_length 2048train_on_responses_only, adamw_8bit, int4main= c0698e7. The other arms are main plus QAT LoRA: fake-quantize the frozen base weight once instead of every forward #18286 plus this PR, toggled with the two kill switches.lm_head, which still fake quantizes per call.lm_head(0.62 GB) instead of 3.4 GB of decoder weights.Interaction with #18286
The two PRs merge cleanly (
git merge-tree). With both:lm_head, the int8-int4 embedding.tests/test_qat_weight_memo.pysetsUNSLOTH_QAT_ROUND_INPLACE=0in its_modelhelper so those tests keep exercising the memo path. Both files pass together (29/29).Tests
tests/test_qat_round_inplace.pyruns on CPU in about 0.5 s and checks:It fails on main (module absent).
Not covered
round_frozen_qat_weights(model)again.lm_headkeeps fake quantizing per call in SFT. With QAT LoRA: fake-quantize the frozen base weight once instead of every forward #18286 it is cached.