Skip to content

Block compile: no seq_len % 8 recompile from the SDPA stride alignment check - #17864

Merged
danielhanchen merged 2 commits into
mainfrom
block-sdpa-align-guard
Nov 15, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
block-sdpa-align-guard

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Block compile no longer recompiles a block whenever the sequence length crosses a multiple of 8 (torch 2.14).

Root cause

torch 2.14 Inductor lowers SDPA through sdpa_constraint, which asks ir.is_aligned_realized_tensor whether each input's strides are 8-aligned, via guard_or_false.

The block's sequence dim is marked dynamic. So the flash backward's (B, H, L) logsumexp (strides H*L, L, 1) turns that check into a Mod(L, 8) guard. The first aligned length after an unaligned one, or the reverse, then recompiled the whole block: 10-16 s per block kind on tiny models on an L4, and 20-44 s on real ones.

Fix

Inside sdpa_constraint only, guard_or_false is answered with statically_known_true.

False is guard_or_false's documented safe answer. So a dynamic length takes the path every unaligned length already took: a stride-order check, plus copying any attention bias to an 8-aligned layout. Static shapes decide as before.

UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1 keeps torch's guard.

Two other levers were tried and rejected:

  • Marking the length unbacked removes the block recompile, but hits a data-dependent branch in a zoo attention patch, which then recompiles on % 8 by itself.
  • maybe_mark_dynamic(min=, max=) exists only on torch 2.15, which does not have this recompile.

Results

  • New test: test_block_does_not_recompile_per_length_mod_8 runs Qwen3 at lengths 517 / 520 / 523 / 528. It sees a % 8 recompile with torch's guard kept and none with this change.
  • Block compile test files: 163 pass on transformers 5.23 and 151 on 4.57.6.
  • Random lengths 511-1025 (B200, correctness only): the % 8 recompile is gone for Llama, Mistral, OLMoE, Qwen2.5-VL, Qwen3, Qwen3-MoE, SmolLM2 4-bit, Qwen3.5 and Gemma4. Each block type now compiles once.
  • Census, transformers 4.57.6 and 5.23.0: no new graph breaks, no newly disengaged models, no new data-dependent errors.
  • fp32 parity: passes. The largest gradient-norm gap is 1.6e-4, against the 1.5e-3 limit.

Colab L4, torch 2.14.1, transformers 5.23.0, 30 steps at random lengths in 511-1025. Fresh process and caches per arm; guard kept x4 vs this change x3. Two guard-kept runs varied by up to 4.5% (the noise check).

Model First 12 steps, guard kept / this PR Steady ms per step
Qwen3 35.1 / 23.4 s 23 / 22
Qwen3-MoE 51.3 / 35.2 s 26 / 26
Qwen3.5 (GDN) 166.0 / 153.1 s 39 / 39
Qwen2.5-VL 32.9 / 24.2 s 38 / 38
SmolLM2 4-bit 32.9 / 22.7 s 133 / 133

Peak memory is unchanged, within 2 MiB.

…t check

torch 2.14 Inductor lowers SDPA through sdpa_constraint, which asks
ir.is_aligned_realized_tensor whether each input's strides are 8-aligned via
guard_or_false. With the block's sequence dim marked dynamic, the flash
backward's (B, H, L) logsumexp (strides H*L, L, 1) turns that into a
Mod(L, 8) guard, so the first aligned length after an unaligned one (or the
reverse) recompiled the whole block: 10-16 s per block kind on tiny models
on an L4, 20-44 s on real ones.

Inside sdpa_constraint only, guard_or_false is answered with
statically_known_true. False is guard_or_false's documented safe answer, so a
dynamic length takes the path every unaligned length already took (a
stride-order check; an attention bias is copied to an 8-aligned layout).
Static shapes decide as before. UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1 keeps the
torch guard.

Colab L4, torch 2.14.1, transformers 5.23.0, 30 steps at random lengths in
511-1025, fresh process and caches per arm, guard kept x4 vs dropped x3:
first 12 steps 35.1 -> 23.4 s (Qwen3), 51.3 -> 35.2 s (Qwen3-MoE),
32.9 -> 24.2 s (Qwen2.5-VL), 32.9 -> 22.7 s (SmolLM2 4-bit),
166.0 -> 153.1 s (Qwen3.5); steady step time and peak memory unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-15T18:17:33.007801Z 52f10c6 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. 👍

Reviewed commit: 52f10c603a

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

[skip ci]
@danielhanchen
danielhanchen merged commit 979b204 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the block-sdpa-align-guard branch November 15, 2026 21:08
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 19, 2026
…SDPA backward on torch < 2.14 (Gemma 4 unaligned attn_bias) (unslothai#18462)

## 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

unslothai#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 unslothai#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).
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