Skip to content

QAT LoRA: fake-quantize the frozen base weight once instead of every forward - #18286

Merged
danielhanchen merged 8 commits into
mainfrom
qat-weight-memo
Nov 18, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
qat-weight-memo

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

QAT LoRA: fake quantize the frozen base weight once, not on every forward

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 call: the forward, the gradient checkpointing replay, and every gradient accumulation micro batch. For the int4 recipe that is about ten elementwise fp32 passes over the whole base model per call (Int4WeightFakeQuantizer._bf16_activations_forward: upcast, group amax / amin, sub, div, round, clamp, mul, add, downcast). The quantizer is a pure function of W (and its config), so this PR caches its output.

What changes

  • New unsloth/models/_qat_weight_memo.py, installed at the end of _prepare_model_for_qat (so FastLanguageModel, FastModel, vision and sentence transformer QAT paths all get it).
  • Each non-adapter weight_fake_quantizer gets a small cache in its __dict__; the torchao quantizer class forward is wrapped once at class level. An instance without a cache, or any call inside a torch.compile trace, runs the original forward untouched, so compiled graphs, guards and recompiles are exactly as before.
  • The cache is served only while the weight is the same unmodified tensor: same storage (weakref identity), storage offset, shape, stride, dtype, device, version counter, and the same autocast state. A weight is cached on its second call with the same tensor, so weights streamed in per forward (offload hooks) are never held.
  • PEFT merge / unmerge write the base weight through .data, which bumps no version counter, so the LoRA layer classes' merge / unmerge drop the cache of their base layer.
  • Never cached: weights that require grad (full fine-tuning QAT), range learning, tensor subclasses / DTensors, multi-process runs (FSDP reshards weights; DDP keeps the old path too), inference mode (an inference tensor cannot be saved for backward later). The cache is plain Python state, so it is not in state_dict, does not move with .to(), and is dropped by deepcopy / pickle.
  • Memory: the cache costs one extra copy of each cached weight. On CUDA / XPU it fills at most half of the memory that is free when the first copy is made; layers past that keep fake quantizing per call.
  • UNSLOTH_QAT_WEIGHT_MEMO=0 turns it off (kill switch), =1 lifts the memory cap, default auto.

Schemes: int4, int8, cactus, int8-int4 (incl. the untied fake quantized lm_head and the int8 embedding), fp8-int4, fp8-fp8. nvfp4 / mxfp8 quantize the weight inside their own matmul op and have no weight_fake_quantizer, so they are unchanged here.

Correctness

Loss and every LoRA gradient bitwise equal, in process, UNSLOTH_QAT_WEIGHT_MEMO=0 (twice, A/A bitwise) vs on (3 steps), Qwen3-0.6B cut to 4 layers, use_gradient_checkpointing="unsloth", B200 (sm100; correctness only). Weight fake quant computations per step (activation quantizers excluded), memo off then on for steps 1, 2, 3:

scheme dtype bitwise (3 steps) computations / step off -> on cached
int4 bf16 yes 57 -> 57, 1, 0 29 layers
int8-int4 bf16 yes 58 -> 58, 2, 0 30 incl. lm_head, embedding
fp8-int4 bf16 yes 57 -> 57, 1, 0 29
fp8-fp8 bf16 yes 57 -> 57, 1, 0 29
int8 bf16 yes 57 -> 57, 1, 0 29
cactus bf16 yes 57 -> 57, 1, 0 29
int4 fp16 yes 57 -> 57, 1, 0 29
int8-int4 fp16 yes 58 -> 58, 2, 0 30
nvfp4, mxfp8 bf16 yes (no change) 0 0

PEFT merge_adapter / unmerge_adapter then training again: logits and grads with the memo bitwise equal to memo off. On torch >= 2.11, where each decoder block is compiled as one region: same dynamo unique graph count (50) and 0 graph breaks on base and head; only the eager lm_head is cached.

tests/test_qat_weight_memo.py (CPU, about 2 s): bitwise outputs + grads with engagement counts for int4 / int8 / int8-int4 / cactus, refresh on an in-place weight change, on PEFT merge / unmerge and on a .data swap, no cache for trainable weights or inference mode, kill switch at prepare, torch.compile(fullgraph=True) frame count 1 and equal output, deepcopy / pickle. Fails on main (module absent); dropping the merge / unmerge invalidation makes the merge test fail.

Speed and memory (Colab, notebook recipe)

unsloth/Qwen3-1.7B, r=16 all linears, use_gradient_checkpointing="unsloth", bs 1 x GA 4, max_seq_length 2048, FineTome chat SFT with train_on_responses_only, adamw_8bit. Fresh process and fresh compile caches per run, base / head interleaved (B H H B B H), median step time of steps 5-14, 3 runs per arm.

GPU torch scheme main s/step (3 runs) this PR s/step (3 runs) A/A spread main / PR speedup peak allocated main -> PR cached
L4 2.10.0 int4 3.751, 3.753, 3.752 1.226, 1.210, 1.251 0.0% / 3.4% 3.06x 8.15 -> 10.68 GB 3.21 GB, 197 layers
L4 2.10.0 int8-int4 4.743, 4.732, 4.707 3.142, 3.088, 3.194 0.8% / 3.4% 1.51x 6.73 -> 9.85 GB 3.78 GB, 198 layers
T4 (fp16) 2.10.0 int4 5.494, 5.438, 5.435 1.759, 1.806, 1.797 1.1% / 2.6% 3.03x 8.15 -> 10.68 GB 3.21 GB, 197 layers
A100 80GB 2.10.0 int4 1.749, 1.737, 1.736 1.184, 1.201, 1.188 0.7% / 1.4% 1.46x 8.15 -> 10.68 GB 3.21 GB, 197 layers
A100 80GB 2.14.1 int4 0.980, 0.988, 0.976 0.922, 0.920, 0.936 1.2% / 1.8% 1.06x 8.15 -> 8.06 GB 0.58 GB, lm_head
A100 40GB 2.14.1 int8-int4 1.028, 1.037, 1.037 0.931, 0.896, 0.911 0.9% / 3.8% 1.14x 7.22 -> 7.29 GB 1.16 GB, lm_head + embedding

On torch < 2.11 every decoder Linear runs eagerly, and the per call fake quant was most of the step (L4 int4: 3.75 s of which about 2.5 s is gone). On torch >= 2.11 the decoder blocks are compiled and keep fake quantizing in graph; only the eager lm_head (and the int8-int4 embedding) is cached, so the gain is smaller and the extra memory is just those tensors (the int4 peak even drops, since the per step fake quantized lm_head transient is gone). First step time is unchanged on both (no new compiles). The 2.14 rows ran on A100 because no L4 was free; the 1.06x int4 row is inside A/A spread + 5%, the others are well above it.

Losses: steps 1 and 2 match across all runs; from step 3 every run (base runs too) drifts at the 1e-3 level, which is the pre-existing nondeterminism of this training setup, and head runs sit inside the base spread.

Not covered

  • Compiled blocks (torch >= 2.11) still fake quantize inside their graph. Feeding the cached weight into the graph would make it eager numerics instead of the compiled ones, so it is not bitwise to main; left for a follow-up.
  • nvfp4 / mxfp8: their custom matmul op quantizes the weight per call; caching the packed NVFP4 / MX weight is a follow-up.
  • Multi-GPU (DDP / FSDP) keeps the old path.

…ward

torchao's weight fake quantizer recomputed fake_quant(W) of every frozen base Linear on each
forward, gradient checkpointing replay and gradient accumulation micro batch. Cache the quantizer's
own output per quantizer while the weight is the same unmodified tensor (storage identity, version
counter, shape / stride / dtype, autocast state), so losses and LoRA gradients stay bitwise identical.

Covers int4, int8, cactus, int8-int4, fp8-int4 and fp8-fp8 (incl. the fake quantized lm_head and
embeddings). The cache holds one extra copy of each cached weight and fills at most half of the
memory free at the first store; UNSLOTH_QAT_WEIGHT_MEMO=0 turns it off, =1 lifts the cap. Weights
that require grad, range learning, tensor subclasses, multi-process runs, inference mode and
torch.compile traces keep the old path; PEFT merge / unmerge drop the cache.
@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-18T12:42:31.610423Z 8339cc4 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: a9f1331805

ℹ️ 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_weight_memo.py Resolved
Comment thread unsloth/models/_qat_weight_memo.py Resolved
…er from free memory

The cache limit was half of the memory free at the first store, measured during the first micro
batch. A later longer batch, evaluation or saving could then need memory the cache held, so a run
that fits without the cache could run out of memory with it.

- Nothing is cached before the first optimizer step, so that step runs exactly as before and its
  peak is the run's own.
- After every optimizer step the limit is what stays free at the highest peak seen so far (minus the
  cache held at that peak), minus the extra a full length batch (rows x max_seq_length, from a
  forward pre hook on the model) would add over the longest batch seen, minus a margin of
  max(512 MiB, 5% of the card). A cache over the limit is evicted.
- Eval mode (Trainer evaluation, model.eval(), for_inference) drops the whole cache and passes
  through, so evaluation and generation have the memory they had before.
- A CUDA out of memory error turns the cache off for the rest of the process.
- Cache usage is recounted from the live caches each step, so a deleted model leaks no budget.
…izer step later

The checkpoint skip planner plans from the first step's memory and keeps more activations from the
second step on, so the cache limit is taken from a step that already ran with that plan.
…pped quantizer

torchao's int8-int4 quantizers do not trace with fullgraph on torch 2.10 / 2.11 (dynamo skips
_per_token_quant_qparam_dim_check), with or without the memo, so the compile test failed there for a
reason outside this PR. It now also covers int4, and skips a scheme only when the unwrapped
quantizer forward fails to compile the same way.
The used bytes per device only went down on an explicit drop() (and, since the observed peak
change, at the next optimizer step's recount). Deleting a model in a notebook left phantom usage
until then, and stats kept reporting it. Each cache now gives its bytes back when it is collected;
drop() clears it first, so nothing is subtracted twice.
…the parameter, not via .data

_native_from_converted re-based the base weight with base.data.add_(...), which keeps the storage and
the version counter, so the QAT weight memo kept serving the fake quantized weight of the old base.
The add now runs on the parameter under no_grad, which bumps its version and invalidates the cache.
The other in place .data writers on base weights are multi-process only (memo off) or rebind .data
to new storage (already caught); the memo docstring states the rule for new writers.
@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: 88a15f40a8

ℹ️ 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_weight_memo.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: 22a3926248

ℹ️ 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_weight_memo.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. Keep it up!

Reviewed commit: 8339cc4239

ℹ️ 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 291fc2a into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the qat-weight-memo branch November 18, 2026 13:44
nick-oom pushed a commit to OOMResearch/unsloth that referenced this pull request Nov 18, 2026
… in place (unslothai#18339)

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 unslothai#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 | unslothai#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 | unslothai#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 unslothai#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 unslothai#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.
- unslothai#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 unslothai#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.
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