Repository navigation
Block compile: keep torch's alignment guard for the memory-efficient SDPA backward on torch < 2.14 (Gemma 4 unaligned attn_bias) - #18462
Merged
Conversation
…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.
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. You're on a roll. 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". |
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.
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.
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_backwardinside the compiled decoder block, and its form depends onseq_len % 8:attn_bias is not correctly aligned (strideH). attn_bias.stride(1) = S*Sattn_bias is not correctly aligned (strideM). attn_bias.stride(2) = SCUDA error: misaligned addressPadded 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_falsewithstatically_known_trueinsidesdpa_constraint, on every torch version, to stop aseq_len % 8recompile 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 aMax(1, ...)that sympy cannot reduce. Without the guard, the backward's bias falls through torequire_stride_order. That call copies the bias densely as(B, H, S, S)with stridesS*SandS, 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:_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.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 mechanismtag_compile_cachealready uses.UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1still keeps every guard.Evidence
Tiny random Gemma-4 built from the real
gemma-4-26B-A4B-itconfig (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.UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1gemma4_unified(gemma-4-12B layout, LoRA 16-bit, transformers 5.23.0) at lengths 37, 38 and 36.UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1passed 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.tests/test_block_sdpa_efficient_backward_guard.py.% 8recompile. On main this test fails withattn_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.test_gemma4_long_band_past_int32_keeps_the_plain_route,test_block_does_not_recompile_per_length_mod_8[torch_guard]andtest_disable_unless_decode_keeps_original_traceable_on_old_torch.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.% 8length guard is added.Not covered
device-side assert triggeredreported for gemma-4-12B LoRA is not reproduced. The 12B layout gives the same three alignment errors on main and trains with this PR.torch.version.hipkeeps the current behaviour).