Skip to content

Block compile: keep torch's alignment guard for the memory-efficient SDPA backward on torch < 2.14 (Gemma 4 unaligned attn_bias) - #18462

Merged
danielhanchen merged 2 commits into
mainfrom
fix/efficient-backward-keeps-align-guard
Nov 19, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix/efficient-backward-keeps-align-guard

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Problem

Since 2026.11.5, Gemma-4 LoRA and QLoRA training fails on the first step on CUDA torch < 2.14 whenever a padded batch has a length that is not a multiple of 8. The error comes from aten._scaled_dot_product_efficient_attention_backward inside the compiled decoder block, and its form depends on seq_len % 8:

padded length error
odd (8191, 37) attn_bias is not correctly aligned (strideH). attn_bias.stride(1) = S*S
2 mod 4 (5858, 38) attn_bias is not correctly aligned (strideM). attn_bias.stride(2) = S
4 mod 8 (36) CUDA error: misaligned address
multiple of 8 (40) trains

Padded batches send every Gemma-4 layer to masked memory-efficient SDPA (head dims 256 and 512, so flash cannot run), so any Studio dataset with mixed lengths hits this. ROCm is not affected.

Root cause

#17864 answers Inductor's guard_or_false with statically_known_true inside sdpa_constraint, on every torch version, to stop a seq_len % 8 recompile on torch 2.14.

SDPA gives the mask an aligned layout: it pads the last dim to a multiple of 8, slices it back, and expands it over heads, so the strides are S * pad8(S), 0, pad8(S), 1. These strides are aligned at every length, but only torch's guard proves it, because the stride expression has a Max(1, ...) that sympy cannot reduce. Without the guard, the backward's bias falls through to require_stride_order. That call copies the bias densely as (B, H, S, S) with strides S*S and S, which the memory-efficient backward on torch < 2.14 rejects. The generated backward shows this directly: empty_strided_cuda((s43, 4, s29, s29), (4*s29*s29, s29*s29, s29, 1)) is fed to _scaled_dot_product_efficient_attention_backward.

Fix

unsloth/models/_block_compile.py, in _sdpa_alignment_without_guard:

  1. On CUDA torch < 2.14, the memory-efficient backward ops (_scaled_dot_product_efficient_attention_backward, _efficient_attention_backward) keep torch's guard. For the padded layout the guard is always true, so it never recompiles. Flash, the efficient forward and every other SDPA op still skip it. Torch 2.14+ and ROCm are unchanged.
  2. The compile cache key gets the tag unsloth/efficient-backward-guard. The FX graph and AOT autograd cache keys do not see this lowering change, so without the tag a warm cache from 2026.11.5 / 2026.11.6 keeps serving the faulting backward. This is the same mechanism tag_compile_cache already uses.

UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1 still keeps every guard.

Evidence

Tiny random Gemma-4 built from the real gemma-4-26B-A4B-it config (2 layers, head_dim 256 sliding and 512 global, MoE and dense variants), FastModel, LoRA r=8, use_gradient_checkpointing="unsloth", batch of 2 right-padded rows, torch 2.10.0+cu130, transformers 5.17.0. Every arm uses its own fresh Inductor cache.

arm len 37 len 38 len 36 len 40
2026.11.4 (before #17864) pass pass pass
2026.11.6 strideH strideM misaligned address
main strideH strideM misaligned address pass
main, UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1 pass pass pass
this PR pass pass pass pass
  • Numerics: this PR gives the same step-0 loss and grad norm as main with the guard kept, to every printed digit, at 37, 38 and 36. At length 40, where main already ran, it matches main exactly (loss 12.594720, grad norm 4.572537). At length 37 the step-0 loss also equals 2026.11.4 (12.586991).
  • QLoRA, dense and the 12B layout: these fail on main and pass here: 4-bit at length 37, the dense (non-MoE) variant at length 38, and a tiny gemma4_unified (gemma-4-12B layout, LoRA 16-bit, transformers 5.23.0) at lengths 37, 38 and 36.
  • Warm cache: main and then this PR ran on one shared Inductor cache directory. Without the cache tag, this PR still failed with main's strideH error because it was served main's cached backward. With the tag it passes.
  • Colab L4 (sm_89), torch 2.10.0+cu128:
    • 2026.11.6 and main fail with strideH, strideM and misaligned address at lengths 37, 38 and 36.
    • 2026.11.4 passes at 37.
    • This PR passes at 37 (four runs, identical numbers), 38, 36 and 40, and with QLoRA at 37. It also passes right after failing main runs on the same machine.
    • The new test file passes on the fix tree and its GPU test fails on main.
    • Main with only UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1 passed on a clean VM, but failed when a failing main run had happened earlier on the same VM, so the env alone is not a reliable workaround there.
  • torch 2.15.0 (transformers 5.23.0): main and this PR both pass at lengths 37 and 36, with identical loss and grad norm, because the gate is off.
  • New tests: tests/test_block_sdpa_efficient_backward_guard.py.
    • CPU: the version and ROCm gate, the efficient backward keeping torch's guard while flash and the efficient forward do not, the cache tag being added once, and the env kill switch.
    • GPU: a compiled Qwen3 layer trains on right-padded batches at every length 9 to 17 in float32. It must match the stock layer (loss rtol 1e-4, gradient relative error 1e-3) with no % 8 recompile. On main this test fails with attn_bias is not correctly aligned (strideH). attn_bias.stride(1) = 81, and it passes with this PR.
  • tests/test_block_compile.py: main and this PR have the same results.
    • On B200 with torch 2.10.0, including the GPU tests: 78 pass and the same 3 tests fail on both. These are test_gemma4_long_band_past_int32_keeps_the_plain_route, test_block_does_not_recompile_per_length_mod_8[torch_guard] and test_disable_unless_decode_keeps_original_traceable_on_old_torch.
    • CPU only, torch 2.14.1: 69 pass on both.

Speed (Colab L4, torch 2.10.0+cu128)

Main vs this PR, right-padded LoRA batches, use_gradient_checkpointing="unsloth", 4 runs per arm interleaved after a main / main pair, each with fresh compile caches. Step time is the median of steps 5 to 34.

gemma-4-E2B QLoRA, batch 2 main this PR
Step time, length 1024 1190.8 ms (1189.3-1195.3) 1178.8 ms (1178.1-1186.2)
Step time, length 2048 2727.8 ms (2724.7-2728.9) 2694.7 ms (2693.7-2694.9)
First step (compile) 196.9 s 196.6 s
Peak memory, 1024 / 2048 8.56 / 9.25 GB 8.56 / 9.25 GB
  • Not slower: about 1% faster at 2048 (the arms' ranges do not overlap; main vs main spread 0.16%), same compile time and memory.
  • Recompiles are identical in both arms (14 graphs, 22 recompile events), and no % 8 length guard is added.
  • On a tiny Gemma-4 with the real 256 / 512 head dims, peak memory at 2048 drops from 0.883 to 0.789 GB.
  • The new cache tag forces one recompile when a cache warmed by an older version is reused; on L4 that first step was not measurably slower (183.1 vs 182.6 s on E2B).
  • Only lengths that are multiples of 8 were timed, since main fails at other lengths.

Not covered

  • Real Gemma-4 weights. The bug is in how the attention bias is laid out, so random weights reproduce it.
  • The device-side assert triggered reported for gemma-4-12B LoRA is not reproduced. The 12B layout gives the same three alignment errors on main and trains with this PR.
  • ROCm: AMD gfx1151 run pending (torch.version.hip keeps the current behaviour).

…SDPA backward on torch < 2.14

Gemma-4 LoRA / QLoRA training on padded batches failed on the first step on
CUDA torch < 2.14 (seen on torch 2.10, sm_89 and sm_100) with
`attn_bias is not correctly aligned (strideH / strideM)` or
`CUDA error: misaligned address` in
aten._scaled_dot_product_efficient_attention_backward, whenever the padded
length was not a multiple of 8.

Root cause: #17864 answers `guard_or_false` with `statically_known_true`
inside Inductor's sdpa_constraint on every torch version. The padded mask
layout SDPA gives the bias (pad to 8, slice, expand over heads) is aligned at
every length, but only torch's guard proves it. Without it the backward's
bias falls through to require_stride_order, which copies it densely as
(B, H, S, S) with strides S*S and S, and the kernel on torch < 2.14 rejects
that layout.

The memory-efficient backward now keeps torch's guard on CUDA torch < 2.14.
The guard is a tautology for the padded layout, so it adds no recompile.
Flash and every other SDPA op still skip it, and torch 2.14+ and ROCm are
unchanged. The compile cache key gets a tag so graphs cached by 2026.11.5 /
2026.11.6 with the dense bias are not served again.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T12:00:11.196819Z dea5420 Manual request
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: dea54205dc

ℹ️ 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 0389bd6 into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the fix/efficient-backward-keeps-align-guard branch November 19, 2026 15:10
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Nov 20, 2026
…qa floor, block SDPA cache tag (unslothai#18631)

Follow-up fixes for unslothai#18488, unslothai#18453, unslothai#18462, found while re-checking the
PRs merged on 2026-11-19. One commit per fix; every fix has a test that
fails on main and passes here.

| Fix | Follows up | Severity |
|---|---|---|
| Attention dispatch: automatic saved attention only inside Unsloth's
checkpoint | unslothai#18488 | P2 |
| ROCm SDPA self-check: no enable_gqa on torch without it | unslothai#18453 | P2
|
| Block SDPA align guard: cache tag also under the override | unslothai#18462 |
P2 |

## Tests (this branch vs main `54af93780b`, CPU)

- New and changed tests: main 8 failed / 16 passed, this branch 24
passed. Each test loads the code of its own tree.
- Neighbouring suites on this branch: attention dispatch, ROCm SDPA
check and block SDPA guard suites: 61 passed, 5 skipped.
- `prepush_gate.py` passes.

## Attention dispatch: automatic saved attention only inside Unsloth's
checkpoint (follows up unslothai#18488)

#### Summary

Follow-up to unslothai#18488. With `UNSLOTH_GC_SAVE_ATTENTION` unset, automatic
saved attention now routes a long training call only where a
saved-attention frame can exist. That means under Unsloth's smart
checkpoint (`use_gradient_checkpointing = "unsloth"`) and, when the call
is traced, only inside Unsloth's own compiled block.

#### What broke

unslothai#18488 routes every unpacked SDPA training call at or above the
threshold through `unsloth_zoo.saved_attention.saved_attention_call`.
The zoo creates frames only inside `UnslothCheckpointFunction` (zoo
`gradient_checkpointing.py:2074`). With `use_gradient_checkpointing =
True` or `False`, `apply_unsloth_gradient_checkpointing` unpatches it,
so no frame ever exists. `saved_attention_call` is
`@torch.compiler.disable`d and with no frame it just runs the plain
call. Inside a compiled decoder block (per-block compile is on by
default for FastLanguageModel on torch >= 2.11), each long attention
call therefore becomes a graph break that saves nothing. Under a user's
`torch.compile(..., fullgraph=True)` it raises `Unsupported: Skip
calling torch.compiler.disable()'d function`.

This only happens where zoo turns on automatic mode: T4 and A100 from 8K
tokens, L4 from 16K.

#### Repro (CPU, automatic mode simulated with a threshold of 16,
32-token call, no smart checkpoint)

| arm | default compile | `fullgraph=True` |
|---|---|---|
| automatic mode off (before unslothai#18488) | 0 graph breaks | compiles |
| main | 3 graph break records (`Skip calling torch.compiler.disable()'d
function`), no frame active | `Unsupported` |
| this branch | 0 graph breaks | compiles |

#### Fix

`_auto_saves_attention` now also requires
`_saved_attention_frames_possible()`:

- `torch.utils.checkpoint.CheckpointFunction` is
`UnslothCheckpointFunction`. Dynamo cannot read a Function class's name,
so this read goes through `_constant_probe`. The patch is installed at
`get_peft_model` / load time, before any trace.
- When traced, `unsloth.models._block_compile._IN_COMPILED_REGION[0]`
must be set. That flag marks Unsloth's own block (`fullgraph=False`,
where a break is legal) and not a user's compile. zoo's sequence tiling
reads the same flag.

- In automatic mode the setting must still be `auto` when the call is
made. `UNSLOTH_GC_SAVE_ATTENTION=0` set after `import unsloth` stops
zoo's frames (`new_saved_attention_frame`), but before this change it
did not stop the routing, so it still produced a graph break per layer
inside Unsloth's own block.

The explicit `=1` / `offload` setting (min_seq None) is unchanged.

#### Tests

New `tests/test_attention_dispatch_saved_attention_scope.py` (CPU):
- automatic mode routes only under the smart checkpoint;
- a user's compile has 0 graph breaks with and without the smart
checkpoint, and `fullgraph=True` compiles;
- inside Unsloth's block under the smart checkpoint the call is still
routed;
- the explicit setting still routes;
- `UNSLOTH_GC_SAVE_ATTENTION=0` / `false` set after import stops routing
and leaves 0 graph breaks inside Unsloth's block.

`tests/test_attention_dispatch_saved_attention.py`: the two
automatic-mode routing tests now install `UnslothCheckpointFunction`, as
a real "unsloth" run does.

Command (per worktree, unsloth_zoo main on `PYTHONPATH`): `python -m
pytest -o addopts= -m "not server and not native_mxc" -p
no:cacheprovider -q
tests/test_attention_dispatch_saved_attention_scope.py
tests/test_attention_dispatch_saved_attention.py`. Each arm imports its
own tree.

| arm | result |
|---|---|
| main (635532f) | 6 failed, 14 passed |
| this branch | 20 passed |

Wider suites (`tests/*attention*.py`, `tests/test_sdpa*.py`,
`tests/utils/test_rocm_sdpa_check.py`): main 2 failed / 255 passed / 302
skipped. This branch: 2 failed / 261 passed / 302 skipped. The same two
failures in `test_flash_attention_sub_config_fallback.py` show up on
main.

#### Not proven here

- No GPU run. Step time for `use_gradient_checkpointing = True` at 8K on
an A100 or T4 (main vs this branch) needs a real card. The
smart-checkpoint path is unchanged, so unslothai#18488's measured gains still
apply.
- Layers that "unsloth" checkpointing leaves unwrapped (frozen bottom
layers skipped by unslothai#18442) still reach the routed call with no frame.
This change does not cover them.

## ROCm SDPA self-check: no enable_gqa on torch without it (follows up
unslothai#18453)

#### Summary

Follow-up to unslothai#18453. On torch 2.4, the declared floor, the ROCm SDPA
self-check refused AOTriton flash for every Unsloth attention call on an
RDNA GPU. The kernel was never the cause: the check sent an argument
that torch 2.4 does not have.

#### What broke

The flash child in `unsloth/utils/rocm_sdpa_check.py` runs a
`segments_gqa` case that calls `F.scaled_dot_product_attention(...,
enable_gqa=True)`. torch added `enable_gqa` in 2.5. On 2.4 the call
raises `TypeError: scaled_dot_product_attention() got an unexpected
keyword argument 'enable_gqa'`. The child records any exception other
than "No available kernel" or out of memory as a failed kernel case, so
the report says `ok: false` and `rocm_sdpa_verdict` refuses flash for
that device. Unsloth itself never passes `enable_gqa` when SDPA lacks it
(`SDPA_HAS_GQA` in `attention_dispatch.py`), so no real call can reach
that layout there.

#### Repro (CPU)

The real child script runs in a subprocess. CUDA calls are mapped to CPU
(torch's CPU flash kernel, which is correct), and
`F.scaled_dot_product_attention` is replaced by one that rejects
`enable_gqa`, as torch 2.4's operator does.

| arm | flash child report |
|---|---|
| main (635532f) | `ok: false`, ran 8, every failure is `segments_gqa
...: unexpected keyword argument 'enable_gqa'` |
| this branch | `ok: true`, ran 4 (expanded K / V segments, fp16 and
bf16, head dims 64 and 128) |

#### Fix

When `enable_gqa` is not in `F.scaled_dot_product_attention.__doc__`,
the child drops the `segments_gqa` case. That is the same test
`attention_dispatch` uses. The expanded K / V and masked cases still
run, so a broken kernel is still refused.

#### Tests

New `tests/utils/test_rocm_sdpa_check_no_gqa.py` (CPU). Command (per
worktree): `python -m pytest -o addopts= -m "not server and not
native_mxc" -p no:cacheprovider -q
tests/utils/test_rocm_sdpa_check_no_gqa.py
tests/utils/test_rocm_sdpa_check.py`. Each arm imports its own tree.

| arm | result |
|---|---|
| main | 1 failed, 24 passed, 2 skipped |
| this branch | 25 passed, 2 skipped |

#### Not proven here

- No ROCm torch 2.4 hardware run, and no claim about which RDNA archs
torch 2.4 offers AOTriton flash on. Where it does not offer flash, this
change makes no difference.
- torch >= 2.5 keeps the `segments_gqa` case unchanged.

## Block SDPA align guard: cache tag also under the override (follows up
unslothai#18462)

#### What broke

unslothai#18462 adds the cache tag `unsloth/efficient-backward-guard` so that
graphs compiled without the efficient-backward guard are not served
again. The patched SDPA lowering is not part of the FX / AOT cache key.
`UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1` returned before adding that tag.

On CUDA torch < 2.14, a run with the override therefore has the same
cache key as a run of the same Unsloth version from before the tag
existed. The version string is 2026.11.7 both before and after unslothai#18462.
That older run compiled the efficient backward without the guard. A user
who set the override as the workaround for the `attn_bias is not
correctly aligned` fault, and kept it after updating, keeps being served
the faulting backward from a warm cache. The PR's own evidence notes the
override was not a reliable workaround once a failing run had warmed the
cache.

#### Fix

`unsloth/models/_block_compile.py`, `_sdpa_alignment_without_guard`:
under the override on an affected torch, add the same cache tag before
returning. The lowering stays stock as before. Torch 2.14+ and ROCm are
unchanged.

#### Tests

New `tests/test_block_sdpa_align_guard_override_cache_tag.py` (CPU, no
compile): with the override set, the lowering must stay untouched. The
tag must be added exactly once on an affected torch and not on 2.14+.
The test loads `_block_compile.py` from its own tree and asserts it.

| Arm | Result |
|---|---|
| main | 1 failed (`torch_lt_2_14`), 2 passed |
| this branch | 3 passed on torch 2.14.1; on torch 2.4.1 (no
`cache_key_tag`) the tag tests skip with that reason |

`tests/test_block_sdpa_efficient_backward_guard.py` passes on both arms.

#### Not covered

No warm-cache GPU run of the fault itself.

## Not proven here

Step time and memory of long-sequence SFT with and without automatic
saved attention; ROCm hardware (gfx1151 / gfx942) for the self-check;
torch 2.14 on GPU for the align guard.
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