Skip to content

Compile each transformer block as one region for every FastModel model (LoRA and QLoRA) - #10744

Merged
danielhanchen merged 44 commits into
unslothai:mainfrom
TarzanZhao:perf/qwen3_5-cpu-overhead
Oct 15, 2026
Merged

danielhanchen merged 44 commits into
unslothai:mainfrom
TarzanZhao:perf/qwen3_5-cpu-overhead

Conversation

@TarzanZhao

@TarzanZhao TarzanZhao commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fine-tuning ran each transformer layer as many small, separately compiled pieces with eager glue in between, so on small and mid-sized models the GPU spent much of every step waiting on the CPU. This PR compiles each decoder layer as one torch.compile region, for every model loaded through FastModel / FastVisionModel, with LoRA and 4-bit QLoRA inside the region. The model-independent half of the original change (Trainer, bitsandbytes and fla launch overhead) landed separately in #11238; the Qwen3.5-only fused layer this PR started with is replaced by the generic version and deleted.

New files: unsloth/models/_block_compile.py (the per-layer region) and unsloth/models/_gdn_op.py (fla's Gated DeltaNet chunk kernel as an opaque custom op, so Qwen3.5 / Qwen3.6 layers compile as one graph). vision.py installs it at the end of post_patch_model; import_fixes.py gains one torch < 2.8 fix (below).

What the block does

  • Finds every *DecoderLayer class and compiles its stock forward once (fullgraph=False, sequence dims marked dynamic up front, no per-length recompiles).
  • Each layer's first call compiles with errors raised; a layer that cannot compile retries with flex_attention outside the region, then keeps the stock forward. The mode is pinned per layer so a gradient-checkpoint recompute never switches graph, and a failure sets the starting mode for sibling layers of the same kind.
  • Training forwards only: eval and generation keep the stock forward, so their logits match transformers bit for bit.
  • Inside a block: Unsloth's decode-aware attention is inlined; bitsandbytes NF4 uses Unsloth's Triton dequantize; Gemma-4 sliding layers take is_causal SDPA when the mask is a plain band; Qwen3.5's fla chunk kernel and causal conv run as traceable ops.
  • MoE experts stay inside the block unless tracing would make zoo fold their LoRA delta into the whole expert stack (Gemma-4); those experts run outside, one graph break each.
  • Stays off on torch < 2.7, under UNSLOTH_FORCE_FLOAT32 (fp16-only GPUs for Qwen3.5, Gemma 3 / 3n / 4, Qwen3-MoE, GLM-4 MoE, gpt-oss), and for gpt-oss. UNSLOTH_BLOCK_COMPILE=0 turns it off; UNSLOTH_COMPILE_DISABLE also does.
  • torch < 2.8: torch.compiler.disable(fn, recursive = False) marks fn itself there, so unsloth_zoo's decode-aware disable was disabling the function it runs. import_fixes.fix_torch_compiler_disable_unless_decode hands it a copy instead (no-op on 2.8+).

Speed

Step time, main (merge base) vs this PR, interleaved main, head, head, main on one rented GPU, fresh process per arm, 20-30 steps, median of steady steps. Peak memory equal in every pair.

model GPU LoRA (16-bit) QLoRA (4-bit)
Qwen3-0.6B A100 338 -> 161 ms (2.10x) 438 -> 190 ms (2.30x)
Qwen3.5-0.8B A100 350 -> 213 ms (1.64x) 458 -> 234 ms (1.96x)
gemma-4-E2B-it A100 / H100 606 -> 425 ms (1.43x) 677 -> 390 ms (1.74x)
gemma-4-12b-it A100 1131 -> 1081 ms (1.05x) 1022 -> 921 ms (1.11x)
gemma-4-26B-A4B-it A100-80GB 803 -> 631 ms (1.27x) 946 -> 694 ms (1.36x)
Qwen3.6-35B-A3B RTX PRO 6000 / A100-80GB 516 -> 465 ms (1.11x) 1399 -> 827 ms (1.69x, profile)

The gain is largest where the step is launch-bound (small and MoE models) and smallest on large dense models. The first step compiles longer (for example 32 s -> 170 s on gemma-4-E2B, A100), so very short runs can come out slower overall.

Correctness

  • fp32 one-step parity, block on vs off, LoRA and QLoRA: loss within 1.4e-4 and LoRA grad norms within 1.5e-3 relative on Qwen3, Qwen3.5, Llama-3.2, gemma-3, gemma-4-E2B and a Gemma-4 MoE, on torch 2.7.1, 2.8, 2.9.1, 2.10, 2.11, 2.12.1, 2.13 and 2.14.1 (T4, L4, A100, B200).
  • Graph breaks: 0 for the dense models above on torch 2.8+; Gemma-4 MoE 8 per step (experts outside the block).
  • AMD gfx1151 (ROCm torch 2.11): base 38/38, head 49/49 tests pass.
  • Regression suite (103 cases, base vs head): 0 regressions, 0 metric moves. sft, vision_sft (Qwen2.5-VL, Gemma-4), vision_grpo and inference_smoke base vs head: no regression.

Not covered

  • No speedup where the block stays off: fp16-only GPUs for the float32-forced families, Gemma-3 on L4 (flex attention exceeds shared memory), torch 2.7 QLoRA (torch's own duplicate-tensor guard keeps it eager).
  • Models loaded through FastLanguageModel's older Llama path do not get the block yet.
  • MLX does not use this path; Windows with an NVIDIA GPU was not run.

@danielhanchen

Copy link
Copy Markdown
Member

This also drops the torch.cuda.synchronize() in Optimizer8bit.step for non-paged optimizers and defaults gradient checkpointing to preserve_rng_state=False, and the always-on fused layers push the first warm step from about 8 to 14.5 seconds, so could you confirm those three on a dropout-enabled LoRA run before I review? The Trainer, bitsandbytes and fla launch changes are model independent, so splitting them out from the Qwen3.5 specific fused-layer work would make this much easier to land.

@TarzanZhao
TarzanZhao marked this pull request as ready for review September 10, 2026 23:51

@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: af5755bf2b

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

Comment thread unsloth/models/_utils.py Outdated
_fn = fn,
**kwargs,
):
kwargs.setdefault("preserve_rng_state", False)

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 Scope the RNG-state bypass to the checked model

When gradient checkpointing is used with lora_dropout > 0, the first post_patch_model call occurs before _get_peft_model injects the dropout modules, so this wrapper globally defaults both checkpoint functions to preserve_rng_state=False; the second post-patch check sees the new dropout and returns without undoing that wrapper. The checkpoint recomputation can therefore use a different LoRA dropout mask from the forward pass, producing gradients inconsistent with the reported loss. Avoid changing the global default based on a pre-adapter model, or explicitly restore/preserve RNG once stochastic modules are added.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/_qwen3_5_layer.py Outdated
Comment on lines +248 to +249
if not m.disable_adapters and not m.merged and m.active_adapters == adapters:
return params

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Refresh cached LoRA parameters when scaling changes

When PEFT's set_scale or scale_layer changes the active adapter's scaling after the first fused forward, none of the three revalidated flags changes, so this returns the cached tuple containing the old scaling float. Subsequent Qwen3.5 fused forwards therefore silently keep using the previous adapter multiplier even though the ordinary PEFT forward would use the updated value. Include the current scaling in the cache validation or read it live on every call.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/_qwen3_5_layer.py Outdated
Comment on lines +257 to +260
if type(m) is nn.Linear:
if m.bias is not None:
return None
return (m.weight, None, None, 1.0)

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 Fall back when fused child modules carry execution hooks

When a Qwen3.5 model uses forward pre-hooks on its leaf modules, such as Accelerate's _hf_hook for CPU or disk offload, the modules remain exact nn.Linear instances and are accepted here, but the fused path consumes the raw weights through F.linear instead of invoking those modules. If the hook is responsible for staging an offloaded weight or moving its input, it never runs and the forward can fail with a device mismatch or use an unstaged tensor; ordinary module execution would honor the hook. Reject modules with _hf_hook or registered forward hooks, or explicitly preserve their execution semantics.

Useful? React with 👍 / 👎.

@TarzanZhao TarzanZhao changed the title [Experimental] Qwen3.5-9B LoRA SFT (unsloth-cli.py) on B200: 1.28x faster step from 8 changes, with takeaways for the repo's acceleration [perf] Qwen3.5-9B LoRA SFT with unsloth-cli.py on a B200: 0.85 s to 0.66 s at 1 GPU, mostly from CPU-side per-step overhead Sep 11, 2026
@TarzanZhao
TarzanZhao marked this pull request as draft September 12, 2026 23:41
@danielhanchen

Copy link
Copy Markdown
Member

Still waiting on the dropout-enabled LoRA check for the dropped Optimizer8bit.step sync and the preserve_rng_state=False default, plus the first-step cost of the always-on fused layers. Splitting the Trainer, bitsandbytes and fla launch changes into their own PR from the Qwen3.5 specific work in _qwen3_5_layer.py would let me land the model-independent half quickly.

TarzanZhao and others added 10 commits September 14, 2026 09:42
…s set

transformers' training_step re-asserts model.train() on every micro-step; on the
PEFT-wrapped Qwen3.5-9B that is a recursive walk over ~2k modules (~13 ms CPU per
micro-step) while the GPU idles. Assert it once, redo only after a root .eval().

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 50aa375)
…icro-step

Trainer.floating_point_ops calls model.num_parameters(exclude_embeddings=True) on
every micro-step, a full named_modules/named_parameters walk (~13 ms CPU) for a
number that never changes. Cache it per model object.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 74cfe20)
…paged 8-bit optimizers

Optimizer8bit.step drains the device after every parameter update (256 times per
step here). Only paged optimizers need that sync; plain adamw_8bit launches
ordinary kernels on the current stream.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 92e6228)
With compile_fla_no_autotune in effect every fla autotuner reuses one config for
every key, yet each launch still built fla's AutotuneKey and Triton's own key
(~25 us of Python). Qwen3.5's GDN layers issue ~2,500 such launches per step.
Once a config is known, call fn.run with it straight away.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 5a78b64)
The generated GDN forward is compiler-disabled because it calls fla's
chunk_gated_delta_rule; the ~25 aten ops around that kernel (4 projections,
depthwise conv + SiLU, split/reshape, sigmoid, softplus gate, repeat_interleave)
ran eagerly in 24 layers x forward/recompute/backward on every micro-step.
Put them in one torch.compile region with the weights as inputs so a single
graph serves every layer; the fla kernel, gated RMSNorm and out_proj are
unchanged. Training path only; LoRA-wrapped projections or a fused
causal-conv1d fall back to the original forward.
UNSLOTH_DISABLE_GDN_FAST_FORWARD=1 disables it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 692af2f)
pre = input_layernorm + mixer input projections (+ q/k norms and RoPE for the 8
attention layers); the fla delta rule / gated RMSNorm or SDPA stay eager; post =
out_proj (+ attention gate) + residual + post_attention_layernorm + LoRA MLP +
residual. Replaces ~6 compiled-region calls and several eager ops per layer with
two, weights as inputs so one graph per region kind serves all layers. Same
dtype boundaries as the stock path. Falls back per layer for caches, merged or
non-vanilla LoRA, eager attention. UNSLOTH_DISABLE_QWEN3_5_LAYER_FUSION=1 disables.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 7b9593e)
…many layers engaged

The static check only recognised nn.SiLU, but ACT2FN['silu'] is transformers'
SiLUActivation (forward = F.silu), so every layer fell back to the stock path and
the previous commit changed nothing at runtime. Both patches now print how many
layers took the fast path so a silent fallback is visible in the log.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 52e173f)
Inside a fused kernel inductor keeps bf16 intermediates in fp32, so the residual
add feeding the post-attention norm, the RoPE products and similar chains were
no longer rounded where the eager path rounds them (step-1 hidden states off by
2.4%). emulate_precision_casts inserts those roundings.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit dd270eb)
pre (norm + projections, + q/k norms) and mid (out_proj / attention gate +
residual + post norm) replace eager ops and round like eager; the MLP region
and a separate RoPE region are compiled like the stock graphs (inductor
defaults). The GDN padding mask is applied before the norm (RMSNorm(0) = 0),
so the norm output's rounding is not left to the fuser. Per-layer outputs now
match the stock forward bit for bit with and without padding.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 4eeb663)
Kernel launches, allocations and extern GEMM calls of each region are issued
from generated C++ rather than the Python wrapper. Same kernels and numbers;
micro-benchmark: 0.27 -> 0.16 ms CPU per no-grad region call, ~0.5x with
autograd. More compile time on a cold cache. UNSLOTH_QWEN3_5_CPP_WRAPPER=0
disables.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Aucx4gqz6Kx3fPb5KpkfN
(cherry picked from commit 2b0d1ce)
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 379738e40a

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

if isinstance(module, torch.nn.ModuleList)
and len(module) > 0
and type(module[0]).__name__.endswith("DecoderLayer")
and all(type(m) is type(module[0]) for m in module)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include heterogeneous decoder layer lists

_layer_lists discards an entire ModuleList unless every entry has the first layer's exact class. FastModel-supported hybrid stacks such as Jamba alternate JambaAttentionDecoderLayer and JambaMambaDecoderLayer, so neither class reaches _decoder_layer_classes and patch_block_compile silently installs none of the advertised block-compilation optimization for that model. Discover each *DecoderLayer class in a mixed list rather than requiring homogeneity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not a correctness issue: mixed stacks (Jamba, Zamba) keep the stock forward exactly as on main. Extending the block to them is new coverage that needs its own Mamba-kernel compile and parity runs, not a fix here.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 66d37e62d4

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review October 15, 2026 16:16
@danielhanchen
danielhanchen merged commit c69969d into unslothai:main Oct 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 20, 2026
… per class (unslothai#14397)

## Summary
The per-decoder-layer compile (unslothai#10744) only found ModuleLists whose
elements were one class named `*DecoderLayer`, so hybrid stacks and
layers named `*Block` / `*Layer` never got it.

- Lists found before are found and treated exactly as before.
- New: lists of `GradientCheckpointingLayer` subclasses (mixed classes
allowed) held next to a token embedding, outside vision / audio towers;
without that base class, one class ending `DecoderLayer` / `Block` /
`Layer`. Each class is wrapped once; the decision is per instance.
- Newly compiled: gpt_neox, gpt2, the t5 decoder, olmo_hybrid, mllama
text (self and cross attention), jamba attention layers, nemotron_h
attention / MLP blocks.
- Mamba-style SSM layers in the new lists stay eager (under a trace
transformers replaces the CUDA scan kernels with its torch scan);
`UNSLOTH_BLOCK_COMPILE_SSM=1` opts in.
- Shared layers count once; instances of a wrapped class outside the
found lists (the T5 encoder) keep the stock forward; the dynamo
recompile limit covers every layer kind of a class.

## Tests
- `tests/test_block_compile_discovery.py` (meta-device models from
default configs, toy stacks): 18 of 23 fail on main, 24 pass here on
torch 2.10, 2.13, 2.14 and transformers 4.57.6 / 5.17.
- fp32 one-step parity, block compile on vs off (tiny random gpt_neox,
gpt2, olmo_hybrid, mllama text, jamba, t5, LoRA): loss and grad norm
within 1e-7 relative, 0 graph breaks (jamba: 2, its MoE experts stay
outside the block as before).

## Not covered
- No step-time numbers for the newly covered architectures.
- SSM opt-in not run on GPU.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 20, 2026
…ion (unslothai#14398)

## Summary
FastModel compiles each decoder layer as one region (unslothai#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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Oct 24, 2026
…(torch < 2.14) (unslothai#15000)

On torch below 2.14, Inductor can generate a looped reduction that
stores a buffer in one loop and reads it back in a later loop of the
same kernel, with no barrier in between. Triton's coalesce pass is free
to give the store and the read-back different thread layouts, so one
warp reads values another warp has not written yet. The result is
silently wrong gradients.

This is upstream pytorch/pytorch#198562 (Triton's view in
triton-lang/triton#10924 is that the kernel author has to insert
`tl.debug_barrier()`). PyTorch fixed it in pytorch/pytorch#190519
(commit 62a4f51), which is in v2.14.0 and v2.14.1 but not in v2.12 or
v2.13. Every torch below 2.14 that Unsloth supports generates these
kernels.

## How it shows up in Unsloth

Block-compiled Qwen3.5 LoRA training (FastModel, which compiles each
decoder layer as one region since unslothai#10744, in 2026.10.7) hits it in the
full-attention q-norm + partial RoPE backward reduction (head_dim 256).
When autotuning picks `R0_BLOCK = 256`, the reduction loop runs once,
the store of the normalized gradient and its read-back land on different
warps, and about 3% of rows come out as garbage. Whether a process is
hit depends only on that autotune pick, so it looks random from run to
run:

| Qwen3.5-0.8B LoRA SFT, bf16, L4, torch 2.11 | grad norm, batches 1 to
5 |
|---|---|
| block compile off (reference) | 0.81, 0.91, 0.88, 0.90, 0.79 |
| main, reduction autotuned to R0_BLOCK 128 | 0.81, 0.91, 0.87, 0.90,
0.79 |
| main, reduction autotuned to R0_BLOCK 256 (4 of 6 processes) | 27618,
28110, 36716, 26878, 54194 |

Forcing the config proves it is causal: R0_BLOCK 256 gave corrupted
gradients in 9 of 9 processes, R0_BLOCK 128 clean in 6 of 6. The kernel
run on its own with random inputs reproduces it in 4 seconds (RTX PRO
6000, torch 2.11, Triton 3.6): wrong at (XBLOCK, R0_BLOCK, num_warps) =
(2, 256, 2), (4, 256, 4), (8, 256, 8), exact at R0_BLOCK 128 and 64. In
the TTGIR of the failing config the loop 1 store uses `warpsPerCTA = [1,
2]` and the loop 2 read-back `warpsPerCTA = [2, 1]`.

## The fix

`fix_inductor_reduction_readback_race` in `unsloth/import_fixes.py`
backports pytorch/pytorch#190519:

- wraps `TritonKernel.load` / `TritonKernel.get_load_buffer` so a load
of a buffer whose store left the CSE cache (`cse.invalidated_stores`) is
preceded by `tl.debug_barrier()`, written into the same buffer the load
goes to (loop body, or hoisted body);
- skips itself when `TritonKernel.load` already reads
`invalidated_stores` (torch 2.14+), so it never doubles the barrier, and
is idempotent;
- sets a no-op `post_grad_custom_post_pass` whose `uuid()` joins the FX
graph / AOTAutograd cache key, so kernels compiled before the update are
rebuilt instead of loaded from a warm cache. A user's own post-grad pass
is left alone.

Registered in `_gpu_init.py` right after
`fix_dynamo_config_thread_visibility`, so on torch 2.12+ the config
value is mirrored to the autograd threads that compile the backward.

## Verification (Colab L4, torch 2.11, main + this change)

- `tests/test_inductor_readback_barrier.py`: 7 passed on the L4 (6 CPU
logic tests + 1 GPU codegen test). The CPU tests also pass on torch
2.6.0 and 2.13.0, and the patch applies to the real `TritonKernel` on
both.
- The upstream test function from #190519 (two-pass layer norm): no
barrier on main, barrier with this change, both match eager.
- Qwen3.5-0.8B SFT with the reduction forced to the racy R0_BLOCK 256:
main corrupted on all 5 batches (a per-call probe recomputing the kernel
output in torch from pre-launch inputs: 29 of 30 calls wrong), this
change clean in 3 of 3 processes (0 of 30 calls wrong, max relative
error 0.0033 = bf16 rounding, barrier present in the kernel); with free
autotuning 2 of 2 clean.

## Cost

Exclusive Colab L4, torch 2.11, LoRA SFT (batch 4, 512-token rows),
fresh process and fresh Inductor / Triton caches per run, runs
alternated A B B A A B, median step time over steps 11 to 30:

| model | main medians (s) | this change medians (s) | ratio | main
spread | kernels with a barrier (main / this change) | peak memory |
|---|---|---|---|---|---|---|
| Qwen3.5-0.8B | 0.3178, 0.3190, 0.3113 | 0.3205, 0.3258, 0.3206 | 1.009
| 2.4% | 7 / 8 of 96 | 2.853 GB both |
| Qwen3-0.6B | 0.2316, 0.2248, 0.2253 | 0.2276, 0.2283, 0.2246 | 1.011 |
3.0% | 5 / 5 of 41 | 2.326 GB both |

Qwen3-0.6B generates no kernel with this pattern, so its code is
unchanged and its 1.1% is run-to-run noise; Qwen3.5's 0.9% is inside the
2.4% spread of main against itself. Losses and grad norms match between
the arms.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
…nslothai#14808)

Since unslothai#10744 (in 2026.10.7), FastModel compiles each stock decoder layer
as one `torch.compile` region. With padding-free packing on (the
default), every step is one packed row whose length changes per step.
Inside the compiled region `hf_packed_attention` cannot run its varlen
kernel, so it falls back to SDPA over the dense block-causal mask. On
SM100 (B200) that call goes to cuDNN attention, which builds a new plan
for every new sequence length (forward, recompute and backward). On
torch 2.11 and 2.12 those builds are slow enough to dominate the step.
FastLanguageModel is not affected because its block wrapper already
sends packed rows to the uncompiled forward.

## Change

- `_block_compile` sets `hf_packed_attention.IN_COMPILED_BLOCK` while
one of its own compiled decoder blocks runs.
- In that window, a packed call (`packed_seq_lengths` present) leaves
the graph through a `torch.compiler.disable` copy of the wrapper and
runs the varlen kernel as it does in eager mode (one graph break per
layer; norms, MLP and LoRA around it stay compiled), but only when it
pays off:
- torch < 2.13 (compiled cuDNN plans per new length cost about 0.3 to 12
s on 2.11, about 0.15 s on 2.13, with cuDNN 9.19 or 9.20 alike),
- the eager wrapper has a varlen kernel for that device / dtype / head
dim / window (torch varlen, flash-attn or xformers),
- SDPA over the dense mask would pick cuDNN (`torch._fused_sdp_choice`).
- The verdict is computed once per (device, dtype, head dim, window)
with real tensors and baked into the block's graph
(`assume_constant_result`), so it adds no guard, recompile or per-call
cost.
- Everywhere else (T4 and other GPUs without a varlen kernel, ROCm,
torch >= 2.13, a user's own outer `torch.compile`, unpacked batches,
`UNSLOTH_HF_PACKED_VARLEN=0`) the code path is the same as before.

## Numbers

Qwen3-0.6B LoRA SFT, 16bit, padding-free, alpaca rows, batch 4, 25
steps, median s/step of steps 6 to 25, base and head interleaved (base,
head, head, base) in fresh processes on one B200 (shared host):

| torch | main | always leave the graph (first commit) | this PR |
|---|---|---|---|
| 2.11 | 0.384 / 0.388 | 0.28 / 0.35 (15 steps) | 0.245 / 0.257 |
| 2.12 | 0.392 / 0.379 | 0.339 / 0.287 | 0.292 / 0.287 |
| 2.13 | 0.189 / 0.158 | 0.282 / 0.253 | same path as main (0 graph
breaks) |

Tesla T4 (fp16, no varlen kernel, Kaggle), same job, 20 steps: leaving
the graph unconditionally was 0.335 / 0.345 s/step against 0.225 / 0.218
on main, every packed call falling back to SDPA anyway. With the gate T4
takes the main path (0 graph breaks): 0.209 / 0.206 against 0.211 /
0.225 (16bit), 0.241 / 0.215 against 0.324 / 0.215 (4bit).

Losses match main within about 3e-3 per step on every arm; peak memory
equal (1.97 to 2.02 GB 16bit, 1.40 GB 4bit on T4).

## Tests

- `tests/test_block_compile.py`: the compiled block sets and restores
the flag, never on the stock forward, and still runs when the packed
module was never imported.
- `tests/test_hf_packed_attention.py`: a packed row the gate sends out
runs the wrapper eagerly while a CPU row, an outer compile without the
flag and unpacked rows stay in the graph; the gate refuses non CUDA
devices, unsupported windows, head dims past 256 or not a multiple of 8,
and torch >= 2.13; the verdict is computed once with real tensors while
tracing (an `lru_cache` wrapper would be traced through and always say
no); on CUDA the traced verdict matches the eager probe and a row it
sends out takes the varlen kernel (asserted on SM100 with torch < 2.13).
- GPU tests pass on B200 with torch 2.11, 2.12 and 2.13.

## Not covered

- Unpacked batches with variable-length padding masks probably hit the
same cuDNN plan rebuilds on SM100 with torch < 2.13; not changed here.
- Not run on H100 / A100 with flash-attn installed, or with GRPO.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 4, 2026
…2.10 (unslothai#16234)

## Summary

Inside the per-layer compiled block (unslothai#10744, `2026.10.6`), Dynamo on
torch 2.8/2.9 evaluates `hasattr(query, "dim")` as `False` (fixed in
torch 2.10, pytorch/pytorch#167651). `_dropped_causal_mask` therefore
falls through and stock flex attention receives `attention_mask=None`
(bidirectional attention) for unpadded training rows, such as SFTTrainer
at batch size 1, on Qwen3.5/3.6 (`head_dim=256`) on H100. On
`Qwen/Qwen3.5-0.8B` (FastModel fp32, 300 tokens, H100, torch 2.9.1),
changing only the last token moves 74,246,486 of 74,247,680 earlier
train-mode logits before this fix and 0 after (SFTTrainer step-1 loss
0.4505 vs 1.3346 causal; 1.3304 after). This PR adds `_is_4d`, which
matches real tensors with `isinstance(query, torch.Tensor)` (Dynamo
reads that correctly on every version) and keeps the duck-typed `dim()`
check for eager stand-ins. All four `hasattr(query, "dim")` checks in
the flex wrapper now use it: the dropped causal mask and the head_dim >
256 kernel options were both lost inside compiled blocks on torch <
2.10, and the other two sit behind torch >= 2.10 device gates. Eager
routing is unchanged: 672 of 672 predicate cells (query kind x key
length x mask form x `is_causal`) match the merge base.

## Tests

- `test_a_dropped_mask_is_still_causal_in_a_compiled_block` in
`tests/test_flex_maskless_sdpa.py`: checks a mask-less causal call under
`torch.compile(..., backend="eager")` against SDPA `is_causal=True`
(CUDA-only; fails without the fix on torch <= 2.9, passes with it).
- Existing flex and block-compile suites on H100: 362 passed, 10 skipped
on torch 2.9.1 (plus the 1 pre-existing `test_flex_mask_graph_breaks.py`
failure) and 369 passed, 4 skipped on torch 2.14.1.
- `test_wrapper_injects_kernel_options_inside_a_compiled_block` in
`tests/test_flex_large_head_dim_kernel_options.py` (CPU): head_dim 512
kernel options reach a compiled call.
- A100, torch 2.9.1: every `tests/test_flex_*.py` gives 268 passed with
this branch. Before the `_is_4d` change, the new compiled kernel-options
test failed. `test_flex_mask_graph_breaks.py` fails on 2.9.1 both before
and after (pre-existing). torch 2.10.0: 271 passed on both.
- FastModel LoRA in train mode with flex attention (tiny Qwen3.5
head_dim 256 and tiny Qwen3, A100, torch 2.9.1): changing only the last
token moved 56,150,370 of 74,247,680 earlier logits at the merge base
and 0 with this PR, and the loss matches the torch 2.10 value.

---------

Signed-off-by: Yufan Zhuang <[email protected]>
Co-authored-by: oobabooga <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
tsautier pushed a commit to tsautier/unsloth that referenced this pull request Nov 15, 2026
…ma-4-12b training (unslothai#17817)

gemma-4-12b training spent about half of its GPU time in attention.
Inside a compiled block, every Gemma-4 layer (sliding hd256 and global
hd512) fell back to masked memory-efficient SDPA: it computes all S x S
scores with a dense bias and repeats the key / value heads (16x on the
global layers). Block compile removes launch gaps but leaves that cost
in place, which is why unslothai#10744 alone gave this model only 1.05-1.11x.

## Changes

1. **Sliding layers longer than the window** (`_block_compile.py`): run
the existing interval kernel, which reads only each row's window,
instead of masked SDPA. Within the window, flash with `is_causal` is
used as before. Kill switch: `UNSLOTH_BLOCK_SLIDING_KERNEL=0`.
2. **Global hd512 layers** (`_block_compile.py`): block compile now
marks a plain causal mask before the block, so the compiled head_dim 512
kernel takes these layers. It reads the single KV head in place.
3. **dK / dV backward with one KV head** (`large_head_attention.py`): it
ran on only 64 programs. It is now split over query-head groups when SMs
would sit idle (A100: 1.5x on that layer). Kill switch:
`UNSLOTH_LH_DKDV_SPLIT=0`.
4. **Gemma-4 sliding router hook**: it was never installed when the
hd512 router wrapped it first. It now installs beneath the wrapping
router (sequences up to 1024: 1.07-1.08x).
5. **ROCm**: the compiled hd512 router test skips on ROCm, where that
router is disabled.

## Results

gemma-4-12b-it with random weights from the real config, FastModel,
batch 1, GC `"unsloth"`, adamw_8bit, transformers 5.22.1. Runs were
ordered base, head, head, base. Repeated runs of the same arm differed
by 0-2.5%.

| arm | A100-80 ms (main -> PR) | G4 ms (main -> PR) | peak GB |
|---|---|---|---|
| QLoRA 2048 | 1426 -> 1005 (1.42x) | 919 -> 626 (1.46x) | 8.5 -> 8.5 |
| LoRA 2048 | 1373 -> 958 (1.44x) | 874 -> 586 (1.48x) | 24.0 -> 23.6 |
| QLoRA 8192 | 9907 -> 4108 (2.44x) | 6546 -> 2520 (2.60x) | 10.6 ->
11.9 (A100), 10.7 -> 10.7 (G4) |
| Full FT 2048 (8-bit Adam) | 1991 -> 1566 (1.27x) | 1205 -> 916 (1.31x)
| 74.6 (fits) |
| QLoRA 1024 | 603 -> 562 (1.07x) | 367 -> 341 (1.08x) | 8.2 |

Attention alone, forward + backward per layer, in ms (masked SDPA on
main -> this PR):

| layer | seq | A100 | G4 | L4 |
|---|---|---|---|---|
| sliding hd256 | 2048 | 9.9 -> 2.5 | 6.2 -> 1.0 | 19.2 -> 3.4 |
| sliding hd256 | 8192 | 107 -> 7.6 | 75 -> 3.9 | 251 -> 20 |
| global hd512 | 2048 | 22.1 -> 7.5 | 12.0 -> 5.9 | 39.7 -> 12.2 |
| global hd512 | 8192 | 210 -> 86 | 143 -> 40 | 542 -> 203 |

Against an fp64 reference, the kernel's error is equal to or lower than
masked SDPA's, at scale 1.0 and 1/sqrt(d).

## Correctness

- **fp32 eager reference:** a tiny Gemma-4 copy with softer attention,
seq 256, past its 64 window. LoRA gradient relative error is
0.0160-0.0161 with this PR vs 0.0161-0.0163 on main, on transformers
5.22.1 and 5.23.0. With the kill switches set, step-0 loss matches main
exactly.
- **Engagement:** the profiler shows the new kernel 12 times per step
and no masked-SDPA kernels.
- **New CPU tests** in `tests/test_block_compile.py` (router hook
beneath a wrapper, global-layer causal verdict, long-band routing, kill
switch): 5 fail on main and pass here.
- **GPU tests:** pass on B200, A100, G4 and L4 (correctness), and on AMD
gfx1151, where the CPU suite goes from 120 to 132 passing with 0
failing. The same 10 hd512-router GPU tests fail on main and on this PR
there, because that router is disabled on ROCm.

## Not covered

- H100.
- Real weights (accuracy).
- Packed or padded batches and batch size above 1. These keep the old
masked path.
FiditeNemini pushed a commit to FiditeNemini/unsloth that referenced this pull request Nov 17, 2026
…kpoint saved-tensor hooks (unslothai#18219)

## Summary

Eager `flex_attention` inside a non-reentrant gradient checkpoint (the
default under DDP) restarts the checkpointed layer's recompute in the
middle of its own forward. Depending on what the layer saved, training
either stops with

```
torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: Recomputed values for the following tensors have different metadata than during the forward pass.
```

or keeps going with wrong input gradients and no error.

This PR builds flex's score_mod backward graph under identity
saved-tensor hooks whenever some saved-tensor hooks are active. Nothing
changes when no hooks are active.

## Root cause

When flex_attention runs eagerly (Inductor could not compile the call,
`suppress_errors` falls back, or Dynamo has marked flex as skipped), the
HOP's autograd implementation calls `create_fw_bw_graph`
(`torch/_higher_order_ops/flex_attention.py`). That function traces the
score_mod joint graph with `make_fx`, and the trace calls
`torch.autograd.grad`. Inside a non-reentrant checkpoint the
checkpoint's pack / unpack hooks are the active default hooks. The trace
packs through them and then unpacks, and the unpack is what tells the
checkpoint frame to recompute. So the layer reruns while its first
forward is still in flight, and the checkpoint compares the tensors
saved so far against a full rerun.

The traced joint graph holds no activations, so running the trace under
identity hooks (the innermost hooks win) is the correct behaviour.

The same happens without block compile. On origin/main, the tiny Gemma-2
test model with `UNSLOTH_BLOCK_COMPILE=0` and non-reentrant
checkpointing does not raise, but its LoRA gradient norm is 146.57 on
the first step and 373.30 on the second (the correct value is 0.026149).
Nothing in the run flags it.

Pure torch reproduces it with no Unsloth code. A Linear followed by
eager `flex_attention` with a softcap score_mod, on 1 x 2 x 32 x 8
inputs:

| run | layer calls during forward | input grad norm |
| --- | --- | --- |
| no checkpoint | 1 | 28.6913 |
| non-reentrant checkpoint, torch as is | 2 | 76.7271 (wrong) |
| non-reentrant checkpoint, with this fix | 1 | 28.6913 |

In Unsloth, the tiny Gemma-2 test model (head_dim 8) hits it through
per-layer block compile. The forced main flex kernel cannot lower at
head_dim below 16, so the full-attention layer keeps flex outside the
block, and that flex call runs eagerly. With reentrant checkpointing
(single GPU) the forward runs under no_grad and never builds the joint
graph, which is why only DDP failed. Real Gemma-2 (head_dim 256)
compiles flex in this configuration, so this exact trigger is specific
to the tiny model. A tiny Gemma-2 copy with head_dim 64 compiles flex
and never reaches the eager path. Any training run where flex falls back
to eager while non-reentrant checkpointing is on is exposed, though.

## Changes

- `unsloth/import_fixes.py`:
`fix_flex_attention_eager_saved_tensor_hooks` wraps
`create_fw_bw_graph`. Under active saved-tensor hooks it pushes identity
hooks for the trace. Otherwise, or if hooks are disabled, it calls
torch's function unchanged. torch 2.6 has no way to query the active
hooks (`_top_saved_tensors_default_hooks`), so there the trace always
runs under identity hooks. The fix is idempotent and does nothing on a
torch without the function.
- `unsloth/_gpu_init.py`: applies the fix at import, next to the other
torch fixes.
- `tests/test_flex_eager_checkpoint_hooks.py`: a CPU test for the
wrapper contract (wraps once, nothing pushed without hooks, identity
hooks pushed under active hooks) and a GPU test checking that eager flex
in a non-reentrant checkpoint matches the plain run, with exactly one
layer call during the forward.

## Testing

- New tests: origin/main 2 failed (`the checkpoint recomputed the layer
inside its own forward`, wrapper missing), this branch 2 passed, about 1
s of test time each.
- Tiny Gemma-2, real 2-rank DDP (torchrun, gloo, both ranks on one
B200), 2 LoRA steps: origin/main raises the CheckpointError above on
both ranks. This branch completes, and both ranks report identical loss
and grad norm.
- Same model on one GPU with non-reentrant checkpointing forced:
origin/main fails, this branch passes.
- Parity numbers and the no-change check on a model that already worked
are in the table below.

Tiny Gemma-2, non-reentrant checkpointing forced on one GPU, fp32, 2
LoRA steps (one-step loss and LoRA grad norm):

| arm | loss | grad norm |
| --- | --- | --- |
| origin/main, block compile off | 12.45302868 | 146.571 then 373.299 |
| origin/main, block compile on | CheckpointError | |
| this PR, block compile off | 12.45302868 | 0.026148804 |
| this PR, block compile on | 12.45302868 | 0.026148802 |
| this PR, reentrant, block compile off (reference) | 12.45302868 |
0.026148804 |

Block on vs off on this branch: loss delta 0, grad norm relative delta
7.1e-08, inside the unslothai#10744 tolerances (loss 1.4e-4, grad norm 1.5e-3).

No change where nothing was broken: a tiny Gemma-2 with head_dim 64
(flex compiles, both layers fully block compiled) gives bit-identical
loss and grad norm on origin/main and this branch, in bf16 and fp32. A
counting wrapper shows that `create_fw_bw_graph` runs 2 times there and
never under active hooks, so the fix stays inert. On the head_dim 8
model it engages 8 times. Reentrant checkpointing results are identical
on both trees.

### torch versions (CPU wheels): wrapper applied, CPU test, and the
pure-torch repro (Linear + eager flex with a softcap score_mod in a
non-reentrant checkpoint, input grad error vs no checkpoint)

| torch | wrapper | CPU test | repro, torch as is | repro, with this PR
|
| --- | --- | --- | --- | --- |
| 2.6.0 | applied (always under identity hooks) | passed | 2 layer calls
in the forward, error inf | 1 call, error 0 |
| 2.10.0 | applied | passed | 2 calls, NaN gradient | 1 call, error 0 |
| 2.14.1 | applied (also reached from the new `sdpa_dense_backward` call
site) | passed | CPU flex has no backward | |
| 2.15.0 | applied | passed | CPU flex has no backward | |

### AMD gfx1151 (ROCm, torch 2.11), base vs this PR

| | Linux | Windows |
| --- | --- | --- |
| new tests | 2 failed / 2 passed | 2 failed / 2 passed |
| tiny Gemma-2, flex, non-reentrant checkpoint, block compile off | base
fails (the recompute starts inside flex's FX trace); this PR matches no
checkpoint exactly | same |
| standard LoRA training cells and generate | identical | identical |

## Not covered

- NCCL across two physical GPUs (DDP ran with gloo on one card).
- A real-size model that falls back to eager flex during training.
- The numerical effect on torch 2.14 / 2.15 (CPU flex has no backward
there; no CUDA run on those versions).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants