Skip to content

4-bit decode: no recompile from the eager setup, one output dtype under autocast, refresh the cached LoRA cast - #14754

Merged
danielhanchen merged 3 commits into
mainfrom
nf4-decode-gate-and-lora-cast
Oct 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
nf4-decode-gate-and-lora-cast

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Three fixes in fast_linear_forward (4-bit decode): a recompile from the bitsandbytes 4-bit GEMM gate added in #14386, the output dtype under a different autocast dtype, and the cached LoRA weight cast.

1. No recompile when an eager call sets the gate up

fast_linear_forward read the lazily set global _BNB_GEMM_4BIT before _bnb_gemm_4bit_ok checked _is_compiling(). Reading the global while tracing makes Dynamo guard on its value. A graph captured while it was still None is invalidated as soon as any eager call sets it to True or False, so every compiled region that goes through fast_linear_forward recompiles once.

The fix checks not _is_compiling() first, so the global is never read while tracing. Under compile the gate already returned False, so compiled code takes the same path as before; only the guard goes away.

2. One output dtype under a different autocast dtype

bitsandbytes gemm_4bit returns X.dtype, while the torch.matmul paths (dequantize fallback, dense) return the autocast dtype when called under a different one (fp16 activations under bf16 autocast, or the reverse). The output dtype therefore depended on the batch size and quant path, and with a LoRA adapter the in-place addmv_ / addmm_ update failed: its torch.mv / torch.mm operand follows autocast while the base output and LoRA factors do not (mat1 and mat2 must have the same dtype). On main this fails on both the fused GEMM and the fallback path.

Now the base result is cast back to X.dtype when it differs, and the LoRA mv / mm result is cast to X.dtype before the in-place update, so every path returns X.dtype (the activation dtype every decode caller allocates its buffers in). Without autocast, or with a matching autocast dtype, nothing changes.

3. The cached LoRA cast follows weight updates

fast_linear_forward cast the LoRA factors to the activation dtype once and stored the copy on the weight as _fast_lora, never refreshing it. When the dtypes differ, which is the default for float16 models (LoRA kept in float32 for mixed precision, so T4), every later decode reused the factors from the first decode: after more training steps (GRPO generation without vLLM, or SFT then generate then more SFT) decode ran with stale adapters. The cache is now keyed on both weights' _version and data_ptr() and the dtype, so an optimizer step or a replaced tensor recasts. Matching dtypes skip the cache entirely (the cast is a no-op). Inference tensors (a LoRA model built under torch.inference_mode()) have no version counter, so for them the key is the storage and dtype only. While tracing, the cast is done inline instead of setting an attribute, which was the second source of a guard on the eager setup.

Tests

tests/test_bnb_integration_compile.py:

  • test_fast_linear_forward_eager_setup_does_not_recompile: compile cold, run eager once, call the compiled function again, assert one frame compiled (torch._dynamo.testing.CompileCounter) and identical outputs.
  • test_fast_linear_forward_sees_lora_updates: float32 adapters, float16 decode, update lora_B in place, the next decode must match a freshly cast one bitwise.
  • test_fast_linear_forward_lora_under_a_different_autocast_dtype[True|False]: fp16 activations with LoRA under bf16 autocast, through the bitsandbytes GEMM (calls counted) and the dequantize fallback; output must be fp16 and match the no-autocast result.
  • test_fast_linear_forward_lora_cast_with_inference_tensors: LoRA model built under torch.inference_mode(), float32 adapters, fp16 decode twice.

New tests on B200:

torch main this PR
2.10.0 4 failed, 7 passed 11 passed
2.14.0 4 failed, 7 passed 11 passed

(-k over every fast_linear_forward test in the file; the inference-tensor test passes on main too, it guards the new cache key.)

The 10 test files that exercise fast_linear_forward or its LoRA cast (bnb integration / compile, NF4 GEMV, float32 LoRA fallback, GPTQ, NVFP4 and MXFP4 LoRA, non-LoRA PEFT inference, multiple active adapters, compressed-tensors FP8 route, LoRA dropout), torch 2.14 on B200: main 5 failed / 538 passed / 20 skipped, this branch 545 passed / 20 skipped (current head; 543 passed on the first revision). Three of main's failures are the new tests; the other two (test_compiled_lora_mlp_backward_never_reads_stale_memory[swiglu|geglu_approx]) timed out on both sides when rerun alone on this loaded host, so they are not claimed either way. The torch 2.10 run of the same 10 files did not finish within 50 minutes on either side on this shared host.

Not covered: no T4 / L4 run (the GEMM gate's target arch list); the change does not touch the arch list or the kernel call, only the gate condition, the output casts and the LoRA cast above. ROCm is unaffected (torch.version.hip already disables the path).

…oRA cast, and keep the bnb GEMM out of mixed autocast

fast_linear_forward read the lazily set _BNB_GEMM_4BIT global and the
_fast_lora attribute while tracing, so the first eager call recompiled
every captured graph. The cached LoRA cast was never refreshed, so with
float32 adapters and float16 decode (the default for float16 models) a
decode after more training used the old adapters. bitsandbytes' 4-bit
GEMM returns X.dtype, so it now declines under a different autocast dtype.
[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T19:01:36.333165Z cfd17a0 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7449f0ee52

ℹ️ 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/utils.py Outdated
and X.dtype in _BNB_GEMM_4BIT_DTYPES
and X.is_cuda
# bitsandbytes returns X.dtype; torch.matmul under autocast returns the autocast dtype.
and not (torch.is_autocast_enabled("cuda") and torch.get_autocast_dtype("cuda") != X.dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cast the LoRA branch with the autocast fallback

When this gate was otherwise eligible but the CUDA autocast dtype differs from X.dtype, the new condition routes small batches to the fallback matmul, which returns the autocast dtype. With an active LoRA adapter, the later branch still casts A and B to X.dtype; its torch_mm result is autocast, but the in-place addmm_ is not autocast-eligible and receives B in a different dtype, causing a dtype-mismatch error. This newly breaks configurations such as UNSLOTH_BNB_GEMM_4BIT=1 on Ampere with fp16 activations, bf16 autocast, and an active LoRA adapter, rather than merely making the output dtype consistent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed (557cfbcf): declining the GEMM only moved the mismatch into the LoRA update. Reworked: the autocast condition is gone from the gate, and fast_linear_forward now casts the base result back to X.dtype whenever it differs (only the torch.matmul paths under a different autocast dtype can produce that), so every branch hands the LoRA update and the caller's decode buffers X.dtype. This also fixes the same addmm_ / addmv_ mismatch on the dequantize fallback, which failed on main. New test test_fast_linear_forward_lora_under_a_different_autocast_dtype[True|False] runs fp16 activations with LoRA under bf16 autocast through the bitsandbytes GEMM (engagement counted) and through the fallback.

Comment thread unsloth/kernels/utils.py Outdated
if lora_A.dtype == dtype and lora_B.dtype == dtype:
return lora_A, lora_B
# Keyed on _version: adapters keep training between decodes (GRPO).
key = (lora_A._version, lora_B._version, lora_A.data_ptr(), lora_B.data_ptr(), dtype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid reading version counters from inference tensors

When a LoRA model or adapter is constructed inside torch.inference_mode() and its weights need casting to the activation dtype, these parameters are inference tensors and accessing _version raises RuntimeError: Inference tensors do not track version counter. This makes the decode fast path fail before the cast, whereas the previous cache implementation could run with such weights; use a cache key that handles inference tensors or bypass caching for them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 557cfbcf: when either factor is an inference tensor the cache key uses data_ptr() and the dtype only, since an inference tensor has no version counter and cannot be updated outside inference mode. New test test_fast_linear_forward_lora_cast_with_inference_tensors builds the LoRA model under torch.inference_mode() and decodes twice with float16 activations and float32 adapters.

…te in X.dtype under autocast, inference-tensor LoRA cast

Declining the bitsandbytes GEMM under a different autocast dtype moved the
mismatch into the LoRA update. The base result is now cast back to X.dtype
wherever torch.matmul followed autocast, and the LoRA mv / mm result is cast
to X.dtype before the in-place update (both failed on main with LoRA under
mixed autocast). Inference tensors have no version counter, so their cast
cache keys on storage.

[skip ci]
@danielhanchen danielhanchen changed the title 4-bit decode: no recompile from the eager setup, refresh the cached LoRA cast, keep the bnb GEMM out of mixed autocast 4-bit decode: no recompile from the eager setup, one output dtype under autocast, refresh the cached LoRA cast Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: cfd17a0fa7

ℹ️ 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 5503246 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the nf4-decode-gate-and-lora-cast branch October 22, 2026 19:23
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 24, 2026
…i#15052)

unslothai#14754 keyed the decode LoRA cast cache (`_fast_lora_weights` in
`unsloth/kernels/utils.py`) on the adapters' `_version`, so an adapter
that keeps training between generations gets a fresh cast. Fused
optimizers do not bump `_version`, so after a `torch.optim.AdamW(fused =
True)` step the cache keeps serving the old adapter weights.

### Cause
`aten::_fused_adamw_`, `aten::_fused_adam_` and `aten::_fused_sgd_` have
no `ADInplaceOrView` kernel, so they update the parameter values without
bumping `_version`. `add_` does have one. Measured with torch 2.14.1:

| | `_version` after one step | values changed |
|---|---|---|
| AdamW foreach, CPU | 0 -> 2 | yes |
| AdamW fused, CPU | 0 -> 0 | yes |
| AdamW foreach, CUDA | 0 -> 2 | yes |
| AdamW fused, CUDA | 0 -> 0 | yes |

`adamw_torch_fused` is the transformers `TrainingArguments` default on
torch >= 2.8. `for_training` already drops the cache, so this is only
reached when generation and training interleave without that switch (for
example `model.eval()` before `generate`, then more training).

### Change
- **New key element:** a global optimizer step post hook
(`torch.optim.optimizer.register_optimizer_step_post_hook`) counts
steps, and the count is part of the cache key next to `_version`.
- **Which optimizers it covers:** every `torch.optim.Optimizer`
subclass, including fused AdamW and the bitsandbytes 8-bit optimizers.
- **What stays the same:**
  - inference tensors still key on storage alone;
  - the compiled path still skips the cache;
  - the same-dtype path still returns the adapters directly.
- **Cost:** one integer increment per optimizer step and one extra
integer in the key per decode projection.

### Tests
`tests/test_fast_lora_cast_cache.py` (CPU):
- **After a step:** the cache returns the new weights after a fused
AdamW, foreach AdamW, for-loop AdamW and SGD step.
- **Without updates:** it still hits when nothing changed.
- **Same dtype:** it is skipped when the dtypes match.

| torch | main | this PR |
|---|---|---|
| 2.7.1 | 1 failed (`adamw_fused`), 5 passed | 6 passed |
| 2.10.0 | 1 failed (`adamw_fused`), 5 passed | 6 passed |
| 2.14.1 | 1 failed (`adamw_fused`), 5 passed | 6 passed |

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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