Skip to content

Keep tensor subclass types through the fused LoRA accumulates - #16249

Merged
danielhanchen merged 9 commits into
mainfrom
lora-fused-followups
Oct 31, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
lora-fused-followups

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

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.

…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.
@chatgpt-codex-connector

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-31T01:26:16.847878Z
We couldn’t complete this review. Comment @codex review to try again.
abf94a4 PR opened
ℹ️ 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.

…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]
@danielhanchen danielhanchen changed the title Keep tensor subclasses in the fused LoRA order and skip the shared adapter product for small CPU inputs Keep tensor subclass operands on the base-then-LoRA order Oct 31, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

The Windows cross-platform test failure here (test_dynamic_compile_with_a_rank_equal_to_the_first_length[False|True], ModuleNotFoundError: No module named 'triton') is not from this change. That test is on main already, and it fails on any host without Triton: its fresh interpreter takes the CPU path of import unsloth, then imports unsloth.kernels directly. It only shows up on this PR because the PR touches tests/test_lora_fused_passes.py. #16256 fixes it. A re-run after that merges should clear it, though this branch also edits the same file, so it may need a merge of main first.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 31, 2026
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 to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 31, 2026
@danielhanchen danielhanchen changed the title Keep tensor subclass operands on the base-then-LoRA order Keep tensor subclass types through the fused LoRA accumulates Oct 31, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 31, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 31, 2026
@danielhanchen
danielhanchen merged commit 4b9a0eb into main Oct 31, 2026
@danielhanchen
danielhanchen deleted the lora-fused-followups branch October 31, 2026 04:42
danielhanchen added a commit that referenced this pull request Oct 31, 2026
## 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.
danielhanchen added a commit that referenced this pull request Nov 4, 2026
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]
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