Repository navigation
LoRA: add the rank-r term inside the base GEMM so small updates are not rounded away - #16071
Conversation
…hare X reads across projections
…into an empty buffer broke block compiles
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…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.
… 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.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…s an operand's storage
…ed path, keep the A-grad layout, default ctx.plain to the old order
…cks, FP8 reference in the module's order
…t undefined values
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
# Conflicts: # tests/test_tp_native_gloo.py
…ng, gate its tests on the API [skip ci]
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
On that runner the fused path's |
…order in every forward and shared backward decision
…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.
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Follow-up on the latest staging run ( |
…or's scale too [skip ci]
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
One more on the latest staging run: |
[skip ci]
|
@codex review |
…, 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>
`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 |
## 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.
## 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.
Summary
The fused LoRA kernels (
LoRA_MLP,LoRA_QKV,LoRA_Wviamatmul_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 functionaltorch.addmmcalls, 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 throughmatmul_lorastill works (a frozen base created underinference_modeincluded). Undervmap/torch.functransforms the eager helper uses the functional calls. Compiled insidetorch.functransforms (grad,jvp,jacrev,jacfwd,vmap) or native forward-mode AD (torch.autograd.forward_ad.dual_level),matmul_lorakeeps the base-then-LoRA order: the op has no forward-mode or batching rule (a compiledjvpreturned zeros, a compiled dual lost its tangent), and a tracedbeta = 0addmm underjvpcrashes torch. The op is used only inside the Dynamo trace oftorch.compile, not undertorch.export(strict or not), which keeps the two functional calls sotorch.funcstill applies to an exported program. Export is recognised by the flagtorch.exportsets, read directly: torch 2.10 / 2.11 Dynamo foldstorch.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 @ Ain 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. Undertorch.compilethe 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 ofLoRA_W,LoRA_QKVandLoRA_MLP. These keep the base-then-LoRA order:lora_dropoutor alora_biasanywhere in the module (a down-only bias included), for the whole module;outbuffer that is not already the output, or that shares storage with X, W, A or B, or that cannot be inspected (traced bytorch.compileormake_fx); a precomputedX @ Asharing 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;torch.export;NF4Tensorreports bf16 over packed storage and has noaddmm_);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);torch.functransforms or under native forward-mode AD;fast_linear_forward, q_len > 1) on a projection with a configuredlora_dropout, matching the training kernels;torch.compile, LoRA weights that are plain tensors rather thannn.Parameter(on torch 2.14 their dynamic shapes broke the backward on a recompile);fuseddecision (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):
Kill switch:
UNSLOTH_LORA_FUSED_PASSES=0restores 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:Speed
ms per step, 2 x 2048 tokens, LoRA r16, default block compile, fresh process per arm, two runs each:
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):
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:
The shared backward frees
A @ X.t()before allocating the combineddY @ B.t(), writes it in place and computeslora_Agradients directly in the[r, K]parameter layout, so its peak is at or below main's. The forward's combinedX @ [A_q; A_k; A_v].t()stays live across the three projections: about2 x tokens x rank x element sizemore (4 MiB at 8192 tokens, rank 128, bf16), plus the concatenatedA(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
tests/test_lora_fused_passes.py:alpha_pattern);matmul_loraequals base GEMM then in-place rank-r add, bit for bit;lora_biasand a down-onlylora_biasin fp16, bf16 and fp32) gives outputs, dX and LoRA gradients bit-identical to the kill switch;lora_Agradients already have the parameter's[r, K]contiguous layout, as row views of one buffer (no copies);torch.compileand undermake_fxfake tracing, a precomputedX @ Asharing the caller buffer (fused and old order), a sparse base weight, multi-token inference with and without a configuredlora_dropout;torch.compile(dynamic = True)ofLoRA_QKVwith plain-tensor andnn.ParameterLoRA 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.X @ Asharing the caller buffer with packed, INT4 and Float8Tensor bases (mocked on CPU), and a 3-D precomputedX @ A;NF4Tensorbase, CSR / CSC / BSR LoRA A weights in the sharedX @ A, a caller buffer sharing storage with the quant state;torch.exportand 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;dXhas the same value and placement as with the kill switch (8 of these fail on the previous head, where QKV'sdXchanged placement). Where a torch's DTensor cannot run main's own order (views of a sharded dim, in-placeaddmm), 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.tests/test_lora_first_addmm_op.py: the op equals the eager sequence bit for bit, passesopcheckincluding its autograd registration, is used by a fullgraph compiledmatmul_lora, gives the eager gradients when that compiled call is differentiated (bf16 and fp32), runs undervmapover X or W, stays out of the graph with the kill switch, and without the op the traced branch keeps the functional form. Compiledgrad,jvp,jacrev,jacfwdandvmaparoundmatmul_lora(bf16 and fp32, eager andaot_eagerbackends) 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 righttorch.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 compiledLoRA_Wforward and backward traces with the op and no graph break (on torch 2.10 / 2.11 Dynamo foldstorch.compiler.is_exporting()to True, which once reached alayoutread Dynamo refuses).NF4Tensorbase, 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 compiledtorch.functransforms, 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 compiledvmapcases pass on both); the fullgraphLoRA_Wtest fails on torch 2.11 with the earlieris_exportingcheck. On an earlier headtest_lora_fused_passes.pyand the dropout / bias and gradient layout files also passed on PEFT 0.18.0 and 0.21.2.aten.addmm_has no sharding strategy there), so that test skips. A sparse base undertorch.exportkeeps main's order on torch 2.6 as well (it has notorch.compiler.is_exporting, so the check readsis_sparse/is_sparse_csr).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.Not covered
torch.compile: only COO and CSR are recognised in traced code (Dynamo refuses to readlayoutthere); eager mode checks every layout.