Skip to content

QAT: weight memo guards for inference mode, side streams and static scales; re-round after a base weight reload - #18434

Merged
danielhanchen merged 8 commits into
mainfrom
kp-qat-guards
Nov 19, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
kp-qat-guards

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

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:

  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 QAT LoRA: fake-quantize the frozen base weight once instead of every forward #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

#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

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.

… 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)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-19T10:48:45.546507Z 6372d44 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

Copy link
Copy Markdown
Codex Review Summary: 🔄 Running

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-11-19T08:45:53.426140Z 71d9759 PR opened
ℹ️ 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: 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".

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

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

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

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

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

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

Comment thread unsloth/models/_qat_round.py Resolved
@danielhanchen
danielhanchen merged commit dc12e10 into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the kp-qat-guards branch November 19, 2026 11:56
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…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.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 20, 2026
…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.
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