Repository navigation
Block compile: no seq_len % 8 recompile from the SDPA stride alignment check - #17864
Merged
Merged
Conversation
…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.
Member
Author
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 asksir.is_aligned_realized_tensorwhether each input's strides are 8-aligned, viaguard_or_false.The block's sequence dim is marked dynamic. So the flash backward's
(B, H, L)logsumexp (stridesH*L, L, 1) turns that check into aMod(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_constraintonly,guard_or_falseis answered withstatically_known_true.Falseisguard_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=1keeps torch's guard.Two other levers were tried and rejected:
% 8by itself.maybe_mark_dynamic(min=, max=)exists only on torch 2.15, which does not have this recompile.Results
test_block_does_not_recompile_per_length_mod_8runs Qwen3 at lengths 517 / 520 / 523 / 528. It sees a% 8recompile with torch's guard kept and none with this change.% 8recompile 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.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).
Peak memory is unchanged, within 2 MiB.