Skip to content

LoRA: add the rank-r term inside the base GEMM so small updates are not rounded away - #16071

Merged
danielhanchen merged 30 commits into
mainfrom
lora-fused-order
Oct 31, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
lora-fused-order

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Summary

The fused LoRA kernels (LoRA_MLP, LoRA_QKV, LoRA_W via matmul_lora) compute the base GEMM, round it to bf16, then add the rank-r term in a second pass and round again. A LoRA update smaller than half a bf16 step of the base output is rounded away. Early in training, or at small learning rates, part of every update is lost, so the adapter trains as if its learning rate were smaller. PEFT has the same order.

This PR writes the rank-r term first and lets the base GEMM accumulate onto it (out.addmm_(X, W.t()), beta 1). cuBLAS reads the LoRA term in the fp32 epilogue of the GEMM, so the sum is rounded once.

  • Backward: dX starts as the rank-r term and the base GEMMs accumulate onto it the same way.

  • Under torch.compile: the fused forward runs as one custom op, unsloth::lora_first_addmm. It writes the rank-r term into a fresh buffer, accumulates the base GEMM in place and returns a new tensor. Written as two functional torch.addmm calls, Inductor first copied the rank-r term into a new output for the second GEMM (242 device-to-device copies per step on Llama-3.2-1B). It registers the addmm gradients and saves only the operands the requested gradients read, so a compiled caller that differentiates through matmul_lora still works (a frozen base created under inference_mode included). Under vmap / torch.func transforms the eager helper uses the functional calls. Compiled inside torch.func transforms (grad, jvp, jacrev, jacfwd, vmap) or native forward-mode AD (torch.autograd.forward_ad.dual_level), matmul_lora keeps the base-then-LoRA order: the op has no forward-mode or batching rule (a compiled jvp returned zeros, a compiled dual lost its tangent), and a traced beta = 0 addmm under jvp crashes torch. The op is used only inside the Dynamo trace of torch.compile, not under torch.export (strict or not), which keeps the two functional calls so torch.func still applies to an exported program. Export is recognised by the flag torch.export sets, read directly: torch 2.10 / 2.11 Dynamo folds torch.compiler.is_exporting() to True in every compiled region. torch 2.6 has no such flag, so there compiled code keeps the functional calls. If any registration step of the op fails, the traced branch keeps the functional calls.

  • Fewer passes over X: in eager mode q / k / v (and gate / up) compute X @ A in one GEMM (compressed sparse LoRA A weights, which cannot be concatenated, keep one product each); in the backward every projection's LoRA gradients read X once. Under torch.compile the shared forward GEMM is skipped (the shared intermediate breaks the block compile), the rest applies.

  • bf16 and fp32 only: fp16 keeps the base-then-LoRA order everywhere, forward and backward. In fp16 a rank-r term (or a summed LoRA dX) rounded on its own can overflow before the base term cancels it, which would make the GradScaler skip steps that main completes.

  • One rule for every call site (_lora_fused_ok), applied the same way in the forward and backward of LoRA_W, LoRA_QKV and LoRA_MLP. These keep the base-then-LoRA order:

    • fp16 activations;
    • lora_dropout or a lora_bias anywhere in the module (a down-only bias included), for the whole module;
    • FP8, INT4 (either orientation) and packed weights, including the MLP down derivative after its FP8 weight is converted;
    • a base weight that dequantizes to another dtype (fp32 weights or an fp16 4-bit state under bf16 autocast), since the in-place accumulate does not autocast;
    • per-projection scales that differ (shared backward only);
    • a caller out buffer that is not already the output, or that shares storage with X, W, A or B, or that cannot be inspected (traced by torch.compile or make_fx); a precomputed X @ A sharing the caller buffer is recomputed, for every base (dense, 4-bit, INT4, packed, Float8Tensor), and a 3-D one is flattened with X. The weight is dequantized before the caller's buffer is written, so a buffer sharing storage with the quant state (absmax, code) is read first;
    • a sparse base weight, in eager mode and under torch.export;
    • a tensor-subclass base weight with no quant state (TorchAO NF4Tensor reports bf16 over packed storage and has no addmm_);
    • a DTensor base weight or activation (X, A, B or a precomputed X @ A), whose placements the plain accumulator would drop. The QKV, MLP and single-projection functions record the same decision for the backward, so a DTensor input never takes the shared or fused backward either (it changed the input gradient's placement for QKV);
    • calls compiled inside torch.func transforms or under native forward-mode AD;
    • multi-token inference (fast_linear_forward, q_len > 1) on a projection with a configured lora_dropout, matching the training kernels;
    • under torch.compile, LoRA weights that are plain tensors rather than nn.Parameter (on torch 2.14 their dynamic shapes broke the backward on a recompile);
    • a backward context built without the forward's fused decision (older or handcrafted callers).
  • DoRA and other unsupported adapters still go to PEFT as before.

  • Rounding tradeoff: the term rounded on its own changes from the base output to the LoRA term. Its rounding error scales with its own size, so the result is closer to the exact sum whenever the LoRA term is smaller than the base term, which is the normal case for a LoRA update. When the LoRA term is about as large as the base output and cancels it, main can keep a residual this PR rounds away. Against an fp64 oracle (bf16, M = 2048, K = N = 1024, r = 16, random weights, varying the LoRA / base ratio):

    LoRA / base output mean abs error, this PR / main QKV dX mean abs error, this PR / main
    0.01 1.12e-3 / 1.50e-3 2.88e-3 / 3.97e-3
    0.1 1.16e-3 / 1.54e-3 2.92e-3 / 4.02e-3
    1 2.48e-3 / 2.48e-3 5.48e-3 / 5.92e-3
    10 2.11e-2 / 1.79e-2 not run
  • Kill switch: UNSLOTH_LORA_FUSED_PASSES=0 restores the previous order everywhere, bit for bit.

Results

Training quality

yahma/alpaca-cleaned (2,000 train rows, 200 held-out eval rows, completion-only loss, up to 1,024 tokens), LoRA r16 on all linear layers, 250 steps, 3 seeds. Held-out eval loss at step 250, mean over seeds:

model, lr fp32-compute reference main this PR this PR - main, per seed kill switch - main (noise)
Llama-3.2-3B bnb-4bit, 1e-5 1.12501 1.12749 1.12510 -0.0023 / -0.0024 / -0.0024 <= 0.00025
Llama-3.2-3B bnb-4bit, 5e-5 1.09976 1.10010 1.09981 -0.0003 / -0.0003 / -0.0002 <= 0.00005
Llama-3.2-3B bnb-4bit, 2e-4 1.09869 1.09881 1.09860 -0.0003 / -0.0000 / -0.0003 <= 0.00012
Qwen3-8B bnb-4bit, 2e-4 n/a 0.99794 0.99809 +0.0002 / +0.0000 / +0.0003 <= 0.0004
  • lr 1e-5: better on every seed at every eval point (step 50: -0.017 to -0.027), and within 0.0001 of the fp32-compute reference where main is 0.0025 away. The LoRA B weights are 5x closer to the reference (relative distance 0.024 vs 0.124).
  • lr 5e-5: better on every seed, by less.
  • lr 2e-4: no difference beyond noise on either model; never worse than main at any eval point.

Speed

ms per step, 2 x 2048 tokens, LoRA r16, default block compile, fresh process per arm, two runs each:

GPU model main this PR change
A100 Qwen3-8B bnb-4bit 1077 / 1080 1070 / 1069 -0.9%
A100 Llama-3.2-3B bnb-4bit 516 / 515 509 / 510 -1.1%
L4 Qwen3-8B / Llama-3.2-3B within the run to run spread

Without block compile the gain on A100 is 2.0-2.7%. Peak memory is unchanged.

Compiled bf16 step time, Llama-3.2-1B LoRA r16, 2 x 512 tokens, fresh process per arm in ABBA order (median of 10 steps per run):

device main order (kill switch) two functional addmms (earlier head) custom op (this head)
Radeon 8060S (gfx1151), Linux, torch 2.11 ROCm 511.8 / 513.9 ms 552.6 / 554.4 ms 514.3 / 511.3 ms
A100, torch 2.14 62.1 / 62.1 / 63.0 ms 61.1 / 62.7 / 64.5 ms 61.6 / 60.8 / 60.5 ms

On gfx1151 the losses with the op are bit-identical to the functional form; on A100 the two agree within the run-to-run spread of either arm (final loss 1.1233-1.1239 vs 1.1235-1.1239). 0 graph breaks in every arm on both. On the current head, which adds the op's gradients and the transform, export and DTensor guards, the same A100 harness on another VM gives 62.5 / 64.0 / 65.2 ms, against 64.5 / 64.5 / 66.1 ms for the first version of the op and 65.7 / 65.7 / 78.0 ms with the kill switch, with 273 device-to-device copies per step in every arm.

Memory of the shared paths

Peak live tensor storage above the inputs on CPU (bf16 unless noted), one QKV forward and backward:

tokens x hidden, width, rank forward main / this PR backward main / this PR
8192 x 512, 512, 128 26.25 / 30.13 MiB 9.50 / 7.88 MiB
8192 x 512, 512, 128 (fp32) 52.5 / 60.25 MiB 19.0 / 15.75 MiB
256 x 8192, 1024, 128 (fp32) 7.63 / 12.38 MiB 67.38 / 67.0 MiB
2048 x 256, 256, 128 (fp32) 7.25 / 9.13 MiB 6.75 / 6.88 MiB

The shared backward frees A @ X.t() before allocating the combined dY @ B.t(), writes it in place and computes lora_A gradients directly in the [r, K] parameter layout, so its peak is at or below main's. The forward's combined X @ [A_q; A_k; A_v].t() stays live across the three projections: about 2 x tokens x rank x element size more (4 MiB at 8192 tokens, rank 128, bf16), plus the concatenated A (rank x hidden per projection), which matters only when the hidden size is large and the token count small. The CUDA allocator peak is set by the activations, which this does not change (the speed runs above show the same peak memory).

Tests

  • New tests/test_lora_fused_passes.py:
    • qkv / o / mlp outputs, dX and LoRA gradients against the previous order and an fp64 PEFT oracle (fp32 and bf16, equal and mixed alpha_pattern);
    • the shared paths engage only where they apply;
    • with the kill switch, matmul_lora equals base GEMM then in-place rank-r add, bit for bit;
    • every excluded configuration (fp16 at all; dropout, lora_bias and a down-only lora_bias in fp16, bf16 and fp32) gives outputs, dX and LoRA gradients bit-identical to the kill switch;
    • an fp16 case whose rank-r term alone overflows stays finite and equals the kill switch;
    • an fp32 base under bf16 autocast, an fp16 NF4 state under bf16 autocast, the eligibility table (INT4 in both orientations, packed, FP8), a caller buffer that needs resizing and one that shares storage with the weight;
    • a bf16 case where the LoRA update is smaller than half a bf16 step of the base output: this PR keeps it (the exact result rounded once), the previous order drops it;
    • the shared backward's lora_A gradients already have the parameter's [r, K] contiguous layout, as row views of one buffer (no copies);
    • a caller buffer under torch.compile and under make_fx fake tracing, a precomputed X @ A sharing the caller buffer (fused and old order), a sparse base weight, multi-token inference with and without a configured lora_dropout;
    • torch.compile(dynamic = True) of LoRA_QKV with plain-tensor and nn.Parameter LoRA weights where a rank equals the first sequence length (fresh interpreter; fails before this change on torch 2.14), and the traced order for both.
    • a precomputed X @ A sharing the caller buffer with packed, INT4 and Float8Tensor bases (mocked on CPU), and a 3-D precomputed X @ A;
    • a TorchAO NF4Tensor base, CSR / CSC / BSR LoRA A weights in the shared X @ A, a caller buffer sharing storage with the quant state;
    • a sparse base weight exported with torch.export and run, a replicated DTensor base weight, and a DTensor X (replicated, row- and column-sharded) with plain W / A / B, whose value and placement match the base-then-LoRA order;
    • QKV, MLP and single-projection forward + backward with DTensor X, A and B (replicated, row- and column-sharded): the recorded decision is the base-then-LoRA order and dX has the same value and placement as with the kill switch (8 of these fail on the previous head, where QKV's dX changed placement). Where a torch's DTensor cannot run main's own order (views of a sharded dim, in-place addmm), they skip. The one-rank DTensor tests use a gloo group on a file store (no TCP rendezvous) and destroy only a group they created.
  • New tests/test_lora_first_addmm_op.py: the op equals the eager sequence bit for bit, passes opcheck including its autograd registration, is used by a fullgraph compiled matmul_lora, gives the eager gradients when that compiled call is differentiated (bf16 and fp32), runs under vmap over X or W, stays out of the graph with the kill switch, and without the op the traced branch keeps the functional form. Compiled grad, jvp, jacrev, jacfwd and vmap around matmul_lora (bf16 and fp32, eager and aot_eager backends) match the eager transforms, and the op's backward needs no saved frozen operands. A compiled native forward-AD tangent matches eager; a strict and a non-strict exported module have no opaque op and give the right torch.func.jvp / grad; export detection reads the export flag, not the folded query; an op whose autograd registration fails (injected, fresh interpreter) stays disabled; a fullgraph compiled LoRA_W forward and backward traces with the op and no graph break (on torch 2.10 / 2.11 Dynamo folds torch.compiler.is_exporting() to True, which once reached a layout read Dynamo refuses).
  • CPU: the 15 LoRA / FP8 kernel test files give 352 passed, 0 failed on torch 2.13, 340 passed on torch 2.11 and 331 passed on torch 2.6 (main: 243 passed, 0 failed, without the new files). The 9 tests added for strict export, the export flag, the partly registered op, the NF4Tensor base, compressed sparse A weights and the quant-state buffer fail on the previous head (strict export on torch 2.6, 2.11 and 2.13) and pass now. Every test added for compiled torch.func transforms, native forward AD, export, DTensor operands, the op's saved operands and a sparse base fails on an earlier head of this PR and passes now (the 4 compiled vmap cases pass on both); the fullgraph LoRA_W test fails on torch 2.11 with the earlier is_exporting check. On an earlier head test_lora_fused_passes.py and the dropout / bias and gradient layout files also passed on PEFT 0.18.0 and 0.21.2.
  • Version floor (CPU): torch 2.6.0 + PEFT 0.18.0 + transformers 4.57.6 + TRL 0.22.2: the 15 LoRA / FP8 files give 330 passed, 0 failed (main: 238 passed, 0 failed); the op registers there, and compiled code keeps the functional calls (no export flag). On torch 2.6 main's own order cannot run a DTensor X (aten.addmm_ has no sharding strategy there), so that test skips. A sparse base under torch.export keeps main's order on torch 2.6 as well (it has no torch.compiler.is_exporting, so the check reads is_sparse / is_sparse_csr).
  • GPU (A100, torch 2.14.1): the same 15 files give 781 passed, 3 failed; main gives 631 passed, 3 failed. The 3 are the same IDs on both (test_fused_lora_peft_fallbacks.py::test_disabled_adapter_without_grad_on_4bit_base_stays_fused[o|qkv|mlp]). RTX PRO 6000 on an earlier head: 455 passed, the same 3 failed.
  • Compile: tiny Llama, Qwen3 and Gemma-3 LoRA training with the default block compile: 0 graph breaks and the same number of compiled graphs with the switch on and off.
  • fp16 + GradScaler (A100 and RTX PRO 6000): Llama-3.2-1B bnb-4bit, 30 steps, autocast fp16: losses identical to the kill switch at every step (fp16 keeps the previous order), 0 skipped steps, scale 65536.

Not covered

  • T4 / fp16 timing, H100 and B200.
  • Training longer than 250 steps, downstream benchmarks, DPO and GRPO trainers.
  • Qwen3-8B at a small learning rate.
  • Gemma-3: the tiny model gave bit-identical losses with the switch on and off, so its path did not reach these kernels; real Gemma models not checked.
  • Compressed sparse (CSC / BSR) base weights or LoRA A weights under torch.compile: only COO and CSR are recognised in traced code (Dynamo refuses to read layout there); eager mode checks every layout.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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 ⚠️ Failed 2026-10-30T20:19:26.723914Z
We couldn’t complete this review. Comment @codex review to try again.
c0c322f 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[bot]

This comment was marked as resolved.

…e differs

In-place accumulation is not autocast, so an unquantized fp32 base weight with half
activations (fp32 weights under fp16 / bf16 autocast) would fail on the dtype mismatch.
matmul_lora and the LoRA_W / LoRA_QKV / LoRA_MLP backward now take the fused order only
when the base weight is quantized or already in the activation dtype.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 30, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… quantized

fast_dequantize returns a 4-bit state's own dtype, so a bf16 NF4 state under fp16 autocast
would reach the in-place base accumulation with mismatched dtypes. The fused order now
needs the state's dtype (or an unquantized weight's dtype) to equal the activation dtype.
…site

fp16 keeps the base-then-LoRA order: a rank-r term or a summed LoRA dX rounded on its own
can overflow fp16 before the base term cancels it. FP8, INT4 (either orientation) and packed
weights are excluded everywhere, including the MLP down derivative after its FP8 weight is
converted. Dropout or a lora_bias anywhere in a module keeps the whole module, forward and
backward, on the old order. A caller buffer that is not already the output takes the old path.
… fp16, bf16 and fp32

Adds a down-only lora_bias case, an fp16 overflow case, the eligibility table (INT4 in both
orientations, packed, FP8, 4-bit state dtype) and a caller buffer that needs resizing.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: d1809a5a73

ℹ️ 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 added a commit to Imagineer99/unsloth that referenced this pull request Oct 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 855adda69b

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

…, dropout inference and plain-tensor weights under compile; d_A as row views

- matmul_lora: a caller's out buffer that cannot be inspected (Dynamo, make_fx fake tensors) is treated as
  shared and takes the base-then-LoRA order; a precomputed XA that shares out is recomputed after the base GEMM.
- _lora_fused_ok: a sparse base weight keeps the old order.
- fast_linear_forward (q_len > 1): a configured lora_dropout keeps the old order, like the training kernels.
- Traced, plain-tensor LoRA weights keep the old order (torch 2.14 dynamic recompile bound the output width
  to 0); the forward's decision is stored on ctx for the backward.
- _shared_lora_backward: AX freed before dB, dB written in place, d_A computed in [sum r, K] layout and
  returned as row views (no per-projection copies).
- Tests for each case.

[skip ci]
…a_first_addmm)

Traced (torch >= 2.11 block compile), the two functional addmms made Inductor copy the rank-r term into a
new output before the base GEMM: 242 device-to-device copies per step on Llama-3.2-1B. The op writes the
rank-r term into a fresh buffer and accumulates the base GEMM in place, returning a new tensor. Eager uses
the same helper with an empty buffer instead of a broadcast zero. If the op cannot be registered, the
traced branch keeps the functional addmms. Tests: bitwise against the eager sequence, opcheck, fullgraph
use of the op, kill switch, and the fallback without the op.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: f9203d3821

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

…for every dispatch, vmap and 3-D XA

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3c9240d04e

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: e95d544a7d

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

Copy link
Copy Markdown
Member Author

Repo tests (CPU, gloo-tp-pp) fails on the float64-reference check this PR adds to test_fused_lora_functions_read_local_shards (staging run, Linux x86_64 runner):

AssertionError: ('dX', 0.0009866450191111653, 0.00017579261020728154)
assert 0.0009866450191111653 <= ((2 * 0.00017579261020728154) + 1e-06)

On that runner the fused path's dX is about 5.6x further from the float64 reference than the plain PEFT path, against the 2x the check allows. So either the new in-GEMM order loses accuracy on some CPU GEMM kernels, or the 2x bound is too tight for dX (it peaks near 1e3, where one fp32 ulp is about 1.2e-4). Worth checking which before merging. Separately, (Python 3.13, a-f) on the same run is a timing flake in test_stray_end_tags_in_a_skipped_menu_stay_linear, unrelated to this PR and fixed in #16170.

…order in every forward and shared backward decision
danielhanchen added a commit that referenced this pull request Oct 30, 2026
…f five (#16170)

## Problem


`studio/backend/tests/test_web_fetch_extraction.py::test_stray_end_tags_in_a_skipped_menu_stay_linear`
failed in `(Python 3.13, a-f)` on an unrelated PR (the staging run for
#16071, a LoRA change):

```
AssertionError: [0.01457291399992755, 0.41335185699995236]
assert 0.41335185699995236 < (0.01457291399992755 * 24)
```

The test times one call of `html_to_markdown` at 1000 and at 8000
repeats and requires the second to stay under 24x the first (8x input,
so linear growth is about 8x and quadratic about 64x). Each size is a
single call, and the small one takes only about 10 to 15 ms, so a single
descheduling of either call on a shared runner moves the ratio. Here it
read 28x. Locally the single-call ratio ranges 6.4x to 8.8x over 15
trials for both inputs, so the extractor is linear; the measurement was
noisy. The test came in with #13489.

## Fix

Each size is timed as the best of five calls on the same input. The
bound and the claim are unchanged: eight times the input must cost less
than 24 times the time. The minimum discards a call that lost the CPU
and keeps the cost of the code itself.

## Verification

- Locally the best-of-three ratio stays between 7.8x and 8.2x for both
inputs over 5 trials, against single-call ratios up to 8.8x. Three
reruns of the changed test pass.
- Sabotage: wrapping `html_to_markdown` with extra work quadratic in the
input length fails the test (`[0.022, 0.814]`, 36x), so the best-of-five
timing still catches superlinear growth.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 5190682ba1

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

Copy link
Copy Markdown
Member Author

Follow-up on the latest staging run (Repo tests (CPU, gloo-tp-pp)): the float64-reference check passes now, but test_fused_lora_functions_read_local_shards fails one step later at tests/test_tp_native_gloo.py:1076, on the gradient comparison for q_proj.lora_B.default.weight (fused vs PEFT at rtol = 1e-4, atol = 1e-6). It is a different assertion from the one in the earlier comment, and still specific to this PR, since main passes it.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 5d4af11d78

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

Copy link
Copy Markdown
Member Author

One more on the latest staging run: Core zoo (HF=4.57.6 + TRL<1) timed out in test_frozen_input_lora[None-inductor] (Failed: Timeout (>300.0s) from pytest-timeout). That is the compiled LoRA path this PR changes, and main does not time out there, so it is worth checking whether the in-GEMM form adds a recompile or a much slower inductor graph on the 4.57.6 leg.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

For the record, the new Repo tests (CPU, rest), (CPU, rest-2) and (CPU, fsdp2) reds on the latest staging run are not from this PR: they come from main after #16125 (tiled MLP) and are fixed in #16196. The fused LoRA test failure and the inductor timeout noted above are still this PR's.

danielhanchen added a commit that referenced this pull request Oct 30, 2026
…, trainer logger) (#16196)

## Problem

Main went red in three Backend CI shards after #16125 (tiled MLP) landed
(seen on the staging run for #16071, reproduced on main):

- `Repo tests (CPU, rest)`: all of
`tests/test_optimized_precision_conflicts.py` fails with `NameError:
name 'check_tiling_available' is not defined`. The fixture runs
`FastLanguageModel.from_pretrained` from `loader.py` in a hand-built
namespace of stubs, and #16125 added a
`check_tiling_available(unsloth_tiled_mlp)` call there that the
namespace does not provide.
- `Repo tests (CPU, rest-2)`: `tests/test_source_read_encoding.py` flags
`tests/test_tiling_integration.py:148: read_text()`. The new test file
reads checked-in sources with the platform default encoding (7 calls).
- `Repo tests (CPU, fsdp2)`: four tests in
`tests/test_fsdp2_native_accelerator_loop_gloo.py` crash every rank with
`NameError: name 'logger' is not defined` from `_unsloth_trainer_init`.
The harness in `tests/test_fsdp2_native_trainer_args_gloo.py` execs that
wrapper in a stub namespace and auto-stubs the bare helper calls it
makes. #16125 added a `try: revalidate_for_trainer(self) except
Exception as e: logger.warning_once(...)`, and in the harness the
revalidation raises, so the warning reaches `logger`, which only exists
as the real module's import.

In all three cases the product is right (`loader.py` imports
`check_tiling_available`, `_utils.py` imports `logger`); the tests'
namespaces had not followed.

## Fix

- `tests/test_optimized_precision_conflicts.py`: stub every name
`loader.py` imports from `..tiling`, the way the fixture already stubs
the Mistral-format helpers. So a future tiling helper called from
`from_pretrained` does not break the precision checks, which never reach
tiling.
- `tests/test_tiling_integration.py`: every `read_text()` names
`encoding = "utf-8"`.
- `tests/test_fsdp2_native_trainer_args_gloo.py`: the harness namespace
carries a no-op `logger` standing in for `_utils.py`'s module logger.

## Verification

Before (main) and after (this branch), same local environment:

| file | main | this branch |
|---|---|---|
| `tests/test_optimized_precision_conflicts.py` | 20 failed | 19 passed
|
| `tests/test_fsdp2_native_accelerator_loop_gloo.py` | 4 failed | 5
passed |
| `tests/test_source_read_encoding.py` | 1 failed | passed |
| `tests/test_tiling_integration.py` (with unsloth-zoo main for
`tiling_registry`) | n/a | 50 passed |
| `tests/test_fsdp2_native_trainer_args_gloo.py` | passed | passed |

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@danielhanchen
danielhanchen merged commit 91989b1 into main Oct 31, 2026
@danielhanchen
danielhanchen deleted the lora-fused-order branch October 31, 2026 00:28
danielhanchen added a commit that referenced this pull request Oct 31, 2026
`tests/test_lora_fused_passes.py::test_dynamic_compile_with_a_rank_equal_to_the_first_length`
(added in #16071) fails on the Windows cross-platform leg, both
parametrizations:

```
File "...\unsloth\kernels\cross_entropy_loss.py", line 13, in <module>
    import triton
ModuleNotFoundError: No module named 'triton'
```

Seen on the staging run for #16249, which only shows it because that PR
touches this file; any PR that does will hit it.

### Why

The rest of the file runs in the pytest process, where the conftest CUDA
spoof sends `import unsloth` down the GPU path, and that path defines
the kernel modules against the `unsloth_zoo` triton stub when Triton is
not installed. The dynamic-rank case runs in a fresh interpreter with
`UNSLOTH_DISABLE_CPU_FALLBACK=0` and no spoof, so `import unsloth` takes
the CPU path, which never loads the kernels. Its own `from
unsloth.kernels import fast_lora` then needs a real Triton, which a
Windows CPU runner does not have. The product is fine here: the CPU
backend does not use these kernels. The test was relying on Triton being
installed.

### Fix

When `find_spec("triton")` is None, the case script imports `fast_lora`
with the stub injected, the same way `_gpu_init` does, then restores
`sys.meta_path` and drops the stub's `triton*` entries from
`sys.modules`, so `torch.compile` does not see a fake Triton. With
Triton installed, nothing changes.

### Verification

Triton hidden with a `PathFinder` that returns None for `triton*` (same
as the Windows runner: `find_spec` is None, `import triton` raises
`ModuleNotFoundError`), torch 2.10 CPU:

| | main | this PR |
|---|---|---|
| case `plain`, no Triton | `ModuleNotFoundError: No module named
'triton'` | `OK` |
| case `param`, no Triton | `ModuleNotFoundError: No module named
'triton'` | `OK` |
| whole file, Triton installed | | 51 passed, 47 skipped |
danielhanchen added a commit that referenced this pull request Oct 31, 2026
## Summary

A follow-up to #16071 (fused LoRA order: the rank-r term goes into a
fresh buffer and the base GEMM accumulates onto it).

**Tensor subclass types survive the fused LoRA accumulates.** The LoRA
kernels update their output with in-place `addmm_` / `addmv_` / `add_`
and drop the return value. For a storage-backed subclass operand (`X`,
`W`, `A`, `B` or a precomputed `XA`), the in-place method returns the
subclass type, but the kernels returned the plain buffer, so the result
came back as a plain `torch.Tensor`.

With this PR every accumulate keeps what the in-place call returns.
Routing, dtypes, autocast behaviour and arithmetic are exactly as on
main: the same ops run in the same order on the same buffers.

- **`matmul_lora`** (`unsloth/kernels/utils.py`): the fused order
(`_lora_first_addmm`, and the caller-buffer branch) and the
base-then-LoRA accumulate.
- **Decode** (`fast_linear_forward`): the batch-one `addmv_` and the
batched `addmm_`.
- **Dropout and `lora_bias`** (`_matmul_lora_ext` in
`unsloth/kernels/fast_lora.py`): the LoRA accumulate and the bias
accumulate. Plain tensors still return the same `out` object as before.
- **Traced no-grad accumulate** (`addmm_`): the opaque `unsloth::addmm_`
op returns nothing, so a subclass operand takes `out.addmm_`, which is
the op's own body. Plain, fake and functional tensors still use the op.
- **Not changed:** the compiled `unsloth::lora_first_addmm` op. Its
functional alternative is autocast while the op is not, so swapping it
would change values under autocast.

**Earlier revisions of this PR** sent subclass operands to the
base-then-LoRA order and then adjusted autocast and caller-buffer
handling around that. Each of those changed behaviour relative to main
in some dtype or buffer combination, so this revision drops them and
keeps main's routing. The small-CPU shared-product gate from the first
revision stays dropped: no single row cutoff was faster across dtype,
width, rank and threads.

## Results

**Values are main's, bit for bit.** In a CPU script over 28 subclass
cases (each of `X`, `W`, `A`, `B`, `XA` with the fused order on and off,
a caller buffer, the autocast cases with a precomputed `XA`, and the
dropout and bias routes), every output has the same dtype and bits as
main. Under bf16 / fp16 autocast with fp32 operands and a precomputed
`XA`, both give fp32 10000; with half `X` / `XA` over an fp32 base, both
give the autocast dtype.

**Compile:** `torch.compile(fullgraph = True)` over `addmm_` (no grad)
and `matmul_lora` has 0 graph breaks.

**CUDA,** Colab A100 40GB, base = main at d8efd15:
- **Tests:** the 15 LoRA / FP8 test files at this head give 831 passed,
78 skipped, 0 failed.
- **Step time:** Llama-3.2-1B bf16 LoRA r16 SFT step (batch 2 x 512,
compiled), median step time, each arm in a fresh process, head / base /
base / head order twice:

| arm | step ms | median | spread |
|---|---|---|---|
| main | 61.99 / 61.81 / 60.37 / 62.84 | 61.90 | 4.0% |
| this PR | 61.23 / 62.04 / 63.76 / 60.95 | 61.63 | 4.6% |

The difference is inside each arm's own spread. Both arms have 0 graph
breaks and 4 graphs, and per-step losses differ between base runs as
much as between base and head.

## Tests

New in `tests/test_lora_fused_passes.py`. Each compares against plain
operands bit for bit and checks that the result is the subclass:
-
`test_a_subclass_operand_keeps_its_type_through_matmul_lora[X|W|A|B|XA]`,
fused order on and off;
- `test_a_caller_buffer_keeps_its_storage_and_the_subclass[X|A|out]`,
fused order on and off, written into the caller's storage;
- `test_autocast_with_a_precomputed_xa_keeps_fp32_operands_finite`, bf16
and fp16: fp32 10000;
- `test_autocast_with_a_half_xa_over_an_fp32_base_autocasts_the_base`,
bf16 and fp16: 8 in the autocast dtype;
- `test_the_dropout_and_bias_route_keeps_a_subclass[X_lora|A|B]`, with
and without a `lora_bias`;
- `test_decode_keeps_a_subclass_adapter[A|B]`, batch 1 and 3;
- `test_the_traced_no_grad_accumulate_keeps_a_subclass_result[A|B]`, and
`test_the_traced_no_grad_accumulate_keeps_the_op_for_plain_tensors`.

With main's kernels, 35 of these cases fail, all on the result type
(main's values match). The plain-operand cases pass on both.

`tests/test_lora_first_addmm_op.py`: the two re-registration cases run
`unsloth.kernels` in a fresh interpreter that the test stubs do not
reach, so they skip when triton is not installed, as on the macOS and
Windows CI runners. (Main's #16256 already makes the dynamic-rank case
in `test_lora_fused_passes.py` run without triton.)

**CPU,** the 15 LoRA / FP8 test files, 0 failed:

| torch | passed | skipped |
|---|---|---|
| 2.13 | 399 | 317 |
| 2.11 | 387 | 329 |
| 2.6 | 378 | 338 |

## Not covered

- ROCm and XPU.
- Real third-party subclass libraries; the tests use a plain
`torch.Tensor` subclass.
- Gradients: backward accumulates into `dX` / `dA` / `dB` are unchanged.
danielhanchen added a commit that referenced this pull request Oct 31, 2026
## Summary

The fused LoRA order from #16071 (the rank-r term goes first and the
base GEMM accumulates onto it) costs extra host time on every call. That
cost shows up as +4% to +7% step time on NVIDIA bf16 runs that are host
bound: small models, under about 1k tokens per step.
`UNSLOTH_LORA_FUSED_PASSES=0` restores the old speed.

The cost is Python work, not GPU work. A CPU profile of one QKV forward
and backward shows:
- about 220 more Python calls than the kill switch;
- `_lora_fused_ok` run 9 times;
- extra bookkeeping in `_shared_XA` / `_shared_lora_backward`.

Gradient checkpointing repeats all of this in the forward, the recompute
and the backward.

This PR keeps the same arithmetic and removes that host work:
- **One decision per call.** `LoRA_W`, `LoRA_QKV` and `LoRA_MLP` decide
eligibility once in the forward and record it on `ctx`. The backward
reuses the answer when the dtype and compile state match, instead of
re-running `_lora_fused_ok` per matmul. `matmul_lora` takes the caller's
answer through `fused_checked`.
- **Fewer calls in the hot path:**
- the functorch check runs only when a `torch.func` transform is active;
  - the DTensor test is a plain `isinstance` chain;
  - the adapter casts are skipped when the dtype already matches;
- `fast_dequantize` is skipped for unquantized weights, where it
returned `W` unchanged;
  - `_shared_XA` / `_shared_lora_backward` do less per call.

The kill switch and every path that is not eligible for the fused order
are unchanged.

## Results

Colab A100 40GB, bf16, LoRA r16, FineTome 64 rows, seq 2048. Each value
is the median steady step time (steps 3 onward) in ms. Every row is
three fresh-process pairs, main then this PR, on one VM. "Kill switch"
is `UNSLOTH_LORA_FUSED_PASSES=0`, run on both trees.

| model | order | main | this PR | change |
|---|---|---|---|---|
| Qwen3-0.6B 16-bit (host bound) | fused (default) | 272.1 / 266.6 /
276.8 | 258.9 / 262.9 / 267.6 | -3.4% (median) |
| Qwen3-0.6B 16-bit | kill switch | 252.1 / 262.8 / 259.8 | 263.3 /
259.1 / 254.3 | same |
| Llama-3.2-3B 4-bit (host bound) | fused (default) | 320.0 / 315.2 /
317.7 | 310.6 / 311.7 / 306.0 | -2.2% (median) |
| Llama-3.2-3B 4-bit | kill switch | 304.4 / 307.5 / 300.7 | 304.9 /
302.2 / 303.4 | same |
| Qwen3-8B 4-bit (GPU bound) | fused (default) | 507.8 / 508.6 | 507.5 /
507.8 | same |
| Qwen3-8B 4-bit | kill switch | 522.7 | 521.3 | same |

Fused order against the kill switch (pooled kill-switch median, with
that pool's spread):

| model | main | this PR | kill-switch spread |
|---|---|---|---|
| Qwen3-0.6B 16-bit | +4.9% | +1.3% | 4.3% |
| Llama-3.2-3B 4-bit | +4.5% | +2.2% | 2.2% |
| Qwen3-8B 4-bit | -2.8% | -2.8% | |

- **Host-bound cases:** the fused order's remaining cost is inside the
kill switch's own run-to-run spread.
- **GPU-bound case:** the fused order keeps its gain.

CPU, one core, one QKV forward + backward, us per iteration over three
repeats:

| tree | fused | kill switch |
|---|---|---|
| main | 423 / 391 / 377 | 361 / 294 / 301 |
| this PR | 381 / 357 / 310 | 359 / 345 / 312 |

## Correctness

- **Bitwise on A100.** 18 cases with the fused order on and off, 132
output and gradient tensors: this PR equals main, and repeated runs of
each tree are identical.
- **End-to-end losses.** These vary from run to run on main itself
(1.21739 to 1.21777 across three main runs of the same seed). This PR
falls inside that range.
- **Compile.** 0 graph breaks and 4 unique graphs on both trees in a
compiled LoRA step. Recompiles go from 34 to 20.

## Tests

- **A100.** The 15 LoRA / FP8 test files: 835 passed, 78 skipped, 0
failed.
- **CPU.** The same files on torch 2.13, 2.11 and 2.6: 403, 391 and 382
passed, 0 failed.

## Not covered

- L4, H100 and B200 timing. The earlier L4 measurement of the regression
was not repeated here.
- AMD and T4 timing. Neither showed the regression: T4 runs fp16, which
the fused order does not take, and the AMD step is GPU bound.
- DPO and GRPO timing. They use the same LoRA autograd functions.
- The MLP path on CPU, since SwiGLU is Triton only. It is covered by the
GPU runs above.
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