Repository navigation
ROCm attention: keep AOTriton SDPA kernels that fail a per-GPU self-check out of Unsloth's attention - #18453
Conversation
…heck out of Unsloth's attention Unsloth sets TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1, so on RDNA archs torch offers AOTriton's flash / memory-efficient kernels to every SDPA call. Since #12740 (per-segment packed SDPA) and #14158 (expanded K/V where enable_gqa would mean math), GQA training calls on ROCm reach those kernels instead of math, and on gfx1200 they fail with hipErrorInvalidValue or corrupt memory (#18403). A child process now runs the GQA shapes Unsloth sends through each backend, forward and backward, against an fp32 reference, once per GPU; a backend that errors, faults or disagrees is excluded from the dispatch's SDPA calls and GQA probes on that GPU. CDNA is trusted, CUDA is unchanged, UNSLOTH_ROCM_SDPA_CHECK=0 skips the check.
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23aa51679a
ℹ️ 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".
…tch SDPA call is guarded The AOTriton self-check runs after the model is resident, so a child that runs out of GPU or host memory (torch / HIP out of memory, MemoryError, killed by the OOM killer) no longer refuses the backend: it is kept, as before the check existed, with a one-time warning. Kernel errors, faults, wrong numbers and timeouts stay refusals. The fp32 reference is now computed one segment and head at a time (exact for the block-diagonal mask), so it needs (n, n) scores instead of (heads, T, T) plus their backward. _rerouted_sdpa (compiled plain-causal attention rerouted off xformers), the decode tail and the packed block-mask fallback called torch's SDPA directly and could still run refused kernels. They now go through the guarded scaled_dot_product_attention, and a test walks the module's AST so a new direct call fails.
|
@codex review |
|
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
## Summary `Repo tests (CPU, studio)` fails on `main` (seen on #18496, whose base already has #18490): ``` FAILED tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe E utils/test_rocm_sdpa_check.py:348: torch.cuda.is_available() E utils/test_rocm_sdpa_check.py:356: torch.cuda.is_available() ``` ## Root cause #18453 added `tests/utils/test_rocm_sdpa_check.py` with two GPU tests gated on `torch.cuda.is_available()`. `tests/_zoo_aggressive_cuda_spoof.py` patches that probe to `True` process-wide, so on a CPU runner these tests un-skip and launch the SDPA self-check children whenever they share a pytest session with the spoofing suites. The guard caught it; the ROCm change itself is unaffected. ## Changes - Both skips now gate on `has_real_cuda()` first (`not has_real_cuda() or not torch.cuda.is_available()`). `has_real_cuda()` records `torch.cuda.is_available()` before any spoof, so it stays true on a real ROCm or CUDA host, where these tests still run. ## Testing - `pytest tests/utils/test_rocm_sdpa_check.py tests/python/test_accelerator_skip_guards.py`: 48 passed, 2 skipped (the two GPU tests, on this CPU host). The guard fails on `main` with the error above.
|
Guten Tag and Hi Daniel ! I will test it the next days on my gfx1201, to convince your patch! Beautiful greetings from the Baltic Sea! |
…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.
Addresses #18403
Problem
On an RX 9060 XT (gfx1200, RDNA4), QLoRA training aborts on the first step with
HIP error: an illegal memory access. The fault shows up in whatever kernel runs next: SwiGLU, fused CE,fork_rng, the decode graphs. WithAMD_SERIALIZE_KERNEL=3the first failure ishipErrorInvalidValuefromF.scaled_dot_product_attentionin_sdpa_packed_segments. 2026.9.7 trains on the same machine. The reporters bisected it to #12740 and #14158.Root cause
unsloth/__init__.py:29setsTORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1(since #8821, already in 2026.9.7). Torch then offers AOTriton's flash and memory-efficient kernels on every arch AOTriton only lists as experimental, which is all of RDNA. Until 2026.9.7, Unsloth's GQA training calls on ROCm never reached those kernels: packed and padding-free rows ran SDPA over a dense block mask withenable_gqa=True, and only math accepts that combination.5babb22c69, 2026.10.1) runs each packed segment as its own causal call with K/V expanded on ROCm (_sdpa_packed_segments,attention_dispatch.py:1117). Torch picks AOTriton flash for that call.e6c95c292b, 2026.10.7) expands K/V wheneverenable_gqawould leave only math (_sdpa_gqa_state_now,attention_dispatch.py:907, used by the dense path at:2133and by the segment runs). On ROCm that sends masked calls to the AOTriton memory-efficient kernel. This is whyUNSLOTH_SDPA_PACKED_SEGMENTS=0stopped helping from 2026.10.7 on.Both choices are right wherever the kernels work. On gfx1200 the reporters show they do not. Upstream has matching RDNA4 reports for these kernels: pytorch#201476 (gfx1201 memory-efficient SDPA wrong in fp32), ROCm/TheRock#10001 (gfx120X memory-efficient grads fail tolerance), and ROCm/TheRock#10054 (gfx1201 FLASH and EFFICIENT fail with
hipErrorInvalidImage).Fix
The new
unsloth/utils/rocm_sdpa_check.pychecks each AOTriton backend once per GPU:AMD_SERIALIZE_KERNEL=3, because a fault poisons the HIP context. Flash and memory-efficient each get their own child, and the two run side by side.enable_gqa, and a boolean block mask. It covers fp16 and bf16, head dims 64 and 128, and segments of 1300, 748 and 37 tokens.attention_dispatchon that GPU: packed segments, the dense path, decode, and the GQA probe that picks betweenenable_gqaand expanded K/V. The remaining backends run, down to math, which is what 2026.9.7 used.Scope:
sdpa_kernel([FLASH])), its own policy is kept.UNSLOTH_ROCM_SDPA_CHECK=0skips the check and trusts torch, which is the current behaviour.rocm_sdpa_verdict(device_index)is exported fromattention_dispatchso users can see what the check decided.Evidence
Flip test.
tests/utils/test_rocm_sdpa_check.pyfakes ROCm on CPU tensors.Existing attention suites. On CPU,
test_sdpa_packed_segments,test_attention_native_routing,test_attention_training_no_cudnn,test_attention_masks,test_attention_rerouted_sdpa, mixed devices, fp32 routing, single row cache, eval backward and bidirectional: 215 passed, 27 skipped. On B200 with-m "gpu or not gpu": 119 passed.The child on a GPU whose kernels are correct (B200). Flash and memory-efficient pass all 8 cases each, in 5.7 s wall. Two negative controls:
AMD gfx1151, Linux, torch 2.11.0+rocm7.13. Tiny Qwen3 with head dim 128 and 8/2 heads, the reporters' settings, run on main and on this branch: fp16, 4-bit LoRA, standard checkpointing, batch 2, padding-free,
train_on_responses_only, about 2k-token rows.AMD_SERIALIZE_KERNEL=3.On gfx1151 the check takes 3.1 s. A kernel matrix at the reporters' shape (32/8 heads, head dim 128, 2048 tokens, fp16 and bf16, forward and backward,
AMD_SERIALIZE_KERNEL=3) shows flash and memory-efficient correct on every layout they accept (AMD CI run 44502291477).gfx1151 does not reproduce the gfx1200 fault, so this run shows two things: the fix costs nothing where the kernels work, and the refusal path works on real AMD hardware. It does not prove the fix on gfx1200.
What gfx1200 users should check
Unsloth: ROCm gfx1200 0: AOTriton ... attention failed a self-check.from unsloth.utils.attention_dispatch import rocm_sdpa_verdict; print(rocm_sdpa_verdict(0))after loading a model.Not covered
attention_dispatch(hf_packed_attention, transformers' own sdpa integration) keep the current behaviour.