Skip to content

Fall back to PEFT's LoRA forward for float32 base weights - #7020

Merged
danielhanchen merged 21 commits into
mainfrom
fix/fused-lora-fp32-dtype
Sep 29, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
fix/fused-lora-fp32-dtype

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Loading a model with dtype = torch.float32 and training LoRA crashes on the first step, in both 16-bit and 4-bit:

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/Qwen2.5-0.5B-Instruct",
    dtype = torch.float32,          # 16bit or load_in_4bit = True, either way
)
RuntimeError: self and mat2 must have the same dtype, but got BFloat16 and Float

The run trains under bf16 autocast while the base weights and adapters stay float32. The fused LoRA kernels in fast_lora.py use in-place addmm_ and out= matmuls, which autocast does not reconcile, so a bf16 gradient meets an fp32 weight in the backward.

Fix

Rather than teach the fused kernels about mixed dtypes, float32 models no longer use them:

  • patch_peft_model skips the fused LoRA kernels when the base weights are float32 (plain or the quant_state dtype of a 4-bit weight) and keeps PEFT's own forward. The patch summary says why: The fused LoRA kernels were skipped because the base weights are float32. fast_lora.py and matmul_lora are unchanged.
  • Two fp32 fixes stay on the inference path, which still runs Unsloth's 4-bit kernels:
    • fast_dequantize picked only the fp16 or bf16 NF4 kernel while allocating out with quant_state.dtype, so an fp32 quant state got bf16 bits written into an fp32 buffer. It now uses bitsandbytes' cdequantize_blockwise_fp32_nf4, bit-exact to bnb.functional.dequantize_4bit.
    • Single-token decode used the 4-bit gemv, which is fp16/bf16 only. fp32 now takes the dequantize + matmul path.

bf16 and fp16 models take exactly the same path as before.

Verification

unsloth/Qwen2.5-0.5B-Instruct, LoRA r=16 on all projections, 10 SFT steps, seed 3407, then greedy generation after for_inference, B200:

Load main this PR
float32, 16-bit crash at step 1 fused kernels skipped; loss 1.889 to 0.325; generates " 13. The quick brown fox..."
float32, 4-bit crash at step 1 fused kernels skipped; loss 1.868 to 0.324; generates " 13. The quick brown fox..."
bf16, 16-bit 24/24/24 layers fused unchanged: 24/24/24 fused, loss 1.910 to 0.325
bf16, 4-bit 24/24/24 layers fused unchanged: 24/24/24 fused, loss 1.885 to 0.330

Without the two inference fixes, float32 4-bit trains but generates !!!!!!!!!!!.

Tests (tests/test_float32_lora_fallback.py): the base weight dtype helper (plain and 4-bit), the skip reason, fp32 NF4 dequantize bit-exact to bitsandbytes, and fp32 single-token decode against a dequantized reference. The last two fail when their fix is reverted. tests/test_lora_dropout_patch_summary.py pins the gate, so it is updated to the three-condition gate.

The dY @ B.t() reuse in the fused LoRA backward that was previously in this PR moved to #12212.

Not covered

Only the Llama-family patch_peft_model path installs the fused kernels, so that is the only gate. XPU uses the same NF4 dequantize fix but was not run on that hardware; ROCm, Apple Silicon and multi-GPU were not exercised.

The fused LoRA ops are decorated with @custom_fwd, which disables
autocast. When an fp32 activation (for example the fp32 output of
fast_rms_layernorm on an fp32 hidden/residual stream) reaches a fused
LoRA path whose base weight is fp16/bf16, nothing downcasts the
activation, so torch.matmul raises:

    expected mat1 and mat2 to have the same dtype: float != c10::Half

This is not torch-version specific; torch.matmul never auto-promotes a
mixed fp16/fp32 matmul.

Reconcile the dtypes at the matmul_lora choke point: after dequantizing
W (both the plain and the fast_dequantize branches, not the fp8 branch),
downcast X to the base weight compute dtype the way autocast would for a
plain Linear, and keep the LoRA A/B cast dtype consistent with it.

Keep the backward pass dtype-consistent: LoRA_MLP, LoRA_QKV and LoRA_W
now record the original input dtype in ctx.input_dtype, pin the saved
activation to the compute dtype, cast the incoming gradients to that
dtype, and cast the returned dX back to the original input dtype to honor
the autograd grad-dtype contract. Every added branch is a no-op when the
dtypes already match, so normal fp16/bf16/fp32 training is unchanged.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner July 9, 2026 06:08
Each fused-LoRA backward computed dY @ B.t() (the LoRA-B projected gradient,
shape (batch*seq, r)) twice per projection: once for the A weight gradient and
once for the dX accumulation. Hoist it into a single temporary and reuse it in
both, removing 6 small matmuls per layer (3 in LoRA_QKV, 2 in LoRA_MLP, 1 in
LoRA_W). Results are bitwise identical; measured about 2 to 3 percent faster on
the LoRA forward plus backward for qkv and mlp in both 16-bit and 4-bit.
@danielhanchen

Copy link
Copy Markdown
Member Author

Added commit cb1ef59, a small backward optimization on top of the dtype fix. Each fused-LoRA backward was computing the LoRA-B projected gradient dY @ B.t() (shape (batchseq, r)) twice per projection, once for the A weight gradient and once for the dX accumulation. It is now hoisted into a single temporary and reused, removing 6 small matmuls per layer (3 in LoRA_QKV, 2 in LoRA_MLP, 1 in LoRA_W). Verified bitwise identical LoRA gradients versus the previous head in an isolated deterministic test (16-bit and 4-bit); the hoisted temporaries are (batchseq, r) so there is no meaningful memory cost. Measured about 2 to 3 percent faster on the LoRA forward plus backward for qkv and mlp in a microbenchmark, both 16-bit and 4-bit.

@oobabooga

Copy link
Copy Markdown
Member

@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: 0d7dff116b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/kernels/utils.py Outdated
Comment on lines +1157 to +1159
if X.dtype != W.dtype:
X = X.to(W.dtype)
dtype = W.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 Keep Float8Tensor activations out of raw fp8

When this branch handles a torchao Float8Tensor, W.dtype is the fp8 storage dtype rather than the matmul compute dtype. With the new cast, normal bf16/fp16 activations are converted to raw fp8 before torch_matmul, and the later LoRA path also casts A/B to that same dtype, bypassing torchao's scaled activation quantization and potentially feeding unsupported/unscaled fp8 tensors. This reconciliation should be skipped for Float8Tensor weights or use the dequantized/actual compute dtype instead.

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.

Checked against the torchao we actually import. Float8Tensor.dtype is the original high-precision dtype, not the fp8 storage dtype; the raw fp8 lives in .qdata. On torchao 0.18.0, for both PerRow and PerTensor granularity:

type=Float8Tensor .dtype=torch.bfloat16 .qdata.dtype=torch.float8_e4m3fn
.contiguous() -> Float8Tensor / torch.bfloat16
.dequantize() -> Tensor / torch.bfloat16
x_fp32.to(W.dtype) -> torch.bfloat16

So the cast lands on bf16, which is the compute dtype, and it cannot produce a raw-fp8 activation. The genuinely-raw-fp8 case is the separate W.dtype == torch.float8_e4m3fn branch that routes to fp8_linear, and that branch deliberately gets no cast.

Separately, the code this points at is gone: the LoRA compute dtype now comes from the produced out rather than from W, which is both autocast-correct and side-steps the question.

Comment thread unsloth/kernels/fast_lora.py Outdated
Comment on lines +648 to +649
ctx.input_dtype = dtype
X = X.to(XW.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 Preserve fp32 LoRA weight gradients

When PEFT keeps the LoRA adapter weights in fp32, this saved-activation cast makes backward derive dtype from the base compute dtype instead, so A/B are cast to fp16/bf16 and the returned adapter gradients are no longer fp32 for the fp32 inputs. In the newly supported fp32-activation into fp16/bf16-base path, that can either trip autograd's gradient dtype check or train the fp32 adapters with low-precision gradients; keep a separate adapter/input dtype for the returned LoRA weight grads.

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.

The 16-bit d_A / d_B against an fp32 adapter is not something this branch introduces. main already builds them as torch.empty_like(A) after A = A.to(X.dtype), so every fused MLP/QKV/O layer does it today for the ordinary bf16-activation case, and unsloth_zoo upcasts lora_A / lora_B to fp32 unconditionally, so that is the normal configuration rather than a corner.

The one combination this branch changes is the one main raises on rather than computing, so there is no fp32 grad being lost. Confirmed over the activation x base weight x adapter dtype x inplace x rows x autocast product, 1350 cells: 1044 that raised on main now run, 306 are bit-identical to main, 0 regressions, and 0 cells where a value or a dtype moved.

It is also not a correctness hazard mechanically: torch converts a floating grad to the leaf dtype in the engine rather than raising. On torch 2.13.0:

grad torch.bfloat16 -> param torch.float32 : ok, .grad dtype = torch.float32
grad torch.float16  -> param torch.float32 : ok, .grad dtype = torch.float32

Accumulating the LoRA weight gradients in fp32 instead of the compute dtype is a real precision improvement, but it is a separate change against main and not a blocker here.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed matmul_lora in unsloth/kernels/utils.py still hands an fp32 activation straight into a 16-bit base weight matmul, so the dtype reconciliation is the right call. The dY @ B.t() hoisting in cb1ef59 is a separate perf change though, so could you split that into its own PR and let the dtype fix be reviewed on its own?

danielhanchen and others added 4 commits September 21, 2026 14:00
Pinning the LoRA compute dtype to W.dtype regressed a case that works on
main: under autocast the base matmul produces `out` in the autocast dtype,
not W's, and `out.addmm_(XA, B)` for the LoRA term is in-place and so is
not autocast-eligible. An fp16 activation against a bf16 base weight under
fp16 autocast then raised

    RuntimeError: self and mat2 must have the same dtype, but got Half and BFloat16

Derive the LoRA operand dtype from `out` instead, which is the dtype the
base matmul actually produced in both regimes, and skip the activation
pre-cast entirely when autocast is on, since autocast reconciles the matmul
itself and pre-casting would only round the activation through a second
dtype. The autocast query sits behind the existing dtype comparison, so the
ordinary matching-dtype path does not pay for it.

Over the activation x base weight x adapter dtype x inplace x rows x
autocast product (1350 cells), against main: 612 cells that raised now run,
306 are bit-identical, 432 still raise (all of them an autocast dtype that
disagrees with the base weight, which the trainer already rejects at setup),
0 regressions and 0 cells whose values or dtypes moved.

tests/test_fused_lora_activation_dtype.py pins both halves: the fp32
activation case fails on main, and the autocast case fails on this branch
before this commit.

Also corrects three comments that said custom_fwd disables autocast. It does
not with cast_inputs=None; the mechanism is that in-place addmm_ and
matmul(out=) are not autocast-eligible.
… in fp32

Two defects the forward-side dtype fix exposed, both reproduced through the
public loader with FastLanguageModel.from_pretrained(dtype = torch.float32).

First, the backward passes dequantize the base weight in its own dtype and
then feed it to `torch.matmul(..., out = X)` and `dX.addmm_(...)`. Neither
form is autocast-eligible, so an fp32 base weight against a bf16 compute
dtype raised

    RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != float

_dequantize_to reconciles the weight at the six dequantize sites in
LoRA_MLP, LoRA_QKV and LoRA_W. It is a no-op whenever the dtypes already
agree, which is every ordinary fp16/bf16/fp32 run.

Second, with the crash gone, fp32 + load_in_4bit trained to a nonsense loss
(15.1 against 0.75 for the same model in bf16). fast_dequantize allocates
`out` with quant_state.dtype but dispatched the NF4 kernel two ways only,
fp16 or bf16, so an fp32 quant_state wrote bf16 bits into an fp32 buffer.
Measured against bitsandbytes' own dequantize_4bit, the error was 0.127 on
weights of magnitude 0.09. bitsandbytes exports cdequantize_blockwise_fp32_nf4;
binding it and making all three dispatch sites three-way takes that error to
exactly 0, and the loss to 0.7428 against 0.7427 for the same model in fp16.

That second one is a pre-existing bug on main, not something this PR
introduced. It was unreachable only because the crash above got there first.

Over the full kernel-level product (1350 cells) against main: 1044 cells that
raised now run, 306 are bit-identical, 0 regressions, 0 cells whose values or
dtypes moved.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

kernels/utils.py now binds cdequantize_blockwise_fp32_nf4 at module scope, and
tests/python/test_bitsandbytes_kernel_readiness.py asserts the probe list matches
those binds exactly. Without this the probe would also clear a wheel that cannot
serve the fp32 dequantize path.
…ected

DEVICE_TYPE is "hip" on ROCm and "mlx" on Apple Silicon, and torch's autocast
APIs accept neither:

    torch.is_autocast_enabled("hip")
    RuntimeError: unknown device type for autocast in get_autocast_dispatch_key_from_device_type

so the new probe turned the mismatched-dtype case, the one this branch exists
to support, into a crash on every ROCm box. DEVICE_TYPE_TORCH already maps hip
to cuda and mlx to mps.

"npu" is rejected too on a torch build without that backend registered, which
DEVICE_TYPE_TORCH does not remap, so the device name is resolved once at import
and falls back to "assume no ambient autocast" when torch will not take it. That
fails OPEN: matmul_lora reconciles the dtypes itself, which is the behaviour that
makes the mismatched case work at all, rather than erroring on the probe.

Resolving it once also keeps the query off the per-matmul path; what remains
there is a module-global lookup behind the existing dtype comparison.

The 1350-cell matrix is unchanged by this: 1044 fixed, 306 bit-identical, 0
regressions, 0 cells whose values or dtypes moved.

Reported by Codex.
The file was marked `gpu` module-wide, so every test in it was deselected on any
runner without an accelerator. That is the wrong way round for
test_autocast_probe_uses_the_torch_device_name: it is pure Python, and it is
exactly the check that needs to run on the non-CUDA platforms, since the defect
it pins (torch.is_autocast_enabled("hip") raising on ROCm) cannot show up on the
NVIDIA box the rest of the file needs.

Marking the three matmul tests individually instead: 7 passed / 1 deselected
under -m gpu, 1 passed / 7 deselected without it, where before it was 0 and 8.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

`torch.is_autocast_enabled` only grew its device-name argument in 2.4, and this
repo still ships extras for older ones (cu118onlytorch211, cu121onlytorch220 and
siblings); this very file already branches on `Version(torch.__version__) <
Version("2.4.0")` for custom_fwd. The single try/except therefore caught the
TypeError on those versions and pinned the probe to "always disabled", so
matmul_lora would pre-cast the activation to the weight dtype and then let
autocast cast it again, changing results by that extra rounding.

Three tiers now, resolved once at import: the device-name form on 2.4+, the
zero-argument form on 2.1-2.3, and only if neither answers, fail open to
"assume no ambient autocast".

The 1350-cell matrix is unchanged: 1044 fixed, 306 bit-identical, 0 regressions,
0 cells whose values or dtypes moved.

Reported by Codex.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 598c026069

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from gemini-code-assist Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
…ciling dtypes inside them

fast_lora.py and matmul_lora go back to main. patch_peft_model now leaves float32 models on
PEFT's own forward and says why in the patch summary. Inference keeps two fp32 fixes: NF4
dequantize uses bitsandbytes' fp32 kernel, and single-token decode skips the fp16/bf16-only
4bit gemv.
@danielhanchen danielhanchen changed the title Fix fused LoRA dtype mismatch on fp32 activations into fp16/bf16 weights Fall back to PEFT's LoRA forward for float32 base weights Sep 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: a91efd61ee

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@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: a91efd61ee

ℹ️ 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/llama.py


def _base_weight_dtype(proj):
weight = getattr(proj, "base_layer", proj).weight

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 decoding packed MXFP4 weights for a dtype check

When q_proj.base_layer is an Mxfp4PackedLinear, reading .weight invokes its property in mxfp4_compressed_linear.py, which performs a fresh full dequantization of the packed matrix. Consequently, every LoRA setup for a packed MXFP4 model creates a potentially large temporary fp16/bf16 weight on the accelerator merely to inspect its dtype, defeating the packed-weight memory guarantee and potentially OOMing large models at patch_peft_model; inspect compute_dtype or the packed quant state before accessing .weight.

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.

Reachable for a compressed-tensors MXFP4 checkpoint, but it is one dequantized q_proj from layers[0], once at patch time, in the compute dtype and freed immediately: about 100 MB at hidden 7168, next to a model that is already resident. Nothing is computed wrong and it cannot plausibly OOM, so keeping the single generic dtype read here.

@danielhanchen
danielhanchen merged commit 5a60350 into main Sep 29, 2026
34 checks passed
@danielhanchen
danielhanchen deleted the fix/fused-lora-fp32-dtype branch September 29, 2026 11:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants