Skip to content

QLoRA: keep dequantized NF4 LoRA base weights in idle VRAM - #18285

Merged
danielhanchen merged 17 commits into
mainfrom
qlora-nf4-dequant-cache
Nov 18, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
qlora-nf4-dequant-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

With Unsloth gradient checkpointing every frozen NF4 LoRA base weight is dequantized three times per micro-batch: in the no-grad forward, in the checkpoint replay and in the backward (kernel census on main: 336 _nf4_dequant_kernel launches per step for the 112 NF4 linears of Llama-3.2-1B, compiled and eager). The decode is deterministic, so this PR keeps the 16-bit copy of as many base weights as fit in otherwise idle VRAM and skips those decodes.

On the notebook-style run (Alpaca, batch 2, gradient accumulation 4), QLoRA steps get faster:

  • Llama-3.1-8B on L4: 25% faster.
  • Llama-3.2-3B on L4: 12.5% faster.
  • Llama-3.2-3B on T4: 14% faster.

Losses are unchanged.

Design

New file unsloth/kernels/dequant_cache.py.

  • Budget. Same scheme as the zoo MoE expert cache. Nothing is cached before the first optimizer step. After every optimizer step (an optimizer step post hook, when the step's activations are freed) the budget is free + reserved-unused - 2 x largest step transient - max(1 GiB, 5% of the card). The transient is the step peak above resident memory.
  • Guard. Every 8th cache hit re-reads free memory (mem_get_info, plus allocator stats only when the driver reports less than the margin). If memory is under the margin it drops the oldest entries and admits nothing more until the next optimizer step. An OOM while admitting turns the cache off for the rest of the process.
  • Lifetime. Entries are tied to their packed weight: a storage weak reference (also swept after every gc collection) and the version counter. They are never served on another stream or during CUDA graph capture. The cache is cleared at the end of SFTTrainer.train(), in for_inference() and before saving, so inference and merging after training get the memory back.
  • Disabled cases. Off when vLLM is loaded (standby would wake into memory the cache took) and when several ranks share a GPU.
  • Who reads it. Only the LoRA kernels' matmul sites read the cache: matmul_lora and the input-gradient sites of LoRA_MLP, LoRA_QKV and LoRA_W. The dense tensor never reaches other code, so save.py's in-place merge and other fast_dequantize callers are unaffected.
  • Traced path. Under per-block compile these sites call two opaque CUDA ops (unsloth::nf4_cached_matmul, unsloth::nf4_cached_addmm_). Each op does the lookup (or the decode) and then the same GEMM as before: _lora_first_addmm, matmul or addmm_. Because the cached tensor never enters the graph, Inductor cannot reuse its buffer, and the graph is the same whatever is cached, so nothing recompiles when the cache fills or drains. The ops are registered as plain CUDA kernels (only called with grad off), which dispatch for less than the custom ops they replace. Per-call CPU cost on a hit is about the same as lora_first_addmm / addmm_.
  • Kill switch. UNSLOTH_NF4_DEQUANT_CACHE=0 runs the previous code at every site. A number caps the cache in GiB.

Results

Colab, torch 2.14.1, transformers 5.17.0, TRL 1.15.0, PEFT 0.21.3, bitsandbytes 0.50.2. Setup: QLoRA r16 on all 7 projections, adamw_8bit, Unsloth gradient checkpointing, per-block compile (default).

Each arm ran 3 times as fresh processes, interleaved base, head, head, base, base, head, followed by one run with the kill switch. Every run had fresh compile caches. The figure is the median optimizer-step time after warmup; the spread is (max - min) / median of that arm's 3 runs.

  • nb: yahma/alpaca-cleaned in the notebook prompt, batch 2, GA 4.
  • short: 2 x 192 random tokens, GA 1.
GPU Model Workload main this PR Change =0
L4 Llama-3.2-3B nb 1.184 s (1.1%) 1.037 s (1.7%) -12.5% 1.193 s
L4 Llama-3.2-3B short 0.289 s (2.4%) 0.271 s (0.7%) -6.3% 0.286 s
L4 Llama-3.1-8B nb 2.628 s (1.6%) 1.964 s (0.6%) -25.3% 2.611 s
T4 Llama-3.2-3B nb 2.779 s (9.2%) 2.397 s (1.3%) -13.8% 2.793 s
T4 Llama-3.2-3B short 0.690 s (6.3%) 0.566 s (3.6%) -18% 0.713 s
T4 Llama-3.1-8B nb 4.693 s (1.6%) 4.712 s (0.2%) +0.4% (tie) 4.698 s
A100 80GB Llama-3.1-8B nb 1.191 s (0.9%) 1.117 s (1.2%) -6.2% 1.199 s

A second T4 3B nb set (the same cache with an earlier op registration) gave 2.806 s (1.5%) on main and 2.408 s (1.8%) with the PR, -14.2%. The first step, which includes compile, is 2 to 3 s faster on L4 and A100 (L4 3B 21.6 s to 19.7 s, L4 8B 23.1 s to 20.7 s) because the compiled blocks no longer contain the dequant.

Memory

torch.cuda.max_memory_allocated in GiB. The step-1 peak is identical on both arms because nothing is cached before the first optimizer step.

GPU, model after load step 1 peak training peak, main training peak, this PR cache
L4, 3B nb 2.10 2.46 2.55 7.79 5.25
L4, 8B nb 5.32 5.91 6.01 18.96 13.0
T4, 3B nb 2.10 2.59 2.73 7.98 5.25
T4, 8B nb 5.32 6.04 6.19 13.40 6.92, then 0
A100, 8B nb 5.32 5.91 6.08 19.08 13.0

On T4 8B the cache took 6.92 GiB after the first step. When a longer batch raised the activation peak, the guard dropped all of it, kept 1 GiB free throughout and admitted nothing more. That configuration gains nothing (it is GEMM bound) and does not slow down. Notebook "peak reserved memory" printouts will show the cache: about 8.2 GB instead of 2.8 GB for 3B on T4.

Correctness

  • Bitwise, B200. Llama-3.2-1B, 6 steps, cache on vs off: grad norms are equal in every step for bf16 compiled, fp16 compiled (T4 numerics) and bf16 eager.
  • Kernel census, B200. Kernels per step drop from 3690 to 3354 (bf16) and from 4023 to 3687 (fp16), exactly the 336 dequant launches. The compiled graph gains no new kernels.
  • Bitwise, A100. On the short workload all 7 runs produced identical losses.
  • Losses elsewhere. Where runs are nondeterministic (L4, T4, nb), step 1 losses are equal. The largest per-step loss difference between main and this PR is within the main-vs-main spread on every case except L4 short (2.6e-3 vs 1.5e-3 at loss 11.48).
  • Memory guard, B200. These runs report a smaller card to the cache.
    • 4.5 GiB card with a 1.2 GiB allocation added at step 3: 1.82 GiB was cached, then evicted. Max allocated stayed at 4.13 GiB and the grad norms matched the uncached run.
    • 2.6 GiB card: only 0.1 GiB fit, and it was evicted at the next pressure.

Tests

  • tests/test_nf4_dequant_cache.py (CPU, under 2 s) covers:
    • mode parsing
    • the budget formula
    • nothing cached before the first optimizer step
    • admission, hits, the transposed view, staleness on an in-place write
    • budget capping
    • margin eviction
    • the OOM fallback
    • gc sweep of a dead weight
    • the kill switch

Not covered

  • No torch < 2.11 run. The eager path was checked on torch 2.14 with UNSLOTH_BLOCK_COMPILE=0.
  • Not run on ROCm, XPU (skipped by design), multi-GPU DDP or GRPO (off with vLLM).
  • Non-Llama model families that reach matmul_lora were not measured.

Memory safety follow-up (ff9fa52 .. 35ceab1)

The first version could run out of memory on runs that fit on main: on Colab T4 / L4 it OOMed in 8 of 9 cells where main peaks at about 87% of the card (Llama-3.1-8B fp16 on T4, 3B and 8B on L4; variable-length batches, a long micro-batch inside gradient accumulation, and evaluation). The follow-up commits make "fits on main" imply "fits with the cache":

  • The cache only fills inside Trainer.train(), after the first optimizer step, and is released at the end of training for every trainer, before evaluation / prediction, in for_inference (text and vision) and before saving.
  • Every admission leaves 2 x the measured step transient plus a margin free, inside set_per_process_memory_fraction when one is set; the cache is off when another process holds more than the margin on the GPU, and off by default in the Studio worker (an explicit UNSLOTH_NF4_DEQUANT_CACHE=1 still works).
  • A forward pre-hook drops the cache before a model call with more tokens or a longer sequence than any measured step allocates anything, so a late long batch runs with main's memory.
  • Auto mode turns itself off for a run with a callback that is not from transformers / TRL / PEFT / accelerate / Unsloth (an arbitrary callback can allocate between steps).
  • A cache hit also requires the same quantization state (absmax) it was decoded from.
  • Peak memory is only read, never reset, and no torch API is patched: after the cache shrinks, a later peak counts only once it exceeds the peak at the shrink; after a plain clear the last measured transient is kept so the cache refills, after a size drop or pressure the conservative bound is kept until a new peak is measured.
  • No host bookkeeping runs while tracing (0 graph breaks base and head in a compiled training run on torch 2.12 / 2.14 / 2.15).

Real cards, final code (Colab; the job printed the module md5):

Cell main peak this PR
L4 8B, long micro-batch in GA4 18.74 GiB 18.84 GiB cache engaged, dropped before the long batch, long-step loss equal
L4 8B, eval every N steps 11.95 GiB 18.95 GiB cache refills after eval (86% of the card), eval losses bitwise equal
T4 8B, late long batch 12.43 GiB 12.66 GiB cache engaged, loss equal

L4 3B notebook recipe (GA4): main 1.128 / 1.135 s per step, this PR 1.004 / 1.026 s (about 10% faster). The in-step peak is higher by design when there is idle VRAM (notebook "peak reserved" prints show the cache).

Not covered: Windows with the follow-up commits (AMD Linux ran up to 5fd3172 with bitwise-equal losses), multi-GPU DDP beyond a 2x T4 smoke, a real Studio run, packing on real cards, desktop GPUs whose display already holds about 1 GiB (auto mode stays off there).

Under Unsloth gradient checkpointing every frozen NF4 linear is dequantized
three times per micro-batch (no-grad forward, checkpoint replay, backward).
unsloth/kernels/dequant_cache.py keeps the 16-bit copy of as many of these
weights as fit in otherwise idle VRAM, so those decodes are skipped. The
decode is deterministic, so the cached tensor is the same values the kernel
would produce.

Budget follows the zoo MoE expert cache: nothing is cached before the first
optimizer step; at every optimizer step (the safe point, activations freed)
room = free + reserved-unused - 2 x largest step transient - max(1 GiB, 5%).
Every 8th hit re-reads free memory and drops the oldest entries while it is
under the margin; an OOM while admitting turns the cache off for the
process. Off with vLLM loaded or several ranks per GPU, cleared at the end
of SFTTrainer.train(), in for_inference() and before saving.

Only the LoRA kernels' matmul sites (matmul_lora and the fast_lora input
gradient sites) read the cache. Eager they take the cached tensor; traced
(per-block compile) they call two opaque CUDA ops that do the lookup and
the same GEMM, so the graph never sees the cached tensor and nothing
recompiles when the cache fills or drains.

UNSLOTH_NF4_DEQUANT_CACHE=0 restores the previous code paths; a number caps
the cache in GiB.
@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-18T14:15:07.233794Z 8cb9618 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: 1c759b4313

ℹ️ 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/kernels/dequant_cache.py Resolved
Comment thread unsloth/kernels/dequant_cache.py Resolved
The budget only covered steps like the ones already measured, and the cache
kept its weights across steps, so memory the base code leaves free could be
taken when something else needed it. On a 5 GiB card budget (Studio's
set_per_process_memory_fraction) the cache also ignored the fraction.

* Auto mode holds weights for one optimizer step: the safe point drops them
  and keeps the budget, so callbacks, evaluation, saving and user code between
  steps see the base memory. The next step's first micro-batch admits again.
* A matmul with more rows (tokens) than any measured before the last safe
  point drops the device's cache until the next safe point: a longer batch
  late in training, a larger GA micro-batch or evaluation batch.
* Nothing is cached outside Trainer.train() (a default TrainerCallback carries
  the scope, so other train() wrappers cannot bypass it); evaluation and
  predict run with no budget; the end of train() returns the memory to the
  driver, for every trainer, not only SFTTrainer.
* Free memory is capped by the per-process memory fraction (also recorded on
  torch without the getter), and the guard re-reads it under a fraction.
* Auto mode stays off while another process holds more than the margin on the
  GPU, or once one grows by more than it.
* FastVisionModel.for_inference clears the cache too.
* Studio's training worker defaults UNSLOTH_NF4_DEQUANT_CACHE=0: its chat
  keep / load checks read the GPU's free memory, which the cache would fill.
An admission only checked that the margin stayed free, so memory taken
after the safe point (a callback's tensor, a second model loaded between
steps) let the cache grow into the room the rest of the step needs. Every
admission now leaves 2 x the measured transient + the margin usable, the
same reserve the budget is computed with.
…pped card

Auto mode re-admits every step, and each admission read the allocator stats
(about 0.4 ms), which made short GA 1 steps slower than without the cache.
The free memory is now read once per optimizer step, at its first admission,
and lowers that step's budget to keep 2 x transient + margin usable; later
admissions only compare against the budget.

Under set_per_process_memory_fraction the margin is a share of the capped
card, not of the whole GPU.
Dropping the cache at every optimizer step re-decoded and re-admitted every
weight each step, which made GA 1 steps slower than without the cache (L4,
Llama-3.2-3B, 2 x 192 tokens: 0.297 s vs 0.284 s). Between optimizer steps
only the trainer and its callbacks run; transformers / TRL / PEFT /
accelerate / Unsloth callbacks evaluate through Trainer.evaluate (the cache
is dropped first) and generate through for_inference (cleared there). So
auto mode keeps its weights across steps again, but only when every callback
of the run comes from those packages: a user callback may allocate anything
between steps, and then auto mode stays off for that run. An explicit GiB cap
opts in regardless. The cache is also dropped when evaluation follows an
epoch.
The size check ran at the first LoRA matmul, after the model had already
allocated for a larger call: on L4 with Llama-3.1-8B, a 52224-token
padding-free micro-batch built its attention inputs with the cache still
held and peaked 2.6 GiB above the base run, 0.6 GiB short of the card.
A forward pre-hook on the trained model (registered at on_train_begin,
removed when training ends) now compares each call's tokens and sequence
length with the largest measured before the last safe point and drops the
cache before the forward runs. Sequence length is tracked too, since
attention masks grow with its square at equal token counts.
test_guard_evicts_under_margin only faked the allocator reading, but the
guard reads torch.cuda.mem_get_info first and returns while the driver has
room, so on any GPU host (ROCm Linux and Windows CI, a B200) the test failed
with all three weights still cached. It only passed where CUDA is absent and
mem_get_info raises.
A hit was served when the packed storage and its version matched, without
checking the quant state, so a weight given a new quant state (new absmax,
same packed tensor) returned the old dense weight. The hit now also
requires the absmax the entry was decoded from; _miss already dropped such
an entry as stale.
The transient was the allocator's lifetime peak minus current allocation,
and that peak still held cache bytes freed since (pressure eviction, a drop
before a larger call, the clear before evaluation), so the freed cache was
counted as activation memory: the transient stayed inflated and the cache
could never refill. Whenever the cache shrinks, the allocator's peak is
restarted at the current usage, so the next safe point measures only what
ran since. torch.cuda.memory_stats / max_memory_* keep reporting the peaks
from before (a notebook's peak reserved memory is still the whole run's);
a user's own reset_peak_memory_stats clears them.
rows_of() tested a SymInt for truthiness and the model forward pre-hook
read and wrote module state; under a whole-model torch.compile (or a
compiled caller that does not take the opaque op route) both would be
traced, adding guards or graph breaks. Both now return at once while
compiling: traced callers do not read the cache there, and the opaque
ops still check the row count eagerly at run time.
a5fdf64 restarted the allocator's peak whenever the cache shrank and
wrapped torch.cuda.memory_stats / reset_peak_memory_stats so callers still
saw the run's peaks. Accelerate, Studio's memory panel, TRL and notebooks
read those APIs, so a default-on cache must leave them alone.

The peak is now only read. When the cache shrinks, the peak at that moment
is recorded; at later safe points a peak that has not risen above it may
still hold the freed cache:
* after a plain clear (evaluation, inference, saving, end of training, a
  smaller budget) the shapes trained on are unchanged, so the last measured
  transient is kept and the cache refills;
* after a size drop or memory pressure the larger or tighter step's own
  transient is unknown, so peak - current stays the (conservative) bound
  until a new peak is measured.
A peak above the recorded one is a real new peak and is measured as usual.

The model pre-hook now records shapes only for training-mode calls, so an
evaluation batch never widens what a later training step may run cached.
@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: 35ceab15c4

ℹ️ 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/kernels/dequant_cache.py Resolved
Comment thread unsloth/save.py Resolved
…ative; save keeps its locals

A training step larger than any measured (more tokens, a longer sequence, more matmul rows) now marks a
stale allocator peak unsafe even when evaluation or a clear has emptied the cache, so the conservative
bound sizes the next budget until a new peak is measured. The end of training does the same for the
next train() call. unsloth_save_model releases the cache through a module-level helper: a local import
there was forwarded by dict(locals()) to unsloth_save_model(**kwargs) on an MTP-head push (TypeError).
…measured rows

Trainer.evaluate / predict run uncached and never size a training step, so their larger matmuls no longer
force the conservative bound after evaluation (the cache refills as before when training resumes at the
measured shapes).
@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: c61b1f4add

ℹ️ 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/kernels/dequant_cache.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: 0a6c086c67

ℹ️ 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/kernels/dequant_cache.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: 47a46e4922

ℹ️ 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/kernels/dequant_cache.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: 66b43638d4

ℹ️ 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/kernels/dequant_cache.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. Already looking forward to the next diff.

Reviewed commit: 8cb9618fc6

ℹ️ 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 567f979 into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the qlora-nf4-dequant-cache branch November 18, 2026 16:26
danielhanchen added a commit that referenced this pull request Nov 18, 2026
## Summary

The whole-tree "Duplicate definitions" step in Lint CI fails on main:

```
duplicate definitions (1):
  unsloth/kernels/dequant_cache.py:740: _ is defined twice (def at line 721, def here)
```

Every PR's source lint job inherits this (for example the staging runs
for #17742 and #18108, both on current main).

## Cause

#18285 registers fake (meta) kernels for its two custom ops with the
idiom the torch.library docs use:

```python
@torch.library.register_fake("unsloth::nf4_cached_matmul", lib = _LIB)
def _(X, W, ...): ...

@torch.library.register_fake("unsloth::nf4_cached_addmm_", lib = _LIB)
def _(out, X, W, ...): ...
```

That code is correct. The decorator keeps a reference to each function,
and the name `_` is never read back, so neither copy is dead.
`lint_duplicate_definitions.py` exists to catch a second copy that
silently replaces the first, which is not what happens here. The lint is
too broad for this case.

## Fix

In `scripts/lint_duplicate_definitions.py`, a `def _` that has at least
one decorator binds nothing. This covers `register_fake`,
`singledispatch`'s `@f.register def _`, and similar registration hooks.
The exemption is deliberately narrow:

- An undecorated `def _` defined twice is still a finding.
- Any other decorated name defined twice is still a finding.

Two self-test cases pin both sides. The docstring's list of carve-outs
documents it.

## Verification

- `--self-test`: 65 cases pass. With the exemption removed, the new
decorated `_` case fails (`self-test FAILED (1 case(s))`).
- Whole tree (`unsloth unsloth_cli studio scripts tests cli.py
unsloth-cli.py`): `clean: 6105 file(s) checked`. On main the only
finding was the one above, so the exemption hides nothing else.
- `tests/test_lint_duplicate_definitions.py`: 12 passed. ruff is clean.
danielhanchen added a commit that referenced this pull request Nov 18, 2026
## Summary

Six tests in `tests/saving/test_save_method_lora_routing.py` fail on
main in every Core job (HF default, 4.57.6 and latest):

```
NameError: name '_release_nf4_dequant_cache' is not defined
FAILED test_unsloth_save_model_guards_a_respelled_merged_4bit[merged-4bit]   (and 2 more params)
FAILED test_the_adapter_save_forwards_a_real_safe_serialization
FAILED test_an_adapter_push_survives_a_transformers_that_dropped_the_keywords
FAILED test_an_adapter_push_still_passes_every_keyword_a_transformers_4_accepts
```

Seen on the staging runs for #17742 and #18256, both on current main.

## Cause

#18285 has `unsloth_save_model` call `_release_nf4_dequant_cache()`
first, so a merge gets back the memory the training-time NF4 dequant
cache held. That is correct. The helper is deliberately module-level,
because `unsloth_save_model` forwards its own `locals()`.

This test does not import `unsloth/save.py`. It execs the named
functions into a namespace that `_load()` builds, pre-stubbing the
helpers every save path calls (`_unmerge_flags_on_error`,
`lora_relative_to_original_base`, and so on). The new helper was not in
that namespace.

## Fix

Add `_release_nf4_dequant_cache` as a no-op default in `_load()`, next
to the other always-called save helpers. None of these fixtures has a
dequant cache to free.

## Verification

`tests/saving/` without the model-loading `test_unsloth_save.py`:

| Tree | Result |
|---|---|
| main | 7 failed (the 6 above plus
`test_torchao_remote_code_consent.py::test_compressed_and_gguf_lora_paths_drop_auto_map_trust`)
|
| this branch | 1 failed (the same torchao test) |

The torchao test fails identically on both sides on this host and does
not fail in CI, so it is unrelated. `test_save_method_lora_routing.py`
passes 80 out of 80. ruff is clean.
danielhanchen added a commit that referenced this pull request Nov 18, 2026
…ckward harnesses (#18368)

## Summary

Sixteen tests in the CPU "rest" shard fail on main since #18285, in two
groups:

```
tests/test_for_inference_resets_inference_runs.py      (6)  KeyError: "'__name__' not in globals"
tests/test_return_logits_survives_for_training.py      (8)  KeyError: "'__name__' not in globals"
tests/test_fp8_down_proj_bf16_backward.py              (2)  RuntimeError: 0 active drivers ([]). There should only be one.
```

Seen on the staging run for #17742, which does not touch these files.

## Cause

#18285 keeps dequantized NF4 LoRA base weights in a cache. Both new call
paths are correct; the CPU harnesses could not follow them.

1. `FastBaseModel.for_inference` (`unsloth/models/vision.py`) now clears
that cache with an inline `from ..kernels.dequant_cache import
clear_dequant_cache`. `_fast_base_model()` in
`test_return_logits_survives_for_training.py` lifts `for_inference` /
`for_training` out of the source and execs them in a namespace with no
package. A relative import there raises `KeyError: '__name__' not in
globals`. The harness already stubbed whole helpers for this reason, but
this import sits in the lifted method itself.
2. The LoRA backward now dequantizes through `dequant_cache.dequantize`.
That function reads `fast_dequantize` from `kernels.utils` when called.
The fp8 fixture only patched `fast_lora.fast_dequantize`, so the real
Triton path ran on a CPU runner. For an fp8 quant state, `dequantize`
falls straight through to `fast_dequantize`, so production behaviour is
unchanged.

## Fix

Test-only:

- `_fast_base_model()` rewrites each relative `from ..x import a` in the
lifted bodies to `a = _relative_import("x", "a")`, resolved from an
explicit stub table. The table starts with `clear_dequant_cache` as a
no-op. Guarded imports the fakes never reach still need no stub. One
that a fake does reach without a stub fails with `stub the relative
import ('kernels.dequant_cache', 'clear_dequant_cache') lifted from
unsloth/models`, so the next inline import says what to add instead of
surfacing as a `KeyError`.
- The fp8 fixture patches `fast_dequantize` in `kernels.utils` as well
as in `fast_lora`.

## Verification

| Tree | Result (the three files) |
|---|---|
| main | 16 failed, 5 passed |
| this branch | 21 passed |
| this branch, stub table emptied (sabotage) | 14 failed, each naming
the missing stub |
| this branch, `kernels.utils` patch removed (sabotage) | 2 failed, `0
active drivers` |

ruff is clean.

The 17th failure in that shard,
`test_grpo_autocast_disabled.py::test_reading_it_tolerates_an_older_trainer`,
has a different cause (#18335) and is handled separately.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 19, 2026
…tocast on the compiled route, invalidate on in-place scale writes (unslothai#18433)

## NF4 dequant cache: no Trainer pre-hook on models without NF4 weights

### Summary

Stop the NF4 dequant cache's Trainer scope from installing its forward
pre-hook on models with no NF4 weights. Before this change, every dense
or 16-bit LoRA model trained with a `transformers` Trainer after `import
unsloth` paid a host read of the attention mask on every forward, for a
cache it can never use.

### Root cause

unslothai#18285 (merge 567f979) appends `UnslothDequantCacheScope` to
`transformers.trainer.DEFAULT_CALLBACKS`. Its `on_train_begin` registers
`_model_pre_hook` on whatever model is trained. For a 2D attention mask
the hook calls `_padded`, which runs `bool(mask.all())`, a host sync on
a CUDA mask, before checking whether the model has anything to cache.
Measured with a dispatch-mode counter on CPU: one `aten.is_nonzero` /
`_local_scalar_dense` call per forward of a plain dense model on
origin/main, zero on the parent. This is a cost, not a correctness
issue: one extra device sync per micro-batch at the start of the
forward.

Reachability: the default case. Any non-4-bit model (bf16 LoRA, full
fine-tuning) trained with a Trainer while the cache mode is `auto`.

### Fix

- New `_has_nf4_weights(model)`: one pass over the modules per
`train()`. It looks for a bitsandbytes NF4 quant state on a parameter,
or on a `Linear4bit`'s own `quant_state` copy (FSDP2 all-gathers the
packed bytes into a Parameter without one).
- `on_train_begin` leaves the scope off (`_ACTIVE = 0`, no hook) when
the trained model has none, so nothing is cached for that run.
- If the check cannot run, it returns True and keeps the previous
guarded behaviour. NF4 models are unchanged, hook included.

### Tests

New `tests/test_nf4_dequant_cache_dense_model.py` (CPU; each arm prints
the `dequant_cache.__file__` it imported):

- origin/main (8ef13a7) with only the new test copied in: `1 failed,
2 passed` (dense model: `assert 1 == 0` host reads per forward).
- this branch: `3 passed`. The NF4 cases (quant state on the parameter,
or only on the `Linear4bit`) still install the hook and still do the one
mask read.
- Existing `tests/test_nf4_dequant_cache.py` passes on this branch (35
passed together with the new file).

Command: `pytest tests/test_nf4_dequant_cache_dense_model.py
tests/test_nf4_dequant_cache.py -o addopts= -m "not server and not
native_mxc" -p no:cacheprovider`.

### Not proven here

- The per-step time cost of the removed sync was not measured on a GPU.
- An NF4 weight whose quant state is reachable neither from its
parameter nor from its module would now turn the cache off for that run.
This is slower but safe, since nothing is cached. None of the current
loaders do this.

## NF4 dequant cache: keep autocast semantics on the compiled matmul
route

### Summary

Keep autocast semantics on the compiled NF4 matmul route added in
unslothai#18285. Under `torch.compile` with autocast, `matmul_lora` on an NF4
weight (no LoRA term, grad off, as inside the fused LoRA autograd
functions) returned a different dtype and different values than the
eager path.

### Root cause

unslothai#18285 (merge 567f979) routes traced NF4 matmuls through the opaque
op `unsloth::nf4_cached_matmul` (`unsloth/kernels/dequant_cache.py`). It
replaces a `torch.matmul` that autocast casts to the autocast dtype, but
autocast does not see inside the op and its fake returns `X.dtype`.
Measured on B200, torch 2.14.1, on origin/main:

- fp16 input, fp16 NF4 weight, bf16 autocast: compiled output was fp16
`inf` in default, `fullgraph=True` and `fullgraph=True, dynamic=True`;
eager gives finite bf16 524288.
- bf16 input under fp16 autocast: compiled output bf16, eager fp16.
- fp32 input, bf16 weight, bf16 autocast: compiled call failed with
`expected mat1 and mat2 to have the same dtype`.

Reachability: only when the activation dtype differs from the autocast
dtype inside a compiled, grad-off NF4 `matmul_lora` call (for example a
user `torch.compile` around the fused LoRA path under a mismatched
`torch.autocast`). Default FastLanguageModel training keeps the
activation, quant state and autocast dtypes equal
(`patch_model_and_tokenizer` casts `quant_state.dtype`), so I found no
default configuration that reaches it. The fix is cheap and makes the op
match the code it replaced.

### Fix

- `nf4_matmul` (traced Python wrapper): when there is no LoRA term and
autocast is on for the input's device, cast `X` to the autocast dtype,
as autocast would for `torch.matmul`. The checks are constant-folded by
Dynamo and the autocast state is already part of Dynamo's global guards,
so no new guard, graph break or recompile.
- `_matmul_impl`: cast the dense weight to `X.dtype` when they differ,
so the result no longer depends on whether autocast is active when the
compiled graph runs.
- The lora-first form is unchanged: it replaces
`unsloth::lora_first_addmm`, which was already an opaque op that
autocast did not cast. `nf4_cached_addmm_` is unchanged (an in-place
`addmm_`, which autocast does not cast).

### Tests

New `tests/test_nf4_dequant_cache_autocast.py` (CUDA; compiled vs eager
`matmul_lora` under autocast, asserts the traced op route ran). Both
arms on one B200 lease, each arm importing its own tree
(`dequant_cache.__file__` printed):

- origin/main (8ef13a7) with only the new test copied in: `5 failed,
34 passed` (3x fp16 `inf` vs bf16, 1x bf16 vs fp16 dtype, 1x fp32 dtype
mismatch RuntimeError).
- this branch: `39 passed`.

Command: `pytest tests/test_nf4_dequant_cache_autocast.py
tests/test_nf4_dequant_cache.py -o addopts= -m "not server and not
native_mxc" -p no:cacheprovider`.

### Not proven here

- Correctness on B200 (sm100) only; sm75 / sm80 / sm89 / sm120 and AMD
were not run.
- Only torch 2.14.1 was run on GPU. `torch.is_autocast_enabled(device)`
and `torch.get_autocast_dtype(device)` exist and are constant-folded by
Dynamo from torch 2.4, so the 2.6 floor imports, but no 2.6 GPU run was
done.
- No end-to-end Unsloth training run reaching the mismatched-dtype case,
since I found no default configuration that reaches it.

## NF4 dequant cache: invalidate on in-place scale writes

### Summary

The NF4 dequant cache from unslothai#18285 could keep serving a dense weight
decoded with old scales after an in-place write to the quant state's
scales. The cache entry now records the address and version of every
scale tensor the decode reads.

### Root cause

unslothai#18285 (merge 567f979) keys a cache hit on the packed weight's
storage pointer and version and on `absmax.data_ptr()` (`_lookup` /
`_miss` in `unsloth/kernels/dequant_cache.py`). An in-place write to
`absmax` (for example `quant_state.absmax.mul_(2)`) keeps its address,
so the hit still matched. With nested quantization
(`compress_statistics=True`), the decode also reads `state2.absmax` and
`offset`, which were not checked at all. Reproduced on CPU with real
bitsandbytes NF4 states: the stale entry differed from a fresh decode by
up to 4.09 (plain absmax), 2.88 (nested absmax), 1.47 (`state2.absmax`)
and 1.02 (`offset`).

Reachability: I found no Unsloth, PEFT or bitsandbytes path that writes
NF4 scales in place during training; reloads, merges and requantization
build new tensors, which the address check already caught. It needs user
or third-party code that edits scales in place. The fix is a few host
attribute reads per lookup, with no device sync.

### Fix

- New `_scales_key(absmax, absmax2, offset)`: the `data_ptr()` and
`_version` of `absmax` and, when present, of the nested `absmax2` and
`offset`. It is stored in the entry slot that held `absmax.data_ptr()`
and compared on every hit and in `_miss`.
- `dequantize` passes `quant_state.state2.absmax` and
`quant_state.offset`. `_dense_from_parts` (the traced op path) passes
the `absmax2` and `offset` it already receives.
- Inference tensors have no version counter; for those the key falls
back to the address alone. They cannot be written in place outside
inference mode, and the cache is bypassed inside it.

### Tests

New `tests/test_nf4_dequant_cache_scales.py` (CPU, real bitsandbytes NF4
states, faked memory reading; each arm prints the
`dequant_cache.__file__` it imported):

- origin/main (8ef13a7) with only the new test copied in: `4 failed,
33 passed` (absmax plain, absmax nested, state2.absmax and offset cases
all served stale).
- this branch: `37 passed` (new test plus the existing
`tests/test_nf4_dequant_cache.py`).

Command: `pytest tests/test_nf4_dequant_cache_scales.py
tests/test_nf4_dequant_cache.py -o addopts= -m "not server and not
native_mxc" -p no:cacheprovider`.

### Not proven here

- The in-place write was simulated. No real training workload that
writes scales in place was found or run.
- The extra attribute reads on the hit path were not timed. They are
host-only (`data_ptr`, `_version`), with no device sync.
- In-place writes to the NF4 code tables (`code`, `state2.code`) are
still not tracked. These are constant codebooks.
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