Skip to content

FastLanguageModel LoRA / QLoRA: compile each decoder block as one region - #14398

Merged
danielhanchen merged 7 commits into
mainfrom
dh/s2-w3-legacy
Oct 20, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
dh/s2-w3-legacy

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

FastModel compiles each decoder layer as one region (#10744), but LoRA / QLoRA loaded through FastLanguageModel (llama, mistral, gemma, gemma2, qwen2, qwen3) never got it.

  • FastLlamaModel.patch_peft_model installs the same per-block compile. On by default on torch >= 2.11, where the fused LoRA kernels are traceable; on torch 2.10 forcing it on was slower (14 graph breaks), so it stays off there. UNSLOTH_BLOCK_COMPILE_LEGACY=0 turns off only this path, UNSLOTH_BLOCK_COMPILE=0 all of it.
  • Attention dispatch traces without graph breaks inside a block: the causal / single-query flags are kept as Python bools with a dynamic length, and a plain causal xformers call takes SDPA is_causal while compiling. Eager calls are unchanged.
  • Packed batches keep the stock layer forward (the legacy attention reads packed lengths on the host).
  • Fused kernels still run inside the region: unsloth::rms_layernorm, unsloth::rope_embedding, unsloth::addmm_, unsloth::dequantize_nf4 and the fast_lora autograd functions. 0 graph breaks per step.

Speed

Steady step, main vs this PR, ABBA x3, fresh process per arm, torch 2.14.1 (base repeat spread 1-4%):

model GPU LoRA QLoRA
Qwen3-0.6B bs1 x 512 A100 262 -> 221 ms (1.19x) 311 -> 255 ms (1.22x)
Qwen3-0.6B bs4 x 1024 A100 284 -> 245 ms (1.16x) 322 -> 287 ms (1.12x)
Llama-3.2-1B bs1 x 512 A100 141 -> 123 ms (1.15x) 165 -> 140 ms (1.18x)
Qwen3-0.6B bs1 x 512 T4 fp16 248 -> 197 ms (1.26x)

Compute-bound steps (T4 at 4k tokens per step) are unchanged. Peak memory unchanged.

Tests

  • tests/test_attention_dispatch_compiled_block.py, tests/test_legacy_block_compile_install.py: fail on main, pass here (CPU, torch 2.10, 2.13, 2.14).
  • bf16 step-0 loss within 2e-4 and grad norm within 3.2e-3 relative of main (FastModel vs FastLanguageModel differ by the same order); fp32 tiny Gemma2 identical on vs off.

Not covered

  • gemma / qwen2 parity at real scale, Windows / AMD / Mac.

With a dynamic sequence length the causal flag and the single-query
probes were SymBools, which SDPA and assume_constant_result reject, and
xformers' attention bias objects cannot be traced. Branch them into
bools, and route a plain causal xformers call to SDPA while compiling.
Eager calls are unchanged.
patch_peft_model now installs the per-block compile FastModel uses.
UNSLOTH_BLOCK_COMPILE_LEGACY=0 turns off only this path and
UNSLOTH_BLOCK_COMPILE=0 every block compile. Off before torch 2.11,
where the fused LoRA kernels stay out of a trace, unless set to 1.
The legacy attention reads packed sequence lengths on the host, which
would graph break and recompile per batch inside the compiled block.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-20T21:39:02.381681Z
We couldn’t complete this review. Comment @codex review to try again.
a53c5e7 New commits
🔒 Security Review ⚠️ Failed 2026-10-20T19:21:13.501919Z
We couldn’t complete this review. Comment @codex security review to try again.
b739aa3 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.

@danielhanchen danielhanchen self-assigned this Oct 20, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b739aa38c1

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

and not config.xformers_kwargs
and _configured_softcap(config) is None
):
backend = SDPA

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the fp32 downcast when rerouting xFormers

On sm_100+ GPUs using DoRA without FlashAttention, Q/K/V are promoted to fp32 and xFormers is selected, but this assignment changes backend to SDPA before the existing xFormers-specific fp32 downcast runs. Consequently the condition at lines 961–969 no longer downcasts these tensors, so compiled training may use fp32 SDPA—potentially falling back to the quadratic math implementation and OOMing on long sequences—while the equivalent eager xFormers path uses bf16/fp16. Preserve the original xFormers downcast requirement across this reroute.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd4b229: the reroute records that the call was xformers, and the fp32 downcast condition keeps applying for it when xformers rejects fp32 on that device, so DoRA's fp32 Q/K/V reach SDPA in bf16 / fp16 as they reach xformers eagerly. New test (xformers fp32 unsupported, fp32 inputs, compiled): output was fp32 before, bf16 now and close to the reference.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: dd4b2294c2

ℹ️ 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
danielhanchen merged commit e24afff into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the dh/s2-w3-legacy branch October 20, 2026 22:25
danielhanchen added a commit that referenced this pull request Oct 20, 2026
## Problem


`tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`
fails on main, so the `Repo tests (CPU, rest)` shard is red on every PR
(for example #14395):

```
AssertionError: 3 file reads in the test trees touch a checked-in file with the platform default encoding, so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8": ['tests/test_grouped_gemm_mixed_tma_device.py:218: read_text()', ...]
AssertionError: 2 file reads in the test trees touch a checked-in file with the platform default encoding, ... ['studio/backend/tests/test_diffusion_vae_oom.py:1726: read_text()', 'tests/test_legacy_block_compile_install.py:15: read_text()']
```

Three test files that merged today read checked-in sources with a bare
`read_text()`:

| File | Reads | Added by |
|---|---|---|
| `tests/test_grouped_gemm_mixed_tma_device.py` | 3 | #14358 |
| `studio/backend/tests/test_diffusion_vae_oom.py` | 1 | #13802 |
| `tests/test_legacy_block_compile_install.py` | 1 | #14398 |

The guard is right: on Windows, `read_text()` decodes with the locale
codec (cp1252), so these break as soon as one of those sources gains a
non-ASCII byte.

## Fix

Pass `encoding = "utf-8"` to the five reads. No other change.

## Verification

- On main: `tests/test_source_read_encoding.py`: 2 failed, 14 passed
(the two failures above).
- With this change: the guard and the two touched `tests/` files pass,
apart from 4 `test_legacy_gate` errors.
- Some failures on this host are the same with and without this change,
so they come from the local environment, not this PR:
- the 4 `test_legacy_gate` setup errors in
`tests/test_legacy_block_compile_install.py`;
- 8 failures in `studio/backend/tests/test_diffusion_vae_oom.py` (102
passed).
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…mpile packing test off leaked env (#14425)

## Problem

Two tests on main fail in CI for reasons in the tests, not the product.
They are red on unrelated PRs, for example #14409 and #14365.

**1. `tests/python/test_v100_fullft_precision.py` (10 tests, `Repo tests
(CPU, studio)`)**

```
tests/python/test_v100_fullft_precision.py:80: in _decide
    exec(CODE, {"torch": torch, "os": os}, {"args": args, "model": model})
E   NameError: name 'args' is not defined
```

The test runs the `mixed_precision` template from `unsloth/models/rl.py`
with separate globals and locals dicts. #14394 added
`_unsloth_precision_requested = tuple(getattr(args, k, False) for k in
(...))` to that template. In the generated trainer this runs inside a
function, where the generator sees `args`, so the product is fine. A
generator inside `exec` with a separate locals dict cannot see those
locals, so the test raises `NameError`.

**2.
`tests/test_legacy_block_compile_install.py::test_packed_calls_keep_the_unsloth_layer_forward`
(`Repo tests (CPU, rest)`)**

```
tests/test_legacy_block_compile_install.py:105: in test_packed_calls_keep_the_unsloth_layer_forward
E   assert []
```

The test (from #14398) expects an unpacked call to go through the
compiled block. `_block_compile._wrap` keeps every call on the stock
forward when `UNSLOTH_COMPILE_DISABLE` is `1`, `UNSLOTH_BLOCK_COMPILE`
is `0`, or `UNSLOTH_FORCE_FLOAT32` is `1`. Eight test modules run
`os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")` at import time,
so the result depends on which modules a worker collected. The test
passes alone and fails with any of those variables set.

## Fix

Test only:

- `test_v100_fullft_precision.py`: `exec` the template in one namespace,
as in the trainer's function scope. Results are still read from `args`
and the environment.
- `test_legacy_block_compile_install.py`: the packing test clears the
three variables with `monkeypatch.delenv` before wrapping.

## Verification

- `test_v100_fullft_precision.py`: on main 10 failed (the `NameError`
above); with this change 10 passed.
- `test_legacy_block_compile_install.py` on main:
- with any one of `UNSLOTH_COMPILE_DISABLE=1`, `UNSLOTH_BLOCK_COMPILE=0`
or `UNSLOTH_FORCE_FLOAT32=1` set: 1 failed (the packing test), 5 passed;
- with this change: 6 passed in each of those three cases and with none
set.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
…ers (unslothai#14704)

When a user wraps the model or a training step in their own
torch.compile, the per-layer block
compile wrapper (installed on the FastLanguageModel LoRA path since
unslothai#14398) is inlined into the
outer trace. It then calls torch._dynamo.maybe_mark_dynamic, which
dynamo forbids while tracing,
and its own compiled callable. fullgraph=True always fails with
"Attempt to trace forbidden callable maybe_mark_dynamic"; with
suppress_errors the outer graph
falls back and splits (5 graphs instead of 1 on a tiny Llama).

Fix: if torch.compiler.is_compiling(), the wrapper runs the stock
forward so the outer graph
owns the layer. Outside an enclosing compile nothing changes (same
graphs, same recompile count,
same loss on a tiny Llama).

Tests:
- New tests/test_block_compile.py::test_outer_compile_owns_the_block
(fullgraph, default,
suppress_errors): fails on main, passes here. Checks grads vs the stock
forward, no nested
  compiled call, no graph breaks, one graph.
- Block compile suites on CPU: 60 passed, 4 skipped (CUDA only) on torch
2.13.0 and 2.14.1.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 22, 2026
…rue) (unslothai#14779)

The SDPA GQA routing added in unslothai#14158 asks torch which kernel a call
would get. That probe, `_sdpa_gqa_state` (and `_sdpa_backend_state` for
the varlen choice), runs through
`torch.compiler.assume_constant_result`, and dynamo can only pass such a
function Python constants. unslothai#14398 handled the boolean arguments. Under
`torch.compile(fullgraph=True, dynamic=True)` the head dim and head
counts are still SymInts, so compilation fails before the forward:

```
torch._dynamo.exc.Unsupported: assume_constant_result argument conversion failed
  Cannot convert argument of type SymNodeVariable to a Python constant
```

Repro: `run_attention` plus backward, noncausal GQA on CUDA, Q (2, 8,
32, 64), K/V (2, 2, 32, 64), no mask, SDPA backend. Before unslothai#14158 both
static and dynamic fullgraph passed.

Fix: a small `_constant_probe` wrapper replaces the two bare
`assume_constant_result` wraps. It passes integer arguments through
`operator.index` before the call. Under dynamo that specialises the head
sizes, which are fixed per model. Batch and sequence length stay
dynamic. Plain ints pass through unchanged, so eager and static-shape
routing is identical. `functools.wraps` is avoided on purpose:
`assume_constant_result` marks the wrapped function in place, and
copying its `__dict__` would mark the wrapper too.

Tests (`tests/test_attention_dispatch_compiled_block.py`):
- CPU: `_sdpa_gqa_state` and `_torch_varlen_beats_segments` traced
fullgraph, static and `dynamic=True`, match eager with 0 graph breaks
and one graph across batch / length changes.
- CUDA: real `run_attention` forward plus backward in bf16 GQA, compiled
fullgraph static and dynamic with Inductor. Outputs and gradients match
eager, with 0 graph breaks and one graph under `dynamic=True`.

Results on B200, torch 2.13.0 and 2.14.1:

| | main | this PR |
|---|---|---|
| fullgraph, static | pass | pass |
| fullgraph, dynamic=True | fails before forward | pass, 0 graph breaks
|
| attention dispatch tests (GPU) | 4 failed, 69 passed | 1 failed, 72
passed |

The remaining failure,
`test_plain_causal_attention_traces_with_a_dynamic_length[xformers]`, is
already on main and fails only on a GPU host: the xformers fp32 downcast
gate looks at the host GPU, not at the tensor device. It is left for a
separate change.
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