Skip to content

QAT LoRA: round the frozen base onto the fake quantization grid once, in place - #18339

Merged
danielhanchen merged 6 commits into
mainfrom
qat-round-inplace
Nov 18, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
qat-round-inplace

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

With qat_scheme + LoRA the base weight is frozen, yet torchao's weight_fake_quantizer recomputes fake_quant(W) for every base Linear on every forward. For the weight-only schemes (int4, int8, cactus) that output depends on W alone, so this PR writes fake_quant(W) into W once 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=True GRPO with QAT. vLLM shares the base weight storage with the trainer (checked: all 197 HF base weights of Qwen3-0.6B keep their data_ptr through 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 optimises fake_quant(W) + BA, a large train / rollout mismatch that nothing guards or corrects (Unsloth leaves vllm_importance_sampling_correction off by default). After rounding both read the same tensor.

What changes

  • New unsloth/models/_qat_round.py, called at the end of _prepare_model_for_qat.
  • Rounded: the base_layer of a PEFT LoRA layer whose weight is frozen, a plain tensor, on the accelerator, and not sharing memory with another parameter or buffer.
  • Skipped, so these keep fake quantizing per call: activation schemes (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 tied lm_head would otherwise round the input embedding too).
  • The write is in place (copy_ under no_grad), so the storage and data_ptr are kept. That is what lets vLLM see the rounded values.
  • UNSLOTH_QAT_ROUND_INPLACE=0 turns it off. The engagement count is recorded as qat_round_inplace in unsloth.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 by sampling/sampling_logp_difference/* for each of the 3 steps.

arm mean abs diff max abs diff IS ratio min / max
bf16, no QAT (floor) 0.025, 0.024, 0.027 0.24, 0.23, 0.23 0.80 / 1.27
int4, main 0.742, 0.613, 0.760 9.84, 5.22, 8.21 0.0001 / 3.0 (clipped)
int4, this PR 0.023, 0.024, 0.024 0.24, 0.25, 0.29 0.75 / 1.28
int8, main 0.059, 0.055, 0.058 0.52, 0.81, 0.75 0.47 / 2.25
int8, this PR 0.023, 0.023, 0.023 0.26, 0.25, 0.27 0.77 / 1.28
cactus, main 0.038, 0.034, 0.037 0.45, 0.37, 0.47 0.63 / 1.57
cactus, this PR 0.024, 0.024, 0.024 0.24, 0.22, 0.20 0.79 / 1.24
fp16 (T4 numerics), no QAT 0.0030, 0.0031, 0.0032 0.04 0.97 / 1.04
fp16 int4, main 0.774, 0.659, 0.788 10.3, 8.5, 12.6 0.0 / 3.0
fp16 int4, this PR 0.0031, 0.0031, 0.0031 0.03 0.96 / 1.03

On main with int4, these are the per-step counts out of about 1000 completion tokens:

  • 15 to 33 tokens (bf16 and fp16) have a ratio above 3. Unsloth's token_truncate clips them when the correction is turned on.
  • 153 to 229 tokens have a ratio below 1/3.
  • Every one of the 8 sequences has a sequence ratio below 1e-4. TRL's 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=0 the run reproduces main exactly: same rollouts and same metrics.

GRPO scores with the raw lm_head.weight. Qwen3's tied lm_head is skipped here, so it adds no mismatch.

Numerics and exports

  • Eager decoder (UNSLOTH_BLOCK_COMPILE=0), Qwen3-0.6B, bf16. For int4, int8 and cactus, UNSLOTH_QAT_ROUND_INPLACE=0 vs on gave bitwise equal results for all of these:
    • the loss and every LoRA gradient of two fixed-batch passes
    • all three AdamW step losses
    • the LoRA weights after training
    • the exports: save_pretrained (392 / 392 tensors), save_pretrained_merged(merged_16bit) (310 / 310) and save_pretrained_torchao (int8 / cactus, 702 / 702)
  • Per forward, the weight fake quant calls drop from 393 to 1 (the tied lm_head).
  • The exports are unchanged because the merged writer (merge_and_overwrite_lora) reads the base from the checkpoint, not from memory.
  • Kill switch: main vs this PR with =0 is bitwise equal everywhere, exports included.
  • Compiled decoder blocks (torch >= 2.11, the default there) are not bitwise equal to main. The compiled graph's in-graph fake quant differs from the eager one:
    • int4: 0.02% of weight elements, at most one grid step
    • int8: 27%
    • cactus: 38%
  • This PR stores the eager result, which is what vLLM serves. For int8 and cactus it is also exactly what torchao's real quantization dequantizes to: 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).
  • Idempotence: int4 (asymmetric min / max, fp32 scales) is idempotent, fake_quant(fake_quant(W)) == fake_quant(W) bitwise on all 196 weights in bf16 and fp16. int8 and cactus are not:
    • The symmetric scale is absmax / 127.5, computed in the weight dtype. The extreme element lands near ±127.46 and rounds to ±127, so absmax shrinks and the recomputed scale moves every code.
    • In bf16 that changes 49% of elements for int8 and 43% for cactus. No fixed point is reached in 20 passes.
    • This is why the PR turns the quantizer off instead of relying on re-quantizing the stored weight.
  • What does change in memory: after quantize_(model, QATConfig(step = "convert")) or a manual merge_and_unload(), the base is now the fake quantized weight the model trained against, not the unrounded one. The QAT notebook's post-convert generate therefore 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 2048
  • FineTome SFT with train_on_responses_only, adamw_8bit, int4
  • A fresh process and fresh compile caches for every run. Arms are interleaved, 3 runs each. The metric is the median step time of steps 5 to 12; speedups use the median of the 3 runs.
  • Arms: main = 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.
torch arm s/step (3 runs) A/A spread vs main peak allocated
2.10.0 main 3.752, 3.773, 3.775 0.6% 1.00x 8.15 GB
2.10.0 #18286 memo only 1.272, 1.268, 1.308 3.1% 2.97x 10.67 GB
2.10.0 this PR only 1.629, 1.669, 1.673 2.7% 2.26x 8.15 GB
2.10.0 both 1.253, 1.279, 1.272 2.1% 2.97x 8.09 GB
2.14.1 main 1.366, 1.367, 1.383 1.3% 1.00x 8.15 GB
2.14.1 #18286 memo only 0.971, 0.990, 0.968 2.3% 1.41x 8.09 GB
2.14.1 this PR only 1.378, 1.371, 1.334 3.3% 1.00x 8.15 GB
2.14.1 both 0.940, 0.957, 0.934 2.4% 1.45x 8.09 GB
  • On torch 2.10 rounding alone gives 2.26x with no extra memory. The remaining gap to the memo is the tied lm_head, which still fake quantizes per call.
  • Combined with QAT LoRA: fake-quantize the frozen base weight once instead of every forward #18286, the speed is the memo's and the peak is main's: 8.09 GB instead of 10.67 GB. The memo then only caches the lm_head (0.62 GB) instead of 3.4 GB of decoder weights.
  • On torch 2.14 the decoder fake quant runs inside the compiled blocks and is cheap, so rounding alone is inside noise, and "both" vs memo (3.4%) is inside A/A spread + 5%. The speed claim is therefore torch < 2.11 only.
  • The reason to ship is correctness, the fast_inference mismatch above.

Interaction with #18286

The two PRs merge cleanly (git merge-tree). With both:

  • Weight-only LoRA bases are rounded and their quantizers are off, so the memo skips them (it already skips disabled quantizers).
  • The memo still caches everything else: activation schemes, the tied lm_head, the int8-int4 embedding.
  • QAT LoRA: fake-quantize the frozen base weight once instead of every forward #18286 is merged; this branch is rebased on it and includes the follow-up: tests/test_qat_weight_memo.py sets UNSLOTH_QAT_ROUND_INPLACE=0 in its _model helper so those tests keep exercising the memo path. Both files pass together (29/29).

Tests

tests/test_qat_round_inplace.py runs on CPU in about 0.5 s and checks:

  • outputs and grads bitwise vs the kill switch for int4 / int8 / cactus in fp32 and bf16
  • the engagement count is 2 vs 0
  • the stored weight equals the quantizer's own output
  • the storage is kept, and a second call is a no-op
  • int8-int4 is untouched
  • tied, trainable and non-LoRA weights are skipped

It fails on main (module absent).

Not covered

  • A base weight rewritten in place after prepare is no longer fake quantized. vLLM's exact merged rollout fold / restore is fine. A later LoRA-GA residual adapter load or user code that rewrites the base would need round_frozen_qat_weights(model) again.
  • The tied lm_head keeps fake quantizing per call in SFT. With QAT LoRA: fake-quantize the frozen base weight once instead of every forward #18286 it is cached.
  • Real 2-GPU / FSDP2 runs were not exercised (DTensors are skipped by design).
  • Only Qwen3 (0.6B, 1.7B) was run.

… 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 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-18T15:41:04.938778Z 0cb0068 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.

@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: 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".

Comment thread unsloth/models/_qat_round.py Resolved
@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: 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".

Comment thread unsloth/models/_qat_round.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. You're on a roll.

Reviewed commit: 0cb00689b6

ℹ️ 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 4b027b4 into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the qat-round-inplace branch November 18, 2026 17:10
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 19, 2026
…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.
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