Repository navigation
Keep tensor subclass types through the fused LoRA accumulates - #16249
Conversation
…apter product for small CPU inputs The eager lora_first_addmm accumulator allocated a plain buffer, so a storage-backed __torch_function__ subclass operand came back as a plain tensor. Those operands now take the functional addmm pair, which keeps the same order and the subclass type. On CPU, concatenating the adapters for one shared X @ A.t() costs more than the extra passes over X below about 2048 rows, so CPU inputs under that size compute one product per projection as before. CUDA and HIP are unchanged. Follow-up to #16071.
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. |
…mall CPU shared-product gate A tensor subclass X, W, A, B, XA or caller buffer (anything whose type is not exactly torch.Tensor or nn.Parameter; quantized weights with a quant state are unchanged) now takes the order used before the fused LoRA order existed, in matmul_lora and in the decision LoRA_W / QKV / MLP record for the backward. This replaces the functional addmm pair, which autocast and could round finite results to inf, and which active function modes also took. The CPU row cutoff for the shared adapter product is removed: it was slower for several shapes and thread counts, so the shared product runs as on main. [skip ci]
|
The Windows cross-platform |
…order, and let a caller's buffer take grad [skip ci]
`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 |
… over an fp32 base
…ype through the in-place accumulates
…es unneeded [skip ci]
…esult type [skip ci]
## Summary Every `Core zoo` cell in `consolidated-tests-ci.yml` is now being cancelled at its 35 minute job cap, on unrelated PRs, with the unsloth_zoo suite at 99%. It is the same failure #14240 fixed at 25 minutes: the suite has grown past the cap. A passing cell from today, for scale: the zoo `pytest -n 4` step reported `14494 passed, 2462 skipped ... in 1770.53s (0:29:30)`, and the whole job ran 34m57s, three seconds under the cap. ## Change - `Core zoo` job: `timeout-minutes: 35` -> `50`, comment updated with the current numbers. - Unchanged: the 5 minute `PYTEST_TIMEOUT` per test, which is what names and stack-dumps a genuine hang. The job cap only bounds the total. ## Evidence Staging Core runs since 2026-10-30 21:28 UTC, Core zoo cells by combo: | PR | HF=4.57.6 | HF=default | HF=latest | |---|---|---|---| | #16041 | failure | cancelled | cancelled | | #16249 | cancelled | cancelled | cancelled | | #16250 | cancelled | cancelled | cancelled | | #16257 | cancelled | cancelled | cancelled | | #16255 (run 1) | cancelled | success (34m57s) | success (28m46s) | | #16255 (run 2) | success | cancelled | cancelled | The cancelled cells end with `##[error]The operation was canceled.` while the suite is printing its last progress lines (98-99%). ## Tests `tests/studio/test_zoo_suite_parallel_isolation.py`, `test_workflow_guards_run_unfiltered.py` and every test that reads `consolidated-tests-ci.yml`: 267 passed. ## Not proven - This PR's own CI run is the first measurement at the new cap; whether 50 minutes leaves enough headroom as the suite keeps growing is not known.
The in-place addmv_ / addmm_ into out's 1-D / 2-D view returns the adapter's tensor subclass (#16249), but discarding that return handed back a plain tensor. Re-tag out itself with as_subclass, which keeps its strides. [skip ci]
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,Bor a precomputedXA), the in-place method returns the subclass type, but the kernels returned the plain buffer, so the result came back as a plaintorch.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.fast_linear_forward): the batch-oneaddmv_and the batchedaddmm_.lora_bias(_matmul_lora_extinunsloth/kernels/fast_lora.py): the LoRA accumulate and the bias accumulate. Plain tensors still return the sameoutobject as before.addmm_): the opaqueunsloth::addmm_op returns nothing, so a subclass operand takesout.addmm_, which is the op's own body. Plain, fake and functional tensors still use the op.unsloth::lora_first_addmmop. 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,XAwith the fused order on and off, a caller buffer, the autocast cases with a precomputedXA, 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 precomputedXA, both give fp32 10000; with halfX/XAover an fp32 base, both give the autocast dtype.Compile:
torch.compile(fullgraph = True)overaddmm_(no grad) andmatmul_lorahas 0 graph breaks.CUDA, Colab A100 40GB, base = main at d8efd15:
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 alora_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], andtest_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 rununsloth.kernelsin 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 intest_lora_fused_passes.pyrun without triton.)CPU, the 15 LoRA / FP8 test files, 0 failed:
Not covered
torch.Tensorsubclass.dX/dA/dBare unchanged.